1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
|
/*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import static org.openecomp.sdc.be.utils.TypeUtils.setField;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fj.data.Either;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ModelOperationExceptionSupplier;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
public abstract class ToscaElementOperation extends BaseOperation {
private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}";
private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}";
private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ";
private static final String FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to get creator vertex with label {} of tosca element vertex {} on graph. Status is {}. ";
private static final Gson gson = new Gson();
private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName());
@Autowired
protected CategoryOperation categoryOperation;
@Autowired
protected ModelOperation modelOperation;
public static DataTypeDefinition createDataType(final String dataTypeName) {
final DataTypeDefinition dataType = new DataTypeDefinition();
dataType.setName(dataTypeName);
return dataType;
}
public static DataTypeDefinition createDataTypeDefinitionWithName(final Entry<String, Object> attributeNameValue) {
final Map<String, Object> attributeMap = (Map<String, Object>) attributeNameValue.getValue();
final DataTypeDefinition dataType = createDataType(attributeNameValue.getKey());
setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, dataType::setDescription);
setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM_NAME, dataType::setDerivedFromName);
// TODO - find the way to set the properties
// CommonImportManager.setProperties(attributeMap, dataType::setProperties);
final Object derivedFrom = attributeMap.get(JsonPresentationFields.DERIVED_FROM.getPresentation());
if (derivedFrom instanceof Map) {
final Map<String, Object> derivedFromMap = (Map<String, Object>) derivedFrom;
final DataTypeDefinition parentDataTypeDataDefinition = new DataTypeDefinition();
parentDataTypeDataDefinition.setName((String) derivedFromMap.get(JsonPresentationFields.NAME.getPresentation()));
parentDataTypeDataDefinition.setUniqueId((String) derivedFromMap.get(JsonPresentationFields.UNIQUE_ID.getPresentation()));
parentDataTypeDataDefinition.setCreationTime((Long) derivedFromMap.get(JsonPresentationFields.CREATION_TIME.getPresentation()));
parentDataTypeDataDefinition.setModificationTime((Long) derivedFromMap.get(JsonPresentationFields.MODIFICATION_TIME.getPresentation()));
dataType.setDerivedFrom(parentDataTypeDataDefinition);
}
return dataType;
}
protected Gson getGson() {
return gson;
}
protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType,
JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId);
VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResponse = janusGraphDao.getByCriteria(vertexType, propertiesToMatch, parseFlag);
if (getResponse.isRight()) {
log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()));
}
List<GraphVertex> componentList = getResponse.left().value();
if (componentList.isEmpty()) {
log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
GraphVertex vertexG = componentList.get(0);
return Either.left(vertexG);
}
public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
return getToscaElement(uniqueId, new ComponentParametersView());
}
public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) {
Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) {
// component already marked for delete
} else {
componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, JanusGraphOperationStatus> updateNode = janusGraphDao.updateVertex(componentToDelete);
StorageOperationStatus updateComponent;
if (updateNode.isRight()) {
log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
updateComponent = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateNode.right().value());
return Either.right(updateComponent);
}
}
return Either.left(componentToDelete);
}
/**
* Performs a shadow clone of previousToscaElement
*
* @param previousToscaElement
* @param nextToscaElement
* @param user
* @return
*/
public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement,
GraphVertex user) {
Either<GraphVertex, StorageOperationStatus> result = null;
GraphVertex createdToscaElementVertex = null;
JanusGraphOperationStatus status;
Either<GraphVertex, JanusGraphOperationStatus> createNextVersionRes = janusGraphDao.createVertex(nextToscaElement);
if (createNextVersionRes.isRight()) {
status = createNextVersionRes.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ",
previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (result == null) {
createdToscaElementVertex = createNextVersionRes.left().value();
final Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
if (status != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.STATE,
user.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (result == null) {
status = janusGraphDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.LAST_MODIFIER,
user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (result == null) {
Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao
.getParentVertex(previousToscaElement, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
if (creatorVertexRes.isRight()) {
status = creatorVertexRes.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS,
EdgeLabelEnum.CREATOR, nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
status = janusGraphDao
.createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR,
new HashMap<>());
if (status != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, EdgeLabelEnum.CREATOR,
user.getUniqueId(), nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (result == null) {
Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT);
while (edgesToCopyIter.hasNext()) {
Edge currEdge = edgesToCopyIter.next();
Vertex currVertex = currEdge.inVertex();
status = janusGraphDao
.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
if (status != JanusGraphOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ",
currEdge.label(), createdToscaElementVertex.getUniqueId(), currVertex.property(GraphPropertyEnum.LABEL.getProperty()),
status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
break;
}
}
}
if (result == null) {
result = Either.left(createdToscaElementVertex);
} else {
CommonUtility
.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(),
previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
}
return result;
}
protected JanusGraphOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
return parentVertex.right().value();
}
GraphVertex userV = parentVertex.left().value();
String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
toscaElement.setLastUpdaterUserId(userId);
toscaElement.setLastUpdaterFullName(buildFullName(userV));
return JanusGraphOperationStatus.OK;
}
public String buildFullName(GraphVertex userV) {
String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
if (fullName == null) {
fullName = "";
} else {
fullName = fullName + " ";
}
String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME);
if (lastName != null) {
fullName += lastName;
}
return fullName;
}
protected JanusGraphOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
return parentVertex.right().value();
}
GraphVertex userV = parentVertex.left().value();
String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
toscaElement.setCreatorUserId(creatorUserId);
toscaElement.setCreatorFullName(buildFullName(userV));
return JanusGraphOperationStatus.OK;
}
protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) {
if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) {
toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName()));
}
if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
}
LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
if (lifecycleStateEnum == null) {
toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
}
long currentDate = System.currentTimeMillis();
if (toscaElement.getCreationDate() == null) {
toscaElement.setCreationDate(currentDate);
}
toscaElement.setLastUpdateDate(currentDate);
return toscaElement;
}
protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
if (toscaElement.isHighestVersion() == null) {
toscaElement.setHighestVersion(true);
}
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION,
toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
nodeTypeVertex
.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED));
nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.MODEL, toscaElement.getMetadataValue(JsonPresentationFields.MODEL));
toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null)
.forEach(e -> nodeTypeVertex.setJsonMetadataField(e.getKey(), e.getValue()));
nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
nodeTypeVertex.setType(toscaElement.getComponentType());
final String toscaVersion = toscaElement.getToscaVersion();
if (toscaVersion != null) {
nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.TOSCA_DEFINITIONS_VERSION, toscaVersion);
}
final Map<String, DataTypeDataDefinition> dataTypes = toscaElement.getDataTypes();
if (MapUtils.isNotEmpty(dataTypes)) {
nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.DATA_TYPES, dataTypes);
}
}
protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
// handle user
String userId = toscaElement.getCreatorUserId();
Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(userId);
if (findUser.isRight()) {
JanusGraphOperationStatus status = findUser.right().value();
log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
GraphVertex creatorVertex = findUser.left().value();
GraphVertex updaterVertex = creatorVertex;
String updaterId = toscaElement.getLastUpdaterUserId();
if (updaterId != null && !updaterId.equals(userId)) {
findUser = findUserVertex(updaterId);
if (findUser.isRight()) {
JanusGraphOperationStatus status = findUser.right().value();
log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
} else {
updaterVertex = findUser.left().value();
}
}
Map<EdgePropertyEnum, Object> props = new EnumMap<>(EdgePropertyEnum.class);
props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
JanusGraphOperationStatus result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
if (JanusGraphOperationStatus.OK != result) {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
result = janusGraphDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
EdgeLabelEnum.LAST_MODIFIER);
if (!result.equals(JanusGraphOperationStatus.OK)) {
log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(),
EdgeLabelEnum.LAST_MODIFIER);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
result = janusGraphDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
if (!result.equals(JanusGraphOperationStatus.OK)) {
log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(),
EdgeLabelEnum.CREATOR);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(result);
}
return StorageOperationStatus.OK;
}
protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
String categoryName = nodeType.getCategories().get(0).getName();
Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName,
categoryName);
if (getCategoryVertex.isRight()) {
return getCategoryVertex.right().value();
}
GraphVertex subCategoryV = getCategoryVertex.left().value();
JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
if (createEdge != JanusGraphOperationStatus.OK) {
log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName,
subCategoryV.getUniqueId());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
return StorageOperationStatus.OK;
}
protected StorageOperationStatus associateResourceMetadataToModel(final GraphVertex nodeTypeVertex, final ToscaElement nodeType) {
if (nodeType.getMetadataValue(JsonPresentationFields.MODEL) == null) {
return StorageOperationStatus.OK;
}
final String model = ((String) nodeType.getMetadataValue(JsonPresentationFields.MODEL));
final JanusGraphOperationStatus createEdge = janusGraphDao
.createEdge(getModelVertex(model), nodeTypeVertex, EdgeLabelEnum.MODEL_ELEMENT, new HashMap<>());
if (createEdge != JanusGraphOperationStatus.OK) {
log.trace("Failed to associate resource {} to model {}", nodeType.getUniqueId(), model);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
return StorageOperationStatus.OK;
}
private GraphVertex getModelVertex(final String modelName) {
log.debug("getModelVertex: fetching model {}", modelName);
final Optional<GraphVertex> modelVertexByNameOptional = modelOperation.findModelVertexByName(modelName);
if (modelVertexByNameOptional.isEmpty()) {
throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
}
return modelVertexByNameOptional.get();
}
protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) {
Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
if (category.isRight()) {
log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value());
return Either.right(category.right().value());
}
GraphVertex categoryV = category.left().value();
if (subcategoryName != null) {
Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
if (subCategory.isRight()) {
log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId,
subCategory.right().value());
return Either.right(subCategory.right().value());
}
GraphVertex subCategoryV = subCategory.left().value();
return Either.left(subCategoryV);
}
return Either.left(categoryV);
}
private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
Either<GraphVertex, StorageOperationStatus> status;
if (artifacts != null) {
artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
String uniqueId = UniqueIdBuilder
.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
if (status.isRight()) {
return status.right().value();
}
}
Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
if (toscaArtifacts != null) {
toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
String uniqueId = UniqueIdBuilder
.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
if (status.isRight()) {
return status.right().value();
}
}
Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
if (deploymentArtifacts != null) {
deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
String uniqueId = UniqueIdBuilder
.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
a.setUniqueId(uniqueId);
});
status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS,
deploymentArtifacts);
if (status.isRight()) {
return status.right().value();
}
}
return StorageOperationStatus.OK;
}
protected JanusGraphOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
JanusGraphOperationStatus status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
if (status != JanusGraphOperationStatus.OK) {
log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
return status;
}
return JanusGraphOperationStatus.OK;
}
protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
return assosiateCommonForToscaElement(nodeTypeVertex, toscaElement, null);
}
protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement,
List<GraphVertex> derivedResources) {
StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
if (associateUsers != StorageOperationStatus.OK) {
return associateUsers;
}
StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement);
if (associateArtifacts != StorageOperationStatus.OK) {
return associateArtifacts;
}
StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources);
if (associateProperties != StorageOperationStatus.OK) {
return associateProperties;
}
StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement);
if (associateAdditionaInfo != StorageOperationStatus.OK) {
return associateAdditionaInfo;
}
if (needConnectToCatalog(toscaElement)) {
StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex);
if (associateToCatalog != StorageOperationStatus.OK) {
return associateToCatalog;
}
}
return StorageOperationStatus.OK;
}
private boolean needConnectToCatalog(ToscaElement toscaElement) {
Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT);
if (isAbstract != null && isAbstract) {
return false;
}
return toscaElement.isHighestVersion();
}
private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) {
Either<GraphVertex, JanusGraphOperationStatus> catalog = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT);
if (catalog.isRight()) {
log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(catalog.right().value());
}
JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge);
}
protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType,
List<GraphVertex> derivedResources) {
// Note : currently only one derived supported!!!!
Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources,
EdgeLabelEnum.PROPERTIES);
if (dataFromDerived.isRight()) {
return dataFromDerived.right().value();
}
Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
if (properties != null) {
properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
p.setUniqueId(uid);
});
Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties);
if (eitherMerged.isRight()) {
// TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property
log.debug("property {} cannot be overriden", eitherMerged.right().value());
return StorageOperationStatus.INVALID_PROPERTY;
}
}
if (!propertiesAll.isEmpty()) {
Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES,
EdgeLabelEnum.PROPERTIES, propertiesAll);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
if (additionalInformation != null) {
Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex,
VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
}
return StorageOperationStatus.OK;
}
protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources,
EdgeLabelEnum edge) {
Map<String, T> propertiesAll = new HashMap<>();
if (derivedResources != null && !derivedResources.isEmpty()) {
for (GraphVertex derived : derivedResources) {
Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao
.getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson);
if (derivedProperties.isRight()) {
if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(derivedProperties.right().value()));
} else {
continue;
}
}
List<GraphVertex> propList = derivedProperties.left().value();
for (GraphVertex propV : propList) {
Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson();
if (propertiesFromDerived != null) {
propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId()));
propertiesAll.putAll(propertiesFromDerived);
}
}
}
}
return Either.left(propertiesAll);
}
protected JanusGraphOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS);
if (result.isLeft()) {
toscaElement.setArtifacts(result.left().value());
} else {
if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return result.right().value();
}
}
result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
if (result.isLeft()) {
toscaElement.setDeploymentArtifacts(result.left().value());
} else {
if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return result.right().value();
}
}
result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS);
if (result.isLeft()) {
toscaElement.setToscaArtifacts(result.left().value());
} else {
if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return result.right().value();
}
}
return JanusGraphOperationStatus.OK;
}
protected JanusGraphOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
Map<String, String> allVersion = new HashMap<>();
allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>();
Either<GraphVertex, JanusGraphOperationStatus> childResourceRes = janusGraphDao
.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
while (childResourceRes.isLeft()) {
GraphVertex child = childResourceRes.left().value();
allChildrenAndParants.add(child);
childResourceRes = janusGraphDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
}
JanusGraphOperationStatus operationStatus = childResourceRes.right().value();
if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
return operationStatus;
} else {
Either<GraphVertex, JanusGraphOperationStatus> parentResourceRes = janusGraphDao
.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
while (parentResourceRes.isLeft()) {
GraphVertex parent = parentResourceRes.left().value();
allChildrenAndParants.add(parent);
parentResourceRes = janusGraphDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
}
operationStatus = parentResourceRes.right().value();
if (operationStatus != JanusGraphOperationStatus.NOT_FOUND) {
return operationStatus;
} else {
allChildrenAndParants.stream().filter(vertex -> {
Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
return (isDeleted == null || !isDeleted);
}).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
toscaElement.setAllVersions(allVersion);
return JanusGraphOperationStatus.OK;
}
}
}
protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId,
Set<LifecycleStateEnum> lifecycleStates,
Set<LifecycleStateEnum> lastStateStates,
ComponentTypeEnum neededType) {
Map<GraphPropertyEnum, Object> props = null;
if (userId != null) {
props = new EnumMap<>(GraphPropertyEnum.class);
// for Designer retrieve specific user
props.put(GraphPropertyEnum.USERID, userId);
}
// in case of user id == null -> get all users by label
// for Tester and Admin retrieve all users
Either<List<GraphVertex>, JanusGraphOperationStatus> usersByCriteria = janusGraphDao
.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
if (usersByCriteria.isRight()) {
log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value()));
}
GraphVertex userV = usersByCriteria.left().value().get(0);
List<T> components = new ArrayList<>();
List<T> componentsPerUser;
final Set<String> ids = new HashSet<>();
Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao
.getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID),
EdgeLabelEnum.STATE, childrenVertecies.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
}
// get all resource with current state
if (childrenVertecies.isLeft()) {
componentsPerUser = fetchComponents(userId, lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
if (componentsPerUser != null) {
for (T comp : componentsPerUser) {
ids.add(comp.getUniqueId());
components.add(comp);
}
}
if (lastStateStates != null && !lastStateStates.isEmpty()) {
// get all resource with last state
childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch children vertices for user {} by edge {} error {}",
userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value()));
}
if (childrenVertecies.isLeft()) {
boolean isFirst;
componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType,
EdgeLabelEnum.LAST_STATE);
if (componentsPerUser != null) {
for (T comp : componentsPerUser) {
isFirst = true;
if (ids.contains(comp.getUniqueId())) {
isFirst = false;
}
if (isFirst) {
components.add(comp);
}
}
}
}
}
} // whlile users
return Either.left(components);
}
private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices,
ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
List<T> components = new ArrayList<>();
for (GraphVertex node : vertices) {
Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
while (edges.hasNext()) {
Edge edge = edges.next();
String stateStr = (String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE);
LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
if (nodeState == null) {
log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
continue;
}
//get user from edge and compare to user from followed request
JanusGraphVertex userVertex = (JanusGraphVertex) edge.outVertex();
String userIdFromEdge = (String) janusGraphDao.getProperty(userVertex, GraphPropertyEnum.USERID.getProperty());
if (lifecycleStates != null && lifecycleStates.contains(nodeState) && (userIdFromEdge.equals(userId))) {
Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED);
if (isDeleted != null && isDeleted || isArchived != null && isArchived) {
log.trace("Deleted/Archived element {}, discard", node.getUniqueId());
continue;
}
Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
if (isHighest) {
ComponentTypeEnum componentType = node.getType();
// get only latest versions
if (componentType == null) {
log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
continue;
}
if (neededType == componentType) {
switch (componentType) {
case SERVICE:
case PRODUCT:
handleNode(components, node, componentType);
break;
case RESOURCE:
Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
if (isAbtract == null || !isAbtract) {
handleNode(components, node, componentType);
} // if not abstract
break;
default:
log.debug("not supported node type {}", componentType);
break;
}// case
} // needed type
}
} // if
} // while edges
} // while resources
return components;
}
protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
if (component.isRight()) {
log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
} else {
components.add(component.left().value());
}
}
protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType,
ComponentParametersView parametersFilter) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = janusGraphDao.getVertexById(componentUid);
if (getVertexRes.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexRes.right().value()));
}
return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
}
protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType,
ComponentParametersView parametersFilter) {
log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
janusGraphDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
T toscaElement = convertToComponent(vertexComponent);
JanusGraphOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
status = setLastModifierFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
status = setCategoriesFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (!parametersFilter.isIgnoreAllVersions()) {
status = setAllVersions(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (!parametersFilter.isIgnoreCapabilities()) {
status = setCapabilitiesFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
if (!parametersFilter.isIgnoreRequirements()) {
status = setRequirementsFromGraph(vertexComponent, toscaElement);
if (status != JanusGraphOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
}
log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
return Either.left(toscaElement);
}
@SuppressWarnings("unchecked")
protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) {
ToscaElement toscaElement = null;
VertexTypeEnum label = componentV.getLabel();
switch (label) {
case NODE_TYPE:
toscaElement = new NodeType();
break;
case TOPOLOGY_TEMPLATE:
toscaElement = new TopologyTemplate();
break;
default:
log.debug("Not supported tosca type {}", label);
break;
}
if (toscaElement != null) {
final Map<String, Object> jsonMetada = componentV.getMetadataJson();
if (MapUtils.isNotEmpty(jsonMetada)) {
toscaElement.setMetadata(jsonMetada);
final Object toscaVersion = jsonMetada.get(ToscaTagNamesEnum.TOSCA_VERSION.getElementName());
if (toscaVersion != null) {
toscaElement.setToscaVersion((String) toscaVersion);
}
final Object dataTypes = jsonMetada.get(ToscaTagNamesEnum.DATA_TYPES.getElementName());
if (dataTypes != null) {
final Map<String, DataTypeDataDefinition> dataTypeDefinitionMap = new HashMap<>();
final Map<String, Object> toscaAttributes = (Map<String, Object>) dataTypes;
for (final Entry<String, Object> attributeNameValue : toscaAttributes.entrySet()) {
final Object value = attributeNameValue.getValue();
final String key = attributeNameValue.getKey();
if (value instanceof Map) {
final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
dataTypeDefinitionMap.put(dataTypeDefinition.getName(), dataTypeDefinition);
} else {
dataTypeDefinitionMap.put(key, createDataType(String.valueOf(value)));
}
}
toscaElement.setDataTypes(dataTypeDefinitionMap);
}
}
}
return (T) toscaElement;
}
protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
List<CategoryDefinition> categories = new ArrayList<>();
SubCategoryDefinition subcategory;
Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
childVertex.right().value());
return childVertex.right().value();
}
Vertex subCategoryV = childVertex.left().value();
String subCategoryNormalizedName = (String) subCategoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
catalogComponent.setSubCategoryNormalizedName(subCategoryNormalizedName);
subcategory = new SubCategoryDefinition();
subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
subcategory.setNormalizedName(subCategoryNormalizedName);
subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
Type listTypeSubcat = new TypeToken<List<MetadataKeyDataDefinition>>() {
}.getType();
List<MetadataKeyDataDefinition> metadataKeys = subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
.fromJson((String) subCategoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeSubcat)
: Collections.emptyList();
subcategory.setMetadataKeys(metadataKeys);
Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
Vertex categoryV = parentVertex.left().value();
String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
CategoryDefinition category = new CategoryDefinition();
category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
category.setNormalizedName(categoryNormalizedName);
category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
category.addSubCategory(subcategory);
categories.add(category);
catalogComponent.setCategories(categories);
return JanusGraphOperationStatus.OK;
}
protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
List<CategoryDefinition> categories = new ArrayList<>();
Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(),
childVertex.right().value());
return childVertex.right().value();
}
Vertex categoryV = childVertex.left().value();
String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
catalogComponent.setCategoryNormalizedName(categoryNormalizedName);
CategoryDefinition category = new CategoryDefinition();
category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value());
category.setNormalizedName(categoryNormalizedName);
category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value());
category.setUseServiceSubstitutionForNestedServices(
(Boolean) categoryV.property(GraphPropertyEnum.USE_SUBSTITUTION_FOR_NESTED_SERVICES.getProperty()).orElse(false));
Type listTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
}.getType();
List<MetadataKeyDataDefinition> metadataKeys = categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).isPresent() ? getGson()
.fromJson((String) categoryV.property(GraphPropertyEnum.METADATA_KEYS.getProperty()).value(), listTypeCat) : Collections.emptyList();
category.setMetadataKeys(metadataKeys);
categories.add(category);
catalogComponent.setCategories(categories);
return JanusGraphOperationStatus.OK;
}
protected JanusGraphOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
List<CategoryDefinition> categories = new ArrayList<>();
SubCategoryDefinition subcategory;
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
return childVertex.right().value();
}
GraphVertex subCategoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
subcategory = new SubCategoryDefinition();
subcategory.setUniqueId(subCategoryV.getUniqueId());
subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
Type listTypeSubcat = new TypeToken<List<String>>() {
}.getType();
List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
subcategory.setIcons(iconsfromJsonSubcat);
final Type metadataKeysTypeCat = new TypeToken<List<MetadataKeyDataDefinition>>() {
}.getType();
final List<MetadataKeyDataDefinition> metadataKeysfromJsonCat = getGson()
.fromJson((String) metadataProperties.get(GraphPropertyEnum.METADATA_KEYS), metadataKeysTypeCat);
subcategory.setMetadataKeys(metadataKeysfromJsonCat);
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
parentVertex.right().value());
return childVertex.right().value();
}
GraphVertex categoryV = parentVertex.left().value();
metadataProperties = categoryV.getMetadataProperties();
CategoryDefinition category = new CategoryDefinition();
category.setUniqueId(categoryV.getUniqueId());
category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
Type listTypeCat = new TypeToken<List<String>>() {
}.getType();
List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
category.setIcons(iconsfromJsonCat);
category.addSubCategory(subcategory);
categories.add(category);
toscaElement.setCategories(categories);
return JanusGraphOperationStatus.OK;
}
public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV,
ComponentParametersView filterResult) {
Either<T, StorageOperationStatus> result = null;
log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
if (toscaElementToUpdate == null) {
log.error("Service object is null");
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
if (modifierUserId == null || modifierUserId.isEmpty()) {
log.error("UserId is missing in the request.");
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
Either<GraphVertex, JanusGraphOperationStatus> findUser = findUserVertex(modifierUserId);
if (findUser.isRight()) {
JanusGraphOperationStatus status = findUser.right().value();
log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, modifierUserId, status);
return result;
}
GraphVertex modifierV = findUser.left().value();
String toscaElementId = toscaElementToUpdate.getUniqueId();
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertex.right().value()));
}
GraphVertex userV = parentVertex.left().value();
String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
if (currentModifier.equals(modifierUserId)) {
log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
} else {
log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
return result;
}
}
final long currentTimeMillis = System.currentTimeMillis();
log.debug("Going to update the last Update Date of the resource from {} to {}",
elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
if (checkCategories != StorageOperationStatus.OK) {
result = Either.right(checkCategories);
return result;
}
// update all data on vertex
fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(elementV);
if (updateElement.isRight()) {
log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
return result;
}
GraphVertex updateElementV = updateElement.left().value();
// DE230195 in case resource name changed update TOSCA artifacts
// file names accordingly
String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> resultToscaArt = getDataFromGraph(updateElementV,
EdgeLabelEnum.TOSCA_ARTIFACTS);
if (resultToscaArt.isRight()) {
log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resultToscaArt.right().value()));
}
Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
if (toscaArtifacts != null) {
for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
}
// TODO call to new Artifact operation in order to update list of artifacts
}
}
if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
if (resultDerived != StorageOperationStatus.OK) {
log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
return Either.right(resultDerived);
}
}
Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
if (updatedResource.isRight()) {
log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
result = Either.right(StorageOperationStatus.BAD_REQUEST);
return result;
}
T updatedResourceValue = updatedResource.left().value();
result = Either.left(updatedResourceValue);
return result;
}
protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
return DaoStatusConverter
.convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
}
protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
return DaoStatusConverter
.convertJanusGraphStatusToStorageStatus(janusGraphDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
}
private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()
.entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())).findAny().get().getValue();
artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
}
protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
StorageOperationStatus status = StorageOperationStatus.OK;
List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
CategoryDefinition newCategory = newCategoryList.get(0);
Either<GraphVertex, JanusGraphOperationStatus> childVertex = janusGraphDao
.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
if (childVertex.isRight()) {
log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
}
GraphVertex subCategoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
Either<GraphVertex, JanusGraphOperationStatus> parentVertex = janusGraphDao
.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
if (parentVertex.isRight()) {
log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(),
parentVertex.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(childVertex.right().value());
}
GraphVertex categoryV = parentVertex.left().value();
metadataProperties = categoryV.getMetadataProperties();
String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
boolean categoryWasChanged = false;
String newCategoryName = newCategory.getName();
SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
String newSubCategoryName = newSubcategory.getName();
if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) {
// the category was changed
categoryWasChanged = true;
} else {
// the sub-category was changed
if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) {
log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
categoryWasChanged = true;
}
}
if (categoryWasChanged) {
Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName,
newCategoryName);
if (getCategoryVertex.isRight()) {
return getCategoryVertex.right().value();
}
GraphVertex newCategoryV = getCategoryVertex.left().value();
status = moveCategoryEdge(elementV, newCategoryV);
log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
}
return status;
}
public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType,
List<ResourceTypeEnum> excludeTypes,
boolean isHighestVersions) {
Either<List<GraphVertex>, JanusGraphOperationStatus> listOfComponents;
if (isHighestVersions) {
listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
} else {
listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
}
if (listOfComponents.isRight() && listOfComponents.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(listOfComponents.right().value()));
}
List<T> result = new ArrayList<>();
if (listOfComponents.isLeft()) {
List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) {
for (GraphVertex vertexComponent : highestAndAllCertified) {
Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType,
new ComponentParametersView(true));
if (component.isRight()) {
log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
return Either.right(component.right().value());
} else {
result.add(component.left().value());
}
}
}
}
return Either.left(result);
}
public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Map<String, CatalogComponent> existInCatalog = new HashMap<>();
Either<Iterator<Vertex>, JanusGraphOperationStatus> verticesEither = janusGraphDao.getCatalogOrArchiveVerticies(isCatalog);
if (verticesEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(verticesEither.right().value()));
}
Iterator<Vertex> vertices = verticesEither.left().value();
while (vertices.hasNext()) {
handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes);
}
stopWatch.stop();
String timeToFetchElements = stopWatch.prettyPrint();
log.info("time to fetch all catalog elements: {}", timeToFetchElements);
return Either.left(existInCatalog.values().stream().collect(Collectors.toList()));
}
private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) {
VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
String json = (String) property.value();
Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation());
Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation());
if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) {
CatalogComponent catalogComponent = new CatalogComponent();
catalogComponent.setUniqueId(uniqueId);
catalogComponent
.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation());
catalogComponent.setLastUpdateDate((lastUpdateDate != null ? (Long) lastUpdateDate : 0L));
catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation()));
catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation()));
catalogComponent.setUuid((String) metadatObj.get(JsonPresentationFields.UUID.getPresentation()));
catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation()));
catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation()));
Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name());
if (edges.hasNext()) {
catalogComponent
.setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value());
}
Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
if (resourceType != null) {
catalogComponent.setResourceType((String) resourceType);
}
if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
setServiceCategoryFromGraphV(vertex, catalogComponent);
} else {
setResourceCategoryFromGraphV(vertex, catalogComponent);
}
List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation());
if (tags != null) {
catalogComponent.setTags(tags);
}
existInCatalog.put(uniqueId, catalogComponent);
}
}
private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) {
boolean isAddToCatalog = true;
Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
if (resourceTypeStr != null) {
ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr);
if (!CollectionUtils.isEmpty(excludeTypes)) {
Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny();
if (op.isPresent()) {
isAddToCatalog = false;
}
}
}
return isAddToCatalog;
}
public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType,
List<ResourceTypeEnum> excludeTypes,
JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
return janusGraphDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
}
// highest + (certified && !highest)
public Either<List<GraphVertex>, JanusGraphOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType,
List<ResourceTypeEnum> excludeTypes) {
long startFetchAllStates = System.currentTimeMillis();
Either<List<GraphVertex>, JanusGraphOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes,
JsonParseFlagEnum.ParseMetadata);
Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> certifiedNotHighestNodes = janusGraphDao
.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return Either.right(certifiedNotHighestNodes.right().value());
}
long endFetchAllStates = System.currentTimeMillis();
List<GraphVertex> allNodes = new ArrayList<>();
if (certifiedNotHighestNodes.isLeft()) {
allNodes.addAll(certifiedNotHighestNodes.left().value());
}
if (highestNodes.isLeft()) {
allNodes.addAll(highestNodes.left().value());
}
log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
return Either.left(allNodes);
}
protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
// get all components marked for delete
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.IS_DELETED, true);
props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
Either<List<GraphVertex>, JanusGraphOperationStatus> componentsToDelete = janusGraphDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
if (componentsToDelete.isRight()) {
JanusGraphOperationStatus error = componentsToDelete.right().value();
if (error.equals(JanusGraphOperationStatus.NOT_FOUND)) {
log.trace("no components to delete");
return Either.left(new ArrayList<>());
} else {
log.info("failed to find components to delete. error : {}", error.name());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
}
return Either.left(componentsToDelete.left().value());
}
protected JanusGraphOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
Either<Map<String, AdditionalInfoParameterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV,
EdgeLabelEnum.ADDITIONAL_INFORMATION);
if (result.isLeft()) {
toscaElement.setAdditionalInformation(result.left().value());
} else {
if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
return result.right().value();
}
}
return JanusGraphOperationStatus.OK;
}
// --------------------------------------------
public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId,
ComponentParametersView componentParametersView);
public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex,
ComponentParametersView componentParametersView);
public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
protected abstract <T extends ToscaElement> JanusGraphOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
protected abstract <T extends ToscaElement> JanusGraphOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);
}
|