aboutsummaryrefslogtreecommitdiffstats
path: root/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java
blob: d96a82c77fce3a23bbad85a18c95696ad4b3877d (plain)
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
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
 * ================================================================================
 * Modifications Copyright (c) 2019 Samsung
 * ================================================================================
 * 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.onap.so.asdc.installer.heat;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.onap.so.logger.LoggingAnchor;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.IResourceInstance;
import org.onap.sdc.api.notification.IStatusData;
import org.onap.sdc.tosca.parser.api.IEntityDetails;
import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
import org.onap.sdc.tosca.parser.elements.queries.EntityQuery.EntityQueryBuilder;
import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery.TopologyTemplateQueryBuilder;
import org.onap.sdc.tosca.parser.enums.SdcTypes;
import org.onap.sdc.tosca.parser.impl.SdcPropertyNames;
import org.onap.sdc.toscaparser.api.*;
import org.onap.sdc.toscaparser.api.elements.Metadata;
import org.onap.sdc.toscaparser.api.functions.GetInput;
import org.onap.sdc.toscaparser.api.parameters.Input;
import org.onap.sdc.utils.DistributionStatusEnum;
import org.onap.so.asdc.client.ASDCConfiguration;
import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
import org.onap.so.asdc.installer.ASDCElementInfo;
import org.onap.so.asdc.installer.BigDecimalVersion;
import org.onap.so.asdc.installer.IVfModuleData;
import org.onap.so.asdc.installer.PnfResourceStructure;
import org.onap.so.asdc.installer.ResourceStructure;
import org.onap.so.asdc.installer.ToscaResourceStructure;
import org.onap.so.asdc.installer.VfModuleArtifact;
import org.onap.so.asdc.installer.VfModuleStructure;
import org.onap.so.asdc.installer.VfResourceStructure;
import org.onap.so.asdc.installer.bpmn.WorkflowResource;
import org.onap.so.asdc.util.YamlEditor;
import org.onap.so.db.catalog.beans.AllottedResource;
import org.onap.so.db.catalog.beans.AllottedResourceCustomization;
import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
import org.onap.so.db.catalog.beans.CollectionResource;
import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
import org.onap.so.db.catalog.beans.ConfigurationResource;
import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization;
import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
import org.onap.so.db.catalog.beans.CvnfcCustomization;
import org.onap.so.db.catalog.beans.HeatEnvironment;
import org.onap.so.db.catalog.beans.HeatFiles;
import org.onap.so.db.catalog.beans.HeatTemplate;
import org.onap.so.db.catalog.beans.HeatTemplateParam;
import org.onap.so.db.catalog.beans.InstanceGroup;
import org.onap.so.db.catalog.beans.InstanceGroupType;
import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
import org.onap.so.db.catalog.beans.NetworkInstanceGroup;
import org.onap.so.db.catalog.beans.NetworkResource;
import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
import org.onap.so.db.catalog.beans.PnfResource;
import org.onap.so.db.catalog.beans.PnfResourceCustomization;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization;
import org.onap.so.db.catalog.beans.SubType;
import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup;
import org.onap.so.db.catalog.beans.ToscaCsar;
import org.onap.so.db.catalog.beans.VFCInstanceGroup;
import org.onap.so.db.catalog.beans.VfModule;
import org.onap.so.db.catalog.beans.VfModuleCustomization;
import org.onap.so.db.catalog.beans.VnfResource;
import org.onap.so.db.catalog.beans.VnfResourceCustomization;
import org.onap.so.db.catalog.beans.VnfcCustomization;
import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository;
import org.onap.so.db.catalog.data.repository.AllottedResourceRepository;
import org.onap.so.db.catalog.data.repository.CollectionResourceCustomizationRepository;
import org.onap.so.db.catalog.data.repository.CollectionResourceRepository;
import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository;
import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository;
import org.onap.so.db.catalog.data.repository.CvnfcConfigurationCustomizationRepository;
import org.onap.so.db.catalog.data.repository.CvnfcCustomizationRepository;
import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository;
import org.onap.so.db.catalog.data.repository.HeatEnvironmentRepository;
import org.onap.so.db.catalog.data.repository.HeatFilesRepository;
import org.onap.so.db.catalog.data.repository.HeatTemplateRepository;
import org.onap.so.db.catalog.data.repository.InstanceGroupRepository;
import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository;
import org.onap.so.db.catalog.data.repository.NetworkResourceRepository;
import org.onap.so.db.catalog.data.repository.PnfCustomizationRepository;
import org.onap.so.db.catalog.data.repository.PnfResourceRepository;
import org.onap.so.db.catalog.data.repository.ServiceProxyResourceCustomizationRepository;
import org.onap.so.db.catalog.data.repository.ServiceRepository;
import org.onap.so.db.catalog.data.repository.TempNetworkHeatTemplateRepository;
import org.onap.so.db.catalog.data.repository.ToscaCsarRepository;
import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository;
import org.onap.so.db.catalog.data.repository.VFModuleRepository;
import org.onap.so.db.catalog.data.repository.VnfResourceRepository;
import org.onap.so.db.catalog.data.repository.VnfcCustomizationRepository;
import org.onap.so.db.catalog.data.repository.VnfcInstanceGroupCustomizationRepository;
import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus;
import org.onap.so.db.request.beans.WatchdogDistributionStatus;
import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup;
import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository;
import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository;
import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;

@Component
public class ToscaResourceInstaller {

    protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry";

    protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor";

    protected static final String ALLOTTED_RESOURCE = "Allotted Resource";

    protected static final String MULTI_STAGE_DESIGN = "multi_stage_design";

    protected static final String SCALABLE = "scalable";

    protected static final String BASIC = "BASIC";

    protected static final String PROVIDER = "PROVIDER";

    protected static final String HEAT = "HEAT";

    protected static final String MANUAL_RECORD = "MANUAL_RECORD";

    protected static final String MSO = "SO";

    protected static final String SDNC_MODEL_NAME = "sdnc_model_name";

    protected static final String SDNC_MODEL_VERSION = "sdnc_model_version";

    private static String CUSTOMIZATION_UUID = "customizationUUID";

    protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration";

    @Autowired
    protected ServiceRepository serviceRepo;

    @Autowired
    protected InstanceGroupRepository instanceGroupRepo;

    @Autowired
    protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo;

    @Autowired
    protected CollectionResourceRepository collectionRepo;

    @Autowired
    protected CollectionResourceCustomizationRepository collectionCustomizationRepo;

    @Autowired
    protected ConfigurationResourceCustomizationRepository configCustomizationRepo;

    @Autowired
    protected ConfigurationResourceRepository configRepo;

    @Autowired
    protected VnfResourceRepository vnfRepo;

    @Autowired
    protected VFModuleRepository vfModuleRepo;

    @Autowired
    protected VFModuleCustomizationRepository vfModuleCustomizationRepo;

    @Autowired
    protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo;

    @Autowired
    protected VnfcCustomizationRepository vnfcCustomizationRepo;

    @Autowired
    protected CvnfcCustomizationRepository cvnfcCustomizationRepo;

    @Autowired
    protected AllottedResourceRepository allottedRepo;

    @Autowired
    protected AllottedResourceCustomizationRepository allottedCustomizationRepo;

    @Autowired
    protected NetworkResourceRepository networkRepo;

    @Autowired
    protected HeatTemplateRepository heatRepo;

    @Autowired
    protected HeatEnvironmentRepository heatEnvRepo;

    @Autowired
    protected HeatFilesRepository heatFilesRepo;

    @Autowired
    protected NetworkResourceCustomizationRepository networkCustomizationRepo;

    @Autowired
    protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
    @Autowired
    protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
    @Autowired
    protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;

    @Autowired
    protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo;

    @Autowired
    protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository;

    @Autowired
    protected ToscaCsarRepository toscaCsarRepo;

    @Autowired
    protected PnfResourceRepository pnfResourceRepository;

    @Autowired
    protected PnfCustomizationRepository pnfCustomizationRepository;

    @Autowired
    protected WorkflowResource workflowResource;

    protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class);

    public boolean isCsarAlreadyDeployed(ToscaResourceStructure toscaResourceStructure)
            throws ArtifactInstallerException {
        boolean deployed = false;
        if (toscaResourceStructure == null) {
            return deployed;
        }

        IArtifactInfo inputToscaCsar = toscaResourceStructure.getToscaArtifact();
        String checkSum = inputToscaCsar.getArtifactChecksum();
        String artifactUuid = inputToscaCsar.getArtifactUUID();

        Optional<ToscaCsar> toscaCsarObj = toscaCsarRepo.findById(artifactUuid);
        if (toscaCsarObj.isPresent()) {
            ToscaCsar toscaCsar = toscaCsarObj.get();
            if (!toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
                String errorMessage =
                        String.format("Csar with UUID: %s already exists.Their checksums don't match", artifactUuid);
                throw new ArtifactInstallerException(errorMessage);
            } else if (toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
                deployed = true;
            }
        }
        return deployed;
    }

    public boolean isResourceAlreadyDeployed(ResourceStructure vfResourceStruct, boolean serviceDeployed)
            throws ArtifactInstallerException {
        boolean status = false;
        ResourceStructure vfResourceStructure = vfResourceStruct;
        try {
            status = vfResourceStructure.isDeployedSuccessfully();
        } catch (RuntimeException e) {
            status = false;
            logger.debug("Exception :", e);
        }
        try {
            Service existingService =
                    serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID());
            if (existingService != null && !serviceDeployed)
                status = true;
            if (status) {
                logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
                        vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
                        vfResourceStructure.getNotification().getServiceName(),
                        BigDecimalVersion.castAndCheckNotificationVersionToString(
                                vfResourceStructure.getNotification().getServiceVersion()),
                        vfResourceStructure.getNotification().getServiceUUID(),
                        vfResourceStructure.getResourceInstance().getResourceName(), "", "");
                WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(
                        vfResourceStruct.getNotification().getDistributionID(), MSO);
                wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
                watchdogCDStatusRepository.saveAndFlush(wdStatus);
            } else {
                logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
                        vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
                        vfResourceStructure.getNotification().getServiceName(),
                        BigDecimalVersion.castAndCheckNotificationVersionToString(
                                vfResourceStructure.getNotification().getServiceVersion()),
                        vfResourceStructure.getNotification().getServiceUUID(),
                        vfResourceStructure.getResourceInstance().getResourceName(), "", "");
            }
            return status;
        } catch (Exception e) {
            logger.error(LoggingAnchor.THREE, MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(),
                    ErrorCode.SchemaError.getValue(), "Exception - isResourceAlreadyDeployed");
            throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e);
        }
    }

    public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException {
        logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}",
                iStatus.getDistributionID(), iStatus.getComponentName());

        try {
            WatchdogComponentDistributionStatus cdStatus =
                    new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), iStatus.getComponentName());
            cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString());
            watchdogCDStatusRepository.save(cdStatus);

        } catch (Exception e) {
            logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage());
            throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage());
        }
    }


    @Transactional(rollbackFor = {ArtifactInstallerException.class})
    public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct)
            throws ArtifactInstallerException {
        if (resourceStruct instanceof VfResourceStructure) {
            installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct);
        } else if (resourceStruct instanceof PnfResourceStructure) {
            installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct);
        } else {
            logger.warn("Unrecognized resource type");
        }
    }

    private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct)
            throws ArtifactInstallerException {

        // PCLO: in case of deployment failure, use a string that will represent
        // the type of artifact that failed...
        List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
        try {
            createToscaCsar(toscaResourceStruct);
            Service service = createService(toscaResourceStruct, resourceStruct);

            processResourceSequence(toscaResourceStruct, service);
            processPnfResources(toscaResourceStruct, service, resourceStruct);
            serviceRepo.save(service);

            WatchdogComponentDistributionStatus status =
                    new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
            status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
            watchdogCDStatusRepository.save(status);

            toscaResourceStruct.setSuccessfulDeployment();

        } catch (Exception e) {
            logger.debug("Exception :", e);
            WatchdogComponentDistributionStatus status =
                    new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
            status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
            watchdogCDStatusRepository.save(status);
            Throwable dbExceptionToCapture = e;
            while (!(dbExceptionToCapture instanceof ConstraintViolationException
                    || dbExceptionToCapture instanceof LockAcquisitionException)
                    && (dbExceptionToCapture.getCause() != null)) {
                dbExceptionToCapture = dbExceptionToCapture.getCause();
            }

            if (dbExceptionToCapture instanceof ConstraintViolationException
                    || dbExceptionToCapture instanceof LockAcquisitionException) {
                logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
                        resourceStruct.getResourceInstance().getResourceName(),
                        resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
                        "Exception - ASCDC Artifact already deployed", e);
            } else {
                String elementToLog = (!artifactListForLogging.isEmpty()
                        ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
                        : "No element listed");
                logger.error(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
                        ErrorCode.DataError.getValue(), "Exception caught during installation of "
                                + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback",
                        e);
                throw new ArtifactInstallerException(
                        "Exception caught during installation of "
                                + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.",
                        e);
            }
        }
    }

    @Transactional(rollbackFor = {ArtifactInstallerException.class})
    public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct)
            throws ArtifactInstallerException {
        VfResourceStructure vfResourceStructure = vfResourceStruct;
        extractHeatInformation(toscaResourceStruct, vfResourceStructure);

        // PCLO: in case of deployment failure, use a string that will represent
        // the type of artifact that failed...
        List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
        try {
            createToscaCsar(toscaResourceStruct);
            createService(toscaResourceStruct, vfResourceStruct);
            Service service = toscaResourceStruct.getCatalogService();
            List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();

            List<IEntityDetails> vfEntityList = getEntityDetails(toscaResourceStruct,
                    EntityQuery.newBuilder(SdcTypes.VF), TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);

            List<IEntityDetails> arEntityDetails = new ArrayList<IEntityDetails>();

            for (IEntityDetails vfEntityDetails : vfEntityList) {

                Metadata metadata = vfEntityDetails.getMetadata();
                String category = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);

                if (ALLOTTED_RESOURCE.equalsIgnoreCase(category)) {
                    arEntityDetails.add(vfEntityDetails);
                }

                processVfModules(vfEntityDetails, vfNodeTemplatesList.get(0), toscaResourceStruct, vfResourceStructure,
                        service, metadata);
            }

            processResourceSequence(toscaResourceStruct, service);
            processAllottedResources(arEntityDetails, toscaResourceStruct, service);
            processNetworks(toscaResourceStruct, service);
            // process Network Collections
            processNetworkCollections(toscaResourceStruct, service);
            // Process Service Proxy & Configuration
            processServiceProxyAndConfiguration(toscaResourceStruct, service);

            logger.info("Saving Service: {} ", service.getModelName());
            service = serviceRepo.save(service);
            correlateConfigCustomResources(service);

            workflowResource.processWorkflows(vfResourceStructure);

            WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
                    vfResourceStruct.getNotification().getDistributionID(), MSO);
            status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
            watchdogCDStatusRepository.save(status);

            toscaResourceStruct.setSuccessfulDeployment();

        } catch (Exception e) {
            logger.debug("Exception :", e);
            WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
                    vfResourceStruct.getNotification().getDistributionID(), MSO);
            status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
            watchdogCDStatusRepository.save(status);
            Throwable dbExceptionToCapture = e;
            while (!(dbExceptionToCapture instanceof ConstraintViolationException
                    || dbExceptionToCapture instanceof LockAcquisitionException)
                    && (dbExceptionToCapture.getCause() != null)) {
                dbExceptionToCapture = dbExceptionToCapture.getCause();
            }

            if (dbExceptionToCapture instanceof ConstraintViolationException
                    || dbExceptionToCapture instanceof LockAcquisitionException) {
                logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
                        vfResourceStructure.getResourceInstance().getResourceName(),
                        vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
                        "Exception - ASCDC Artifact already deployed", e);
            } else {
                String elementToLog = (!artifactListForLogging.isEmpty()
                        ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
                        : "No element listed");
                logger.error(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
                        ErrorCode.DataError.getValue(),
                        "Exception caught during installation of "
                                + vfResourceStructure.getResourceInstance().getResourceName()
                                + ". Transaction rollback",
                        e);
                throw new ArtifactInstallerException("Exception caught during installation of "
                        + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e);
            }
        }
    }


    List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
            ISdcCsarHelper iSdcCsarHelper) {

        List<NodeTemplate> nodes = new ArrayList<>();
        nodes.addAll(nodeTemplates);

        for (NodeTemplate nodeTemplate : nodeTemplates) {
            RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
            List<RequirementAssignment> reqAs = requirement.getAll();
            for (RequirementAssignment ra : reqAs) {
                String reqNode = ra.getNodeTemplateName();
                for (NodeTemplate rNode : resultList) {
                    if (rNode.getName().equals(reqNode)) {
                        if (!resultList.contains(nodeTemplate)) {
                            resultList.add(nodeTemplate);
                        }
                        if (nodes.contains(nodeTemplate)) {
                            nodes.remove(nodeTemplate);
                        }
                        break;
                    }
                }
            }
        }

        if (!nodes.isEmpty()) {
            getRequirementList(resultList, nodes, iSdcCsarHelper);
        }

        return resultList;
    }

    // This method retrieve resource sequence from csar file
    void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) {
        List<String> resouceSequence = new ArrayList<>();
        List<NodeTemplate> resultList = new ArrayList<>();

        ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
        List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
        List<NodeTemplate> nodes = new ArrayList<>();
        nodes.addAll(nodeTemplates);

        for (NodeTemplate nodeTemplate : nodeTemplates) {
            RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);

            if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
                resultList.add(nodeTemplate);
                nodes.remove(nodeTemplate);
            }
        }

        resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);

        for (NodeTemplate node : resultList) {
            String templateName = node.getMetaData().getValue("name");
            if (!resouceSequence.contains(templateName)) {
                resouceSequence.add(templateName);
            }
        }

        String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(","));
        service.setResourceOrder(resourceSeqStr);
        logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr);
    }


    // this of temporary solution
    private static String getValue(Object value, List<Input> inputs) {
        String outInput;
        String defaultValue = null;
        if (value instanceof Map) {
            Collection values = ((LinkedHashMap) value).values();
            outInput = (values.size() > 0) ? values.toArray()[0].toString() : "";
        } else if (value instanceof GetInput) {
            String inputName = ((GetInput) value).getInputName();
            Optional<Input> inputOptional =
                    inputs.stream().filter(input -> input.getName().equals(inputName)).findFirst();
            if (inputOptional.isPresent()) {
                Input input = inputOptional.get();
                defaultValue = input.getDefault() != null ? input.getDefault().toString() : "";
            }
            // Gets a value between [ and ]
            String regex = "\\[.*?\\]";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(value.toString());
            String valueStr = matcher.find() ? matcher.group() : inputName;
            outInput = valueStr + "|" + defaultValue;
        } else {
            outInput = value != null ? value.toString() : "";
        }
        return outInput;
    }

    String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid)
            throws ArtifactInstallerException {
        Map<String, String> resouceRequest = new HashMap<>();
        ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();

        List<Input> serInput = iSdcCsarHelper.getServiceInputs();
        Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
                .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid))
                .findFirst();
        if (nodeTemplateOpt.isPresent()) {
            NodeTemplate nodeTemplate = nodeTemplateOpt.get();
            LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();

            for (String key : resourceProperties.keySet()) {
                Property property = resourceProperties.get(key);

                String value = getValue(property.getValue(), serInput);
                resouceRequest.put(key, value);
            }
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(resouceRequest);

            jsonStr = jsonStr.replace("\"", "\\\"");
            logger.debug(
                    "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr);
            return jsonStr;
        } catch (JsonProcessingException e) {
            logger.error("resource input could not be deserialized for resource customization id ("
                    + resourceCustomizationUuid + ")");
            throw new ArtifactInstallerException("resource input could not be parsed", e);
        }
    }

    protected void processNetworks(ToscaResourceStructure toscaResourceStruct, Service service)
            throws ArtifactInstallerException {

        List<IEntityDetails> vlEntityList = getEntityDetails(toscaResourceStruct, EntityQuery.newBuilder(SdcTypes.VL),
                TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);

        if (vlEntityList != null) {
            for (IEntityDetails vlEntity : vlEntityList) {
                String networkResourceModelName = vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME);

                TempNetworkHeatTemplateLookup tempNetworkLookUp =
                        tempNetworkLookupRepo.findFirstBynetworkResourceModelName(networkResourceModelName);

                if (tempNetworkLookUp != null) {
                    HeatTemplate heatTemplate =
                            heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
                    if (heatTemplate != null) {
                        NetworkResourceCustomization networkCustomization = createNetwork(vlEntity, toscaResourceStruct,
                                heatTemplate, tempNetworkLookUp.getAicVersionMax(),
                                tempNetworkLookUp.getAicVersionMin(), service);
                        // only insert unique entries
                        if (!service.getNetworkCustomizations().contains(networkCustomization)) {
                            service.getNetworkCustomizations().add(networkCustomization);
                        }
                    } else {
                        throw new ArtifactInstallerException("No HeatTemplate found for artifactUUID: "
                                + tempNetworkLookUp.getHeatTemplateArtifactUuid());
                    }
                } else {
                    NetworkResourceCustomization networkCustomization =
                            createNetwork(vlEntity, toscaResourceStruct, null, null, null, service);
                    networkCustomization.setResourceInput(
                            getResourceInput(toscaResourceStruct, networkCustomization.getModelCustomizationUUID()));
                    service.getNetworkCustomizations().add(networkCustomization);
                    logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for "
                            + networkResourceModelName);
                }

            }
        }
    }

    protected void processAllottedResources(List<IEntityDetails> arEntityDetails,
            ToscaResourceStructure toscaResourceStruct, Service service) throws ArtifactInstallerException {

        List<IEntityDetails> pnfAREntityList = getEntityDetails(toscaResourceStruct,
                EntityQuery.newBuilder(SdcTypes.PNF), TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);

        for (IEntityDetails pnfEntity : pnfAREntityList) {

            Metadata metadata = pnfEntity.getMetadata();
            String category = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);
            if (ALLOTTED_RESOURCE.equalsIgnoreCase(category)) {
                arEntityDetails.add(pnfEntity);
            }

        }

        if (arEntityDetails != null) {
            for (IEntityDetails arEntity : arEntityDetails) {
                AllottedResourceCustomization allottedResource =
                        createAllottedResource(arEntity, toscaResourceStruct, service);
                String resourceInput =
                        getResourceInput(toscaResourceStruct, allottedResource.getModelCustomizationUUID());
                if (!"{}".equals(resourceInput)) {
                    allottedResource.setResourceInput(resourceInput);
                }
                if (!service.getAllottedCustomizations().contains(allottedResource)) {
                    service.getAllottedCustomizations().add(allottedResource);
                }
            }
        }
    }


    protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) {
        Metadata metadata = nodeTemplate.getMetaData();
        ConfigurationResource configResource = new ConfigurationResource();
        configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
        configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
        configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
        configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
        configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
        configResource.setToscaNodeType(nodeTemplate.getType());
        return configResource;
    }

    protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate,
            ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
            Service service) {
        Metadata metadata = nodeTemplate.getMetaData();

        ConfigurationResource configResource = getConfigurationResource(nodeTemplate);

        ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization();

        Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();

        configCustomizationResource
                .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
        configCustomizationResource.setModelInstanceName(nodeTemplate.getName());

        configCustomizationResource.setFunction(
                toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "function"));
        configCustomizationResource.setRole(
                toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "role"));
        configCustomizationResource.setType(
                toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "type"));
        configCustomizationResource.setServiceProxyResourceCustomization(spResourceCustomization);

        configCustomizationResource.setConfigurationResource(configResource);
        configCustomizationResource.setService(service);
        configResourceCustomizationSet.add(configCustomizationResource);

        configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);

        return configCustomizationResource;
    }


    protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) {

        List<NodeTemplate> serviceProxyResourceList =
                toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);

        List<NodeTemplate> configurationNodeTemplatesList =
                toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);

        List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<>();
        List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<>();

        ServiceProxyResourceCustomization serviceProxy = null;

        if (serviceProxyResourceList != null) {
            for (NodeTemplate spNode : serviceProxyResourceList) {
                serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct);
                serviceProxyList.add(serviceProxy);

                for (NodeTemplate configNode : configurationNodeTemplatesList) {

                    List<RequirementAssignment> requirementsList =
                            toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll();
                    for (RequirementAssignment requirement : requirementsList) {
                        if (requirement.getNodeTemplateName().equals(spNode.getName())) {
                            ConfigurationResourceCustomization configurationResource = createConfiguration(configNode,
                                    toscaResourceStruct, serviceProxy, service, configurationResourceList);

                            Optional<ConfigurationResourceCustomization> matchingObject =
                                    configurationResourceList.stream()
                                            .filter(configurationResourceCustomization -> configNode.getMetaData()
                                                    .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)
                                                    .equals(configurationResource.getModelCustomizationUUID()))
                                            .filter(configurationResourceCustomization -> configurationResourceCustomization
                                                    .getModelInstanceName()
                                                    .equals(configurationResource.getModelInstanceName()))
                                            .findFirst();
                            if (!matchingObject.isPresent()) {
                                configurationResourceList.add(configurationResource);
                            }
                            break;
                        }
                    }
                }

            }
        }

        service.setConfigurationCustomizations(configurationResourceList);
        service.setServiceProxyCustomizations(serviceProxyList);
    }

    /*
     * ConfigurationResourceCustomization objects have their IDs auto incremented in the database. Unless we know their
     * IDs we cannot possibly associate their related records. So these ConfigResourceCustomizations are persisted first
     * and subsequently correlated.
     */

    protected void correlateConfigCustomResources(Service service) {
        /* Assuming that we have only one pair of VRF-VNR */
        ConfigurationResourceCustomization vrfConfigCustomResource = null;
        ConfigurationResourceCustomization vnrConfigCustomResource = null;
        List<ConfigurationResourceCustomization> configCustomList = service.getConfigurationCustomizations();
        for (ConfigurationResourceCustomization configResource : configCustomList) {
            String nodeType = configResource.getConfigurationResource().getToscaNodeType();
            if (NODES_VRF_ENTRY.equalsIgnoreCase(nodeType)) {
                vrfConfigCustomResource = configResource;
            } else if (VLAN_NETWORK_RECEPTOR.equalsIgnoreCase(nodeType)) {
                vnrConfigCustomResource = configResource;
            }
        }

        if (vrfConfigCustomResource != null) {
            vrfConfigCustomResource.setConfigResourceCustomization(vnrConfigCustomResource);
            configCustomizationRepo.save(vrfConfigCustomResource);

        }
        if (vnrConfigCustomResource != null) {
            vnrConfigCustomResource.setConfigResourceCustomization(vrfConfigCustomResource);
            configCustomizationRepo.save(vnrConfigCustomResource);
        }
    }

    protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) {

        List<IEntityDetails> crEntityList = getEntityDetails(toscaResourceStruct, EntityQuery.newBuilder(SdcTypes.CR),
                TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);

        if (crEntityList != null) {
            for (IEntityDetails ncEntity : crEntityList) {

                createNetworkCollection(ncEntity, toscaResourceStruct, service);
                collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource());

                List<NetworkInstanceGroup> networkInstanceGroupList =
                        toscaResourceStruct.getCatalogNetworkInstanceGroup();
                for (NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList) {
                    instanceGroupRepo.saveAndFlush(networkInstanceGroup);
                }

            }
        }
        service.getCollectionResourceCustomizations()
                .add(toscaResourceStruct.getCatalogCollectionResourceCustomization());
    }



    /**
     * This is used to process the PNF specific resource, including resource and resource_customization.
     * {@link IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for
     * details.
     */
    protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service,
            PnfResourceStructure resourceStructure) throws Exception {
        logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID());

        ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper();
        EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build();
        TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build();

        List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false);
        for (IEntityDetails entityDetails : entityDetailsList) {
            Metadata metadata = entityDetails.getMetadata();
            String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
            String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
            String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID();
            if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) {
                logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}",
                        customizationUUID, notifCustomizationUUID);

                if (checkExistingPnfResourceCutomization(customizationUUID)) {
                    logger.info("Resource customization UUID: {} already deployed", customizationUUID);
                } else {
                    PnfResource pnfResource = findExistingPnfResource(service, modelUuid);
                    if (pnfResource == null) {
                        pnfResource = createPnfResource(entityDetails);
                    }
                    PnfResourceCustomization pnfResourceCustomization =
                            createPnfResourceCustomization(entityDetails, pnfResource);
                    pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization);
                    toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization);
                    service.getPnfCustomizations().add(pnfResourceCustomization);
                }
            } else {
                logger.warn(
                        "Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}",
                        customizationUUID, notifCustomizationUUID);
            }
        }
    }

    private PnfResource findExistingPnfResource(Service service, String modelUuid) {
        PnfResource pnfResource = null;
        for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) {
            if (pnfResourceCustomization.getPnfResources() != null
                    && pnfResourceCustomization.getPnfResources().getModelUUID().equals(modelUuid)) {
                pnfResource = pnfResourceCustomization.getPnfResources();
            }
        }
        if (pnfResource == null) {
            pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource);
        }
        return pnfResource;
    }

    private boolean checkExistingPnfResourceCutomization(String customizationUUID) {
        return pnfCustomizationRepository.findById(customizationUUID).isPresent();
    }

    /**
     * Construct the {@link PnfResource} from {@link IEntityDetails} object.
     */
    private PnfResource createPnfResource(IEntityDetails entity) {
        PnfResource pnfResource = new PnfResource();
        Metadata metadata = entity.getMetadata();
        pnfResource.setModelInvariantUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
        pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
        pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
        pnfResource.setModelVersion(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
        pnfResource.setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
        pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
        pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
        pnfResource.setToscaNodeType(entity.getToscaType());
        return pnfResource;
    }

    /**
     * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object.
     */
    private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails,
            PnfResource pnfResource) {

        PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization();
        Metadata metadata = entityDetails.getMetadata();
        Map<String, Property> properties = entityDetails.getProperties();
        pnfResourceCustomization.setModelCustomizationUUID(
                testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
        pnfResourceCustomization.setModelInstanceName(entityDetails.getName());
        pnfResourceCustomization
                .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
        pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE)));
        pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE)));
        pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
        pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN)));
        pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME)));
        pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION)));
        pnfResourceCustomization.setSkipPostInstConf(getBooleanValue(properties.get(SKIP_POST_INST_CONF)));
        pnfResourceCustomization.setPnfResources(pnfResource);

        return pnfResourceCustomization;
    }

    /**
     * Get value from {@link Property} and cast to boolean value. Return true if property is null.
     */
    private boolean getBooleanValue(Property property) {
        if (null == property) {
            return true;
        }
        Object value = property.getValue();
        return new Boolean(String.valueOf(value));
    }

    /**
     * Get value from {@link Property} and cast to String value. Return empty String if property is null value.
     */
    private String getStringValue(Property property) {
        if (null == property) {
            return "";
        }
        Object value = property.getValue();
        return String.valueOf(value);
    }

    protected void processVfModules(IEntityDetails vfEntityDetails, NodeTemplate nodeTemplate,
            ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure, Service service,
            Metadata metadata) throws Exception {

        String vfCustomizationCategory =
                vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);

        logger.debug("VF Category is : " + vfCustomizationCategory);

        String vfCustomizationUUID =
                vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);

        logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);

        IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();

        // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before
        // comparing their VF Modules UUID's
        logger.debug("Checking if Notification VF ResourceCustomizationUUID: "
                + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: "
                + vfCustomizationUUID);

        if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {

            logger.debug("vfCustomizationUUID: " + vfCustomizationUUID
                    + " matches vfNotificationResource CustomizationUUID");

            VnfResourceCustomization vnfResource = createVnfResource(vfEntityDetails, toscaResourceStruct, service);

            if (vfResourceStructure.getVfModuleStructure() != null
                    && !vfResourceStructure.getVfModuleStructure().isEmpty()) {
                Set<CvnfcCustomization> existingCvnfcSet = new HashSet<>();
                Set<VnfcCustomization> existingVnfcSet = new HashSet<>();
                List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom = new ArrayList<>();

                for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) {

                    logger.debug("vfModuleStructure:" + vfModuleStructure.toString());

                    List<IEntityDetails> vfModuleEntityList =
                            getEntityDetails(toscaResourceStruct,
                                    EntityQuery.newBuilder("org.openecomp.groups.VfModule"), TopologyTemplateQuery
                                            .newBuilder(SdcTypes.SERVICE).customizationUUID(vfCustomizationUUID),
                                    false);

                    IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata();

                    logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : "
                            + vfMetadata.getVfModuleModelCustomizationUUID());

                    Optional<IEntityDetails> matchingObject = vfModuleEntityList.stream()
                            .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID "
                                    + group.getMetadata().getValue("vfModuleModelCustomizationUUID")))
                            .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID")
                                    .equals(vfMetadata.getVfModuleModelCustomizationUUID()))
                            .findFirst();
                    if (matchingObject.isPresent()) {
                        VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(),
                                toscaResourceStruct, vfResourceStructure, vfMetadata, vnfResource, service,
                                existingCvnfcSet, existingVnfcSet, existingCvnfcConfigurationCustom);
                        vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources());
                    } else
                        throw new Exception(
                                "Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: "
                                        + vfMetadata.getVfModuleModelCustomizationUUID());

                }
            }


            // Check for VNFC Instance Group info and add it if there is
            List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStruct,
                    EntityQuery.newBuilder("org.openecomp.groups.VfcInstanceGroup"),
                    TopologyTemplateQuery.newBuilder(SdcTypes.VF).customizationUUID(vfCustomizationUUID), false);


            for (IEntityDetails groupEntity : vfcEntityList) {
                VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization =
                        createVNFCInstanceGroup(groupEntity, nodeTemplate, vnfResource, toscaResourceStruct);
                vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
            }

            List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, vfcEntityList);
            if (!CollectionUtils.isEmpty(seqResult)) {
                String resultStr = seqResult.stream().collect(Collectors.joining(","));
                vnfResource.setVnfcInstanceGroupOrder(resultStr);
                logger.debug("vnfcGroupOrder result for service uuid(" + service.getModelUUID() + ") : " + resultStr);
            }
            // add this vnfResource with existing vnfResource for this service
            addVnfCustomization(service, vnfResource);
        } else {
            logger.debug("Notification VF ResourceCustomizationUUID: "
                    + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
                    + "Tosca VF Customization UUID: " + vfCustomizationUUID);
        }
    }

    private List<String> processVNFCGroupSequence(ToscaResourceStructure toscaResourceStructure,
            List<IEntityDetails> groupEntityDetails) {
        if (CollectionUtils.isEmpty(groupEntityDetails)) {
            return Collections.emptyList();
        }

        ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
        List<String> strSequence = new ArrayList<>(groupEntityDetails.size());
        List<IEntityDetails> tempEntityList = new ArrayList<>(groupEntityDetails.size());
        List<IEntityDetails> entities = new ArrayList<>();
        tempEntityList.addAll(groupEntityDetails);

        for (IEntityDetails vnfcEntityDetails : groupEntityDetails) {

            List<IEntityDetails> vnfcMemberNodes = vnfcEntityDetails.getMemberNodes();

            boolean hasRequirements = false;
            for (IEntityDetails vnfcDetails : vnfcMemberNodes) {

                Map<String, RequirementAssignment> requirements = vnfcDetails.getRequirements();

                if (requirements != null && !requirements.isEmpty()) {
                    hasRequirements = true;
                    break;
                }
            }

            if (!hasRequirements) {
                strSequence.add(vnfcEntityDetails.getName());
                tempEntityList.remove(vnfcEntityDetails);
                entities.addAll(vnfcMemberNodes);
            }
        }

        getVNFCGroupSequenceList(strSequence, tempEntityList, entities, iSdcCsarHelper);

        return strSequence;

    }

    private void getVNFCGroupSequenceList(List<String> strSequence, List<IEntityDetails> vnfcGroupDetails,
            List<IEntityDetails> vnfcMemberNodes, ISdcCsarHelper iSdcCsarHelper) {
        if (CollectionUtils.isEmpty(vnfcGroupDetails)) {
            return;
        }

        List<IEntityDetails> tempGroupList = new ArrayList<>();
        tempGroupList.addAll(vnfcGroupDetails);

        for (IEntityDetails vnfcGroup : vnfcGroupDetails) {
            List<IEntityDetails> members = vnfcGroup.getMemberNodes();
            for (IEntityDetails memberNode : members) {
                boolean isAllExists = true;


                Map<String, RequirementAssignment> requirements = memberNode.getRequirements();

                if (requirements == null || requirements.isEmpty()) {
                    continue;
                }


                for (Map.Entry<String, RequirementAssignment> entry : requirements.entrySet()) {
                    RequirementAssignment rqa = entry.getValue();
                    String name = rqa.getNodeTemplateName();
                    for (IEntityDetails node : vnfcMemberNodes) {
                        if (name.equals(node.getName())) {
                            break;
                        }
                    }

                    isAllExists = false;
                    break;
                }

                if (isAllExists) {
                    strSequence.add(vnfcGroup.getName());
                    tempGroupList.remove(vnfcGroupDetails);
                    vnfcMemberNodes.addAll(vnfcGroupDetails);
                }
            }

            if (!tempGroupList.isEmpty() && tempGroupList.size() < vnfcGroupDetails.size()) {
                getVNFCGroupSequenceList(strSequence, tempGroupList, vnfcMemberNodes, iSdcCsarHelper);
            }
        }
    }

    public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification,
            String consumerId) {
        WatchdogServiceModVerIdLookup modVerIdLookup =
                new WatchdogServiceModVerIdLookup(distributionId, servideUUID, distributionNotification, consumerId);
        watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup);

        try {

            WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId);
            watchdogDistributionStatusRepository.saveAndFlush(distributionStatus);

        } catch (ObjectOptimisticLockingFailureException e) {
            logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString());
            throw e;
        }
    }

    protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct,
            VfResourceStructure vfResourceStructure) {
        for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {

            switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) {
                case ASDCConfiguration.HEAT:
                case ASDCConfiguration.HEAT_NESTED:
                    createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
                    break;
                case ASDCConfiguration.HEAT_VOL:
                    createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
                    VfModuleArtifact envModuleArtifact =
                            getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
                    createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact);
                    break;
                case ASDCConfiguration.HEAT_ENV:
                    createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact);
                    break;
                case ASDCConfiguration.HEAT_ARTIFACT:
                    createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, toscaResourceStruct);
                    break;
                case ASDCConfiguration.HEAT_NET:
                case ASDCConfiguration.OTHER:
                    logger.warn(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(),
                            vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:"
                                    + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")",
                            ErrorCode.DataError.getValue(), "Artifact type not supported");
                    break;
                default:
                    break;

            }
        }
    }

    protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure,
            VfModuleArtifact vfModuleArtifact) {
        String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName();
        artifactName = artifactName.substring(0, artifactName.indexOf('.'));
        for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
            if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName)
                    && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
                return moduleArtifact;
            }
        }
        return null;
    }

    public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure,
            List<String> listTypes) {
        String newFileBody = filebody;
        for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {

            if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) {

                newFileBody =
                        verifyTheFilePrefixInString(newFileBody, moduleArtifact.getArtifactInfo().getArtifactName());
            }
        }
        return newFileBody;
    }

    public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) {

        String needlePrefix = "file:///";
        String prefixedFilenameToVerify = needlePrefix + filenameToVerify;

        if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) {
            return body;
        }

        StringBuilder sb = new StringBuilder(body.length());

        int currentIndex = 0;
        int startIndex = 0;

        while (currentIndex != -1) {
            startIndex = currentIndex;
            currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex);

            if (currentIndex == -1) {
                break;
            }
            // We append from the startIndex up to currentIndex (start of File
            // Name)
            sb.append(body.substring(startIndex, currentIndex));
            sb.append(filenameToVerify);

            currentIndex += prefixedFilenameToVerify.length();
        }

        sb.append(body.substring(startIndex));

        return sb.toString();
    }

    protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,
            ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) {

        HeatTemplate existingHeatTemplate =
                heatRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());

        if (existingHeatTemplate == null) {
            HeatTemplate heatTemplate = new HeatTemplate();
            List<String> typeList = new ArrayList<>();
            typeList.add(ASDCConfiguration.HEAT_NESTED);
            typeList.add(ASDCConfiguration.HEAT_ARTIFACT);

            heatTemplate.setTemplateBody(
                    verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
            heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName());

            if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
                heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
            } else {
                heatTemplate.setTimeoutMinutes(240);
            }

            heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
            heatTemplate.setVersion(BigDecimalVersion
                    .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
            heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());

            if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
                heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
            } else {
                heatTemplate.setArtifactChecksum(MANUAL_RECORD);
            }

            Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(),
                    vfModuleArtifact.getArtifactInfo().getArtifactUUID());
            heatTemplate.setParameters(heatParam);
            vfModuleArtifact.setHeatTemplate(heatTemplate);
        } else {
            vfModuleArtifact.setHeatTemplate(existingHeatTemplate);
        }
    }

    protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure,
            VfModuleArtifact vfModuleArtifact) {

        HeatEnvironment existingHeatEnvironment =
                heatEnvRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());

        if (existingHeatEnvironment == null) {
            HeatEnvironment heatEnvironment = new HeatEnvironment();
            heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName());
            List<String> typeList = new ArrayList<>();
            typeList.add(ASDCConfiguration.HEAT);
            typeList.add(ASDCConfiguration.HEAT_VOL);
            heatEnvironment.setEnvironment(
                    verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
            heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
            heatEnvironment.setVersion(BigDecimalVersion
                    .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
            heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());

            if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
                heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
            } else {
                heatEnvironment.setArtifactChecksum(MANUAL_RECORD);
            }
            vfModuleArtifact.setHeatEnvironment(heatEnvironment);
        } else {
            vfModuleArtifact.setHeatEnvironment(existingHeatEnvironment);
        }
    }

    protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure,
            VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) {

        HeatFiles existingHeatFiles =
                heatFilesRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());

        if (existingHeatFiles == null) {
            HeatFiles heatFile = new HeatFiles();
            heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
            heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
            heatFile.setFileBody(vfModuleArtifact.getResult());
            heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName());
            heatFile.setVersion(BigDecimalVersion
                    .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
            toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
            if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
                heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
            } else {
                heatFile.setArtifactChecksum(MANUAL_RECORD);
            }
            vfModuleArtifact.setHeatFiles(heatFile);
        } else {
            vfModuleArtifact.setHeatFiles(existingHeatFiles);
        }
    }

    protected Service createService(ToscaResourceStructure toscaResourceStructure,
            ResourceStructure resourceStructure) {

        Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata();

        List<Service> services =
                serviceRepo.findByModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
        Service service;
        if (!services.isEmpty() && services.size() > 0) {
            service = services.get(0);
        } else {
            service = new Service();
        }

        if (serviceMetadata != null) {

            if (toscaResourceStructure.getServiceVersion() != null) {
                service.setModelVersion(toscaResourceStructure.getServiceVersion());
            }

            service.setServiceType(serviceMetadata.getValue("serviceType"));
            service.setServiceRole(serviceMetadata.getValue("serviceRole"));
            service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));

            service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
            service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
            service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
            service.setEnvironmentContext(serviceMetadata.getValue("environmentContext"));

            if (resourceStructure != null)
                service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext());

            service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
            service.setCsar(toscaResourceStructure.getCatalogToscaCsar());
            service.setNamingPolicy(serviceMetadata.getValue("namingPolicy"));
            String generateNaming = serviceMetadata.getValue("ecompGeneratedNaming");
            Boolean generateNamingValue = null;
            if (generateNaming != null) {
                generateNamingValue = "true".equalsIgnoreCase(generateNaming);
            }
            service.setOnapGeneratedNaming(generateNamingValue);
        }


        toscaResourceStructure.setCatalogService(service);
        return service;
    }

    protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service,
            ToscaResourceStructure toscaResourceStructure) {

        Metadata spMetadata = nodeTemplate.getMetaData();

        ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization();

        Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>();

        spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
        spCustomizationResource
                .setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
        spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
        spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
        spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));

        spCustomizationResource
                .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
        spCustomizationResource.setModelInstanceName(nodeTemplate.getName());
        spCustomizationResource.setToscaNodeType(nodeTemplate.getType());

        String sourceServiceUUID = spMetadata.getValue("sourceModelUuid");

        Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID);

        spCustomizationResource.setSourceService(sourceService);
        spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
        serviceProxyCustomizationSet.add(spCustomizationResource);


        toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource);

        return spCustomizationResource;
    }

    protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate,
            ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
            Service service, List<ConfigurationResourceCustomization> configurationResourceList) {

        ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization(
                nodeTemplate, toscaResourceStructure, spResourceCustomization, service);

        ConfigurationResource configResource = null;

        ConfigurationResource existingConfigResource = findExistingConfiguration(service,
                nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID), configurationResourceList);

        if (existingConfigResource == null) {
            configResource = getConfigurationResource(nodeTemplate);
        } else {
            configResource = existingConfigResource;
        }

        configCustomizationResource.setConfigurationResource(configResource);

        return configCustomizationResource;
    }

    protected ConfigurationResource createFabricConfiguration(IEntityDetails fabricEntity,
            ToscaResourceStructure toscaResourceStructure) {

        Metadata fabricMetadata = fabricEntity.getMetadata();

        ConfigurationResource configResource = new ConfigurationResource();

        configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
        configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
        configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
        configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
        configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
        configResource.setToscaNodeType(fabricEntity.getToscaType());

        return configResource;
    }

    protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) {
        Optional<ToscaCsar> toscaCsarOpt =
                toscaCsarRepo.findById(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
        ToscaCsar toscaCsar;
        if (!toscaCsarOpt.isPresent()) {
            toscaCsar = new ToscaCsar();
            toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
        } else {
            toscaCsar = toscaCsarOpt.get();
        }
        if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) {
            toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum());
        } else {
            toscaCsar.setArtifactChecksum(MANUAL_RECORD);
        }
        toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName());
        toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion());
        toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription());
        toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL());

        toscaResourceStructure.setCatalogToscaCsar(toscaCsar);
    }

    protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) {
        VnfcCustomization vnfcCustomization = null;
        for (VnfcCustomization vnfcCustom : vnfcCustomizations) {
            if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
                vnfcCustomization = vnfcCustom;
            }
        }

        if (vnfcCustomization == null)
            vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);

        return vnfcCustomization;
    }

    protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations,
            String customizationUUID) {
        CvnfcCustomization cvnfcCustomization = null;
        for (CvnfcCustomization cvnfcCustom : cvnfcCustomizations) {
            if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
                cvnfcCustomization = cvnfcCustom;
            }
        }

        if (cvnfcCustomization == null)
            cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);

        return cvnfcCustomization;
    }

    protected NetworkResourceCustomization createNetwork(IEntityDetails networkEntity,
            ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,
            Service service) {

        NetworkResourceCustomization networkResourceCustomization =
                networkCustomizationRepo.findOneByModelCustomizationUUID(
                        networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

        boolean networkUUIDsMatch = true;
        // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from
        // the distribution.
        // If not we'll update the Customization record with latest from the distribution
        if (networkResourceCustomization != null) {
            String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID();
            String latestNetworkModelUUID = networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);

            if (!existingNetworkModelUUID.equals(latestNetworkModelUUID)) {
                networkUUIDsMatch = false;
            }

        }

        if (networkResourceCustomization != null && !networkUUIDsMatch) {

            NetworkResource networkResource =
                    createNetworkResource(networkEntity, toscaResourceStructure, heatTemplate, aicMax, aicMin);

            networkResourceCustomization.setNetworkResource(networkResource);

            networkCustomizationRepo.saveAndFlush(networkResourceCustomization);


        } else if (networkResourceCustomization == null) {
            networkResourceCustomization = createNetworkResourceCustomization(networkEntity, toscaResourceStructure);

            NetworkResource networkResource = findExistingNetworkResource(service,
                    networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
            if (networkResource == null)
                networkResource =
                        createNetworkResource(networkEntity, toscaResourceStructure, heatTemplate, aicMax, aicMin);

            networkResource.addNetworkResourceCustomization(networkResourceCustomization);
            networkResourceCustomization.setNetworkResource(networkResource);
        }

        return networkResourceCustomization;
    }

    protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) {
        NetworkResource networkResource = null;
        for (NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()) {
            if (networkCustom.getNetworkResource() != null
                    && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) {
                networkResource = networkCustom.getNetworkResource();
            }
        }
        if (networkResource == null)
            networkResource = networkRepo.findResourceByModelUUID(modelUUID);

        return networkResource;
    }

    protected NetworkResourceCustomization createNetworkResourceCustomization(IEntityDetails networkEntity,
            ToscaResourceStructure toscaResourceStructure) {
        NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization();
        networkResourceCustomization.setModelInstanceName(
                testNull(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
        networkResourceCustomization.setModelCustomizationUUID(
                testNull(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));

        networkResourceCustomization.setNetworkTechnology(
                getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));

        networkResourceCustomization
                .setNetworkType(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));

        networkResourceCustomization
                .setNetworkRole(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));

        networkResourceCustomization
                .setNetworkScope(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));

        return networkResourceCustomization;
    }

    protected NetworkResource createNetworkResource(IEntityDetails vlEntity,
            ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) {
        NetworkResource networkResource = new NetworkResource();
        String providerNetwork =
                getLeafPropertyValue(vlEntity, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);

        if ("true".equalsIgnoreCase(providerNetwork)) {
            networkResource.setNeutronNetworkType(PROVIDER);
        } else {
            networkResource.setNeutronNetworkType(BASIC);
        }

        networkResource.setModelName(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));

        networkResource.setModelInvariantUUID(
                testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
        networkResource.setModelUUID(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
        networkResource
                .setModelVersion(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));

        networkResource.setAicVersionMax(aicMax);
        networkResource.setAicVersionMin(aicMin);
        networkResource.setToscaNodeType(vlEntity.getToscaType());
        networkResource
                .setDescription(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
        networkResource.setOrchestrationMode(HEAT);
        networkResource.setHeatTemplate(heatTemplate);
        return networkResource;
    }

    protected CollectionNetworkResourceCustomization createNetworkCollection(IEntityDetails cnrEntity,
            ToscaResourceStructure toscaResourceStructure, Service service) {

        CollectionNetworkResourceCustomization collectionNetworkResourceCustomization =
                new CollectionNetworkResourceCustomization();

        // **** Build Object to populate Collection_Resource table
        CollectionResource collectionResource = new CollectionResource();

        collectionResource.setModelName(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
        collectionResource
                .setModelInvariantUUID(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
        collectionResource.setModelUUID(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
        collectionResource.setModelVersion(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
        collectionResource.setDescription(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
        collectionResource.setToscaNodeType(cnrEntity.getToscaType());

        toscaResourceStructure.setCatalogCollectionResource(collectionResource);

        // **** Build object to populate Collection_Resource_Customization table
        NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization();

        ncfc.setFunction(getLeafPropertyValue(cnrEntity, "cr_function"));
        ncfc.setRole(getLeafPropertyValue(cnrEntity, "cr_role"));
        ncfc.setType(getLeafPropertyValue(cnrEntity, "cr_type"));

        ncfc.setModelInstanceName(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
        ncfc.setModelCustomizationUUID(
                cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

        Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>();
        networkResourceCustomizationSet.add(collectionNetworkResourceCustomization);

        ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet);

        ncfc.setCollectionResource(collectionResource);
        toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc);

        // *** Build object to populate the Instance_Group table
        List<IEntityDetails> ncEntityList =
                getEntityDetails(toscaResourceStructure,
                        EntityQuery.newBuilder("org.openecomp.groups.NetworkCollection"),
                        TopologyTemplateQuery.newBuilder(SdcTypes.CR).customizationUUID(
                                cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
                        false);

        List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>();

        List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList =
                new ArrayList<>();

        for (IEntityDetails ncGroupEntity : ncEntityList) {

            NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup();
            Metadata instanceMetadata = ncGroupEntity.getMetadata();
            networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
            networkInstanceGroup
                    .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
            networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
            networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
            networkInstanceGroup.setToscaNodeType(ncGroupEntity.getToscaType());
            networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set
            // Role
            networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set
            // type
            networkInstanceGroup.setCollectionResource(collectionResource);

            // ****Build object to populate
            // Collection_Resource_Instance_Group_Customization table
            CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization =
                    new CollectionResourceInstanceGroupCustomization();
            crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup);
            crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
            crInstanceGroupCustomization.setModelCustomizationUUID(
                    cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

            // Loop through the template policy to find the subinterface_network_quantity property name. Then extract
            // the value for it.
            List<IEntityDetails> policyEntityList = getEntityDetails(toscaResourceStructure,
                    EntityQuery.newBuilder("org.openecomp.policies.scaling.Fixed"),
                    TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), true);

            if (policyEntityList != null) {
                for (IEntityDetails policyEntity : policyEntityList) {
                    for (String policyNetworkCollection : policyEntity.getTargets()) {

                        if (policyNetworkCollection.equalsIgnoreCase(ncGroupEntity.getName())) {

                            Map<String, Property> propMap = policyEntity.getProperties();

                            if (propMap.get("quantity") != null) {

                                String quantity = getLeafPropertyValue(cnrEntity,
                                        getPropertyInput(propMap.get("quantity").toString()));

                                if (quantity != null) {
                                    crInstanceGroupCustomization
                                            .setSubInterfaceNetworkQuantity(Integer.parseInt(quantity));
                                }

                            }

                        }
                    }
                }
            }

            crInstanceGroupCustomization.setDescription(
                    getLeafPropertyValue(cnrEntity, instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
                            + "_network_collection_description"));

            crInstanceGroupCustomization.setFunction(getLeafPropertyValue(cnrEntity,
                    instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + "_network_collection_function"));

            crInstanceGroupCustomization.setCollectionResourceCust(ncfc);
            collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization);

            networkInstanceGroup
                    .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList);

            networkInstanceGroupList.add(networkInstanceGroup);


            toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList);

            List<IEntityDetails> networkEntityList =
                    getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.VL),
                            TopologyTemplateQuery.newBuilder(SdcTypes.CR).customizationUUID(
                                    cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
                            false);

            List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>();

            // *****Build object to populate the NetworkResource table
            NetworkResource networkResource = new NetworkResource();

            for (IEntityDetails networkEntity : networkEntityList) {

                String providerNetwork = getLeafPropertyValue(networkEntity,
                        SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);

                if ("true".equalsIgnoreCase(providerNetwork)) {
                    networkResource.setNeutronNetworkType(PROVIDER);
                } else {
                    networkResource.setNeutronNetworkType(BASIC);
                }

                networkResource.setModelName(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));

                networkResource.setModelInvariantUUID(
                        networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
                networkResource.setModelUUID(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
                networkResource
                        .setModelVersion(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));

                networkResource.setAicVersionMax(
                        networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));

                TempNetworkHeatTemplateLookup tempNetworkLookUp =
                        tempNetworkLookupRepo.findFirstBynetworkResourceModelName(
                                networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));

                if (tempNetworkLookUp != null) {

                    HeatTemplate heatTemplate =
                            heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
                    networkResource.setHeatTemplate(heatTemplate);

                    networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin());

                }

                networkResource.setToscaNodeType(networkEntity.getToscaType());
                networkResource.setDescription(
                        networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
                networkResource.setOrchestrationMode(HEAT);

                // Build object to populate the
                // Collection_Network_Resource_Customization table
                for (IEntityDetails networkMemberEntity : ncGroupEntity.getMemberNodes()) {
                    collectionNetworkResourceCustomization.setModelInstanceName(networkMemberEntity.getName());
                }

                collectionNetworkResourceCustomization.setModelCustomizationUUID(
                        networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

                collectionNetworkResourceCustomization.setNetworkTechnology(
                        getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
                collectionNetworkResourceCustomization.setNetworkType(
                        getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
                collectionNetworkResourceCustomization.setNetworkRole(
                        getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
                collectionNetworkResourceCustomization.setNetworkScope(
                        getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
                collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup);
                collectionNetworkResourceCustomization.setNetworkResource(networkResource);
                collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc);

                collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization);
            }

        }

        return collectionNetworkResourceCustomization;
    }

    protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(IEntityDetails vfcInstanceEntity,
            NodeTemplate vnfcNodeTemplate, VnfResourceCustomization vnfResourceCustomization,
            ToscaResourceStructure toscaResourceStructure) {

        Metadata instanceMetadata = vfcInstanceEntity.getMetadata();

        InstanceGroup existingInstanceGroup =
                instanceGroupRepo.findByModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

        VFCInstanceGroup vfcInstanceGroup;

        if (existingInstanceGroup == null) {
            // Populate InstanceGroup
            vfcInstanceGroup = new VFCInstanceGroup();
            vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
            vfcInstanceGroup
                    .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
            vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
            vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
            vfcInstanceGroup.setToscaNodeType(vfcInstanceEntity.getToscaType());
            vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
            vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
        } else {
            vfcInstanceGroup = (VFCInstanceGroup) existingInstanceGroup;
        }

        // Populate VNFCInstanceGroupCustomization
        VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization();

        vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization);
        vnfResourceCustomization.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);

        vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
        vfcInstanceGroup.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);

        vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));

        String getInputName = null;

        Map<String, Property> groupProperties = vfcInstanceEntity.getProperties();

        for (String key : groupProperties.keySet()) {
            Property property = groupProperties.get(key);

            String vfcName = property.getName();

            if (vfcName != null) {
                if (vfcName.equals("vfc_instance_group_function")) {

                    String vfcValue = property.getValue().toString();
                    int getInputIndex = vfcValue.indexOf("{get_input=");
                    if (getInputIndex > -1) {
                        getInputName = vfcValue.substring(getInputIndex + 11, vfcValue.length() - 1);
                    }

                }
            }

        }

        List<IEntityDetails> serviceEntityList = getEntityDetails(toscaResourceStructure,
                EntityQuery.newBuilder(SdcTypes.VF)
                        .customizationUUID(vnfResourceCustomization.getModelCustomizationUUID()),
                TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);

        if (serviceEntityList != null && !serviceEntityList.isEmpty()) {
            vfcInstanceGroupCustom.setFunction(getLeafPropertyValue(serviceEntityList.get(0), getInputName));
        }

        vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);

        ArrayList<Input> inputs = vnfcNodeTemplate.getSubMappingToscaTemplate().getInputs();
        createVFCInstanceGroupMembers(vfcInstanceGroupCustom, vfcInstanceEntity, inputs);

        return vfcInstanceGroupCustom;
    }

    private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom,
            IEntityDetails vfcModuleEntity, List<Input> inputList) {
        List<IEntityDetails> members = vfcModuleEntity.getMemberNodes();
        if (!CollectionUtils.isEmpty(members)) {
            for (IEntityDetails vfcEntity : members) {
                VnfcCustomization vnfcCustomization = new VnfcCustomization();

                Metadata metadata = vfcEntity.getMetadata();
                vnfcCustomization
                        .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
                vnfcCustomization.setModelInstanceName(vfcEntity.getName());
                vnfcCustomization.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
                vnfcCustomization
                        .setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
                vnfcCustomization.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
                vnfcCustomization.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
                vnfcCustomization.setToscaNodeType(testNull(vfcEntity.getToscaType()));
                vnfcCustomization
                        .setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
                vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcEntity, inputList));
                vnfcCustomization.setVnfcInstanceGroupCustomization(vfcInstanceGroupCustom);
                List<VnfcCustomization> vnfcCustomizations = vfcInstanceGroupCustom.getVnfcCustomizations();

                if (vnfcCustomizations == null) {
                    vnfcCustomizations = new ArrayList<>();
                    vfcInstanceGroupCustom.setVnfcCustomizations(vnfcCustomizations);
                }
                vnfcCustomizations.add(vnfcCustomization);
            }
        }
    }

    public String getVnfcResourceInput(IEntityDetails vfcEntity, List<Input> inputList) {
        Map<String, String> resouceRequest = new HashMap<>();
        Map<String, Property> vfcTemplateProperties = vfcEntity.getProperties();
        for (String key : vfcTemplateProperties.keySet()) {
            Property property = vfcTemplateProperties.get(key);
            String resourceValue = getValue(property.getValue(), inputList);
            resouceRequest.put(key, resourceValue);
        }

        String resourceCustomizationUuid =
                vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);

        String jsonStr = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            jsonStr = objectMapper.writeValueAsString(resouceRequest);
            jsonStr = jsonStr.replace("\"", "\\\"");
            logger.debug("vfcResource request for resource customization id (" + resourceCustomizationUuid + ") : "
                    + jsonStr);
        } catch (JsonProcessingException e) {
            logger.debug("Json Exception: {}", e.getMessage());
            logger.error("Exception occurred", e);
        }

        return jsonStr;
    }

    protected VfModuleCustomization createVFModuleResource(IEntityDetails vfModuleEntityDetails,
            ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure,
            IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service,
            Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet,
            List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom) {

        VfModuleCustomization vfModuleCustomization =
                findExistingVfModuleCustomization(vnfResource, vfModuleData.getVfModuleModelCustomizationUUID());

        if (vfModuleCustomization == null) {

            VfModule vfModule = findExistingVfModule(vnfResource,
                    vfModuleEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));

            Metadata vfMetadata = vfModuleEntityDetails.getMetadata();
            if (vfModule == null)
                vfModule = createVfModule(vfModuleEntityDetails, toscaResourceStructure, vfModuleData, vfMetadata);

            vfModuleCustomization =
                    createVfModuleCustomization(vfModuleEntityDetails, toscaResourceStructure, vfModule, vfModuleData);
            vfModuleCustomization.setVnfCustomization(vnfResource);
            setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization,
                    vfMetadata);
            vfModuleCustomization.setVfModule(vfModule);
            vfModule.getVfModuleCustomization().add(vfModuleCustomization);
            vnfResource.getVfModuleCustomizations().add(vfModuleCustomization);
        } else {
            vfResourceStructure.setAlreadyDeployed(true);
        }

        // ******************************************************************************************************************
        // * Extract VFC's and CVFC's then add them to VFModule
        // ******************************************************************************************************************

        List<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations = new ArrayList<>();
        Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<>();
        Set<VnfcCustomization> vnfcCustomizations = new HashSet<>();

        // Only set the CVNFC if this vfModule group is a member of it.

        List<IEntityDetails> groupMembers = getEntityDetails(toscaResourceStructure,
                EntityQuery.newBuilder("org.openecomp.groups.VfModule")
                        .uUID(vfModuleCustomization.getVfModule().getModelUUID()),
                TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);

        String vfModuleMemberName = null;

        // Extract CVFC lists
        List<IEntityDetails> cvnfcEntityList = getEntityDetails(toscaResourceStructure,
                EntityQuery.newBuilder(SdcTypes.CVFC), TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);


        for (IEntityDetails cvfcEntity : cvnfcEntityList) {
            boolean cvnfcVfModuleNameMatch = false;

            for (IEntityDetails entity : groupMembers) {

                List<IEntityDetails> groupMembersNodes = entity.getMemberNodes();
                for (IEntityDetails groupMember : groupMembersNodes) {

                    vfModuleMemberName = groupMember.getName();

                    if (vfModuleMemberName.equalsIgnoreCase(cvfcEntity.getName())) {
                        cvnfcVfModuleNameMatch = true;
                        break;
                    }

                }
            }


            if (vfModuleMemberName != null && cvnfcVfModuleNameMatch) {

                // Extract associated VFC - Should always be just one
                List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStructure,
                        EntityQuery.newBuilder(SdcTypes.VFC),
                        TopologyTemplateQuery.newBuilder(SdcTypes.CVFC).customizationUUID(
                                cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
                        false);


                for (IEntityDetails vfcEntity : vfcEntityList) {

                    VnfcCustomization vnfcCustomization = new VnfcCustomization();
                    VnfcCustomization existingVnfcCustomization = null;

                    existingVnfcCustomization = findExistingVfc(existingVnfcSet,
                            vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

                    if (existingVnfcCustomization == null) {
                        vnfcCustomization = new VnfcCustomization();
                    } else {
                        vnfcCustomization = existingVnfcCustomization;
                    }

                    // Only Add Abstract VNFC's to our DB, ignore all others
                    if (existingVnfcCustomization == null && vfcEntity.getMetadata()
                            .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) {

                        vnfcCustomization.setModelCustomizationUUID(
                                vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
                        vnfcCustomization.setModelInstanceName(vfcEntity.getName());
                        vnfcCustomization.setModelInvariantUUID(
                                vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
                        vnfcCustomization
                                .setModelName(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
                        vnfcCustomization
                                .setModelUUID(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

                        vnfcCustomization.setModelVersion(
                                testNull(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
                        vnfcCustomization.setDescription(
                                testNull(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
                        vnfcCustomization.setToscaNodeType(testNull(vfcEntity.getToscaType()));

                        vnfcCustomizations.add(vnfcCustomization);
                        existingVnfcSet.add(vnfcCustomization);
                    }

                    // This check is needed incase the VFC subcategory is
                    // something other than Abstract. In that case we want to
                    // skip adding that record to our DB.
                    if (vnfcCustomization.getModelCustomizationUUID() != null) {
                        CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
                        cvnfcCustomization.setModelCustomizationUUID(
                                cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
                        cvnfcCustomization.setModelInstanceName(cvfcEntity.getName());
                        cvnfcCustomization.setModelInvariantUUID(
                                cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
                        cvnfcCustomization
                                .setModelName(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
                        cvnfcCustomization
                                .setModelUUID(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

                        cvnfcCustomization.setModelVersion(
                                testNull(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
                        cvnfcCustomization.setDescription(testNull(
                                cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
                        cvnfcCustomization.setToscaNodeType(testNull(cvfcEntity.getToscaType()));

                        if (existingVnfcCustomization != null) {
                            cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization);
                        } else {
                            cvnfcCustomization.setVnfcCustomization(vnfcCustomization);
                        }

                        cvnfcCustomization.setNfcFunction(getLeafPropertyValue(cvfcEntity, "nfc_function"));
                        cvnfcCustomization.setNfcNamingCode(getLeafPropertyValue(cvfcEntity, "nfc_naming_code"));

                        cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);

                        // *****************************************************************************************************************************************
                        // * Extract Fabric Configuration
                        // *****************************************************************************************************************************************

                        List<IEntityDetails> fabricEntityList =
                                getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.CONFIGURATION),
                                        TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);

                        for (IEntityDetails fabricEntity : fabricEntityList) {

                            Map<String, RequirementAssignment> requirements = fabricEntity.getRequirements();

                            for (RequirementAssignment requirement : requirements.values()) {

                                if (requirement.getNodeTemplateName().equals(cvfcEntity.getName())) {

                                    ConfigurationResource fabricConfig = null;

                                    ConfigurationResource existingConfig = findExistingConfiguration(
                                            existingCvnfcConfigurationCustom,
                                            fabricEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

                                    if (existingConfig == null) {

                                        fabricConfig = createFabricConfiguration(fabricEntity, toscaResourceStructure);

                                    } else {
                                        fabricConfig = existingConfig;
                                    }

                                    CvnfcConfigurationCustomization cvnfcConfigurationCustomization =
                                            createCvnfcConfigurationCustomization(fabricEntity, toscaResourceStructure,
                                                    vnfResource, vfModuleCustomization, cvnfcCustomization,
                                                    fabricConfig, vfModuleMemberName);

                                    cvnfcConfigurationCustomizations.add(cvnfcConfigurationCustomization);

                                    existingCvnfcConfigurationCustom.add(cvnfcConfigurationCustomization);

                                }
                            }

                        }
                        cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
                        cvnfcCustomizations.add(cvnfcCustomization);
                        existingCvnfcSet.add(cvnfcCustomization);

                    }

                }

            }
        }
        vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations);

        return vfModuleCustomization;
    }

    protected CvnfcConfigurationCustomization createCvnfcConfigurationCustomization(IEntityDetails fabricEntity,
            ToscaResourceStructure toscaResourceStruct, VnfResourceCustomization vnfResource,
            VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization,
            ConfigurationResource configResource, String vfModuleMemberName) {

        Metadata fabricMetadata = fabricEntity.getMetadata();

        CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();

        cvnfcConfigurationCustomization.setConfigurationResource(configResource);

        cvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);

        cvnfcConfigurationCustomization
                .setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
        cvnfcConfigurationCustomization.setModelInstanceName(fabricEntity.getName());

        List<IEntityDetails> policyList =
                getEntityDetails(toscaResourceStruct, EntityQuery.newBuilder("org.openecomp.policies.External"),
                        TopologyTemplateQuery.newBuilder(SdcTypes.VF), true);


        if (policyList != null) {
            for (IEntityDetails policyEntity : policyList) {

                for (String policyCvfcTarget : policyEntity.getTargets()) {

                    if (policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)) {

                        String policyType = getLeafPropertyValue(policyEntity, "type");

                        if (policyType != null && policyType.equalsIgnoreCase("Fabric Policy")) {
                            cvnfcConfigurationCustomization.setPolicyName(getLeafPropertyValue(policyEntity, "name"));
                        }
                    }
                }
            }
        }

        cvnfcConfigurationCustomization.setConfigurationFunction(getLeafPropertyValue(fabricEntity, "function"));
        cvnfcConfigurationCustomization.setConfigurationRole(getLeafPropertyValue(fabricEntity, "role"));
        cvnfcConfigurationCustomization.setConfigurationType(getLeafPropertyValue(fabricEntity, "type"));

        return cvnfcConfigurationCustomization;
    }

    protected ConfigurationResource findExistingConfiguration(
            List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom, String modelUUID) {
        ConfigurationResource configResource = null;
        for (CvnfcConfigurationCustomization cvnfcConfigCustom : existingCvnfcConfigurationCustom) {
            if (cvnfcConfigCustom != null) {
                if (cvnfcConfigCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
                    configResource = cvnfcConfigCustom.getConfigurationResource();
                }
            }
        }

        return configResource;
    }

    protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID,
            List<ConfigurationResourceCustomization> configurationResourceList) {
        ConfigurationResource configResource = null;
        for (ConfigurationResourceCustomization configurationResourceCustom : configurationResourceList) {
            if (configurationResourceCustom.getConfigurationResource() != null
                    && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
                configResource = configurationResourceCustom.getConfigurationResource();
            }
        }

        return configResource;
    }

    protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource,
            String vfModuleModelCustomizationUUID) {
        VfModuleCustomization vfModuleCustomization = null;
        for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
            if (vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)) {
                vfModuleCustomization = vfModuleCustom;
            }
        }
        return vfModuleCustomization;
    }

    protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) {
        VfModule vfModule = null;
        for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
            if (vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)) {
                vfModule = vfModuleCustom.getVfModule();
            }
        }
        if (vfModule == null)
            vfModule = vfModuleRepo.findByModelUUID(modelUUID);

        return vfModule;
    }

    protected VfModuleCustomization createVfModuleCustomization(IEntityDetails vfModuleEntityDetails,
            ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) {
        VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();

        vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID());

        vfModuleCustomization.setVfModule(vfModule);

        String initialCount = getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT);


        if (initialCount != null && initialCount.length() > 0) {
            vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount));
        }

        String availabilityZoneCount =
                getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT);

        if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) {
            vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount));
        }

        vfModuleCustomization
                .setLabel(getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL));

        String maxInstances =
                getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES);

        if (maxInstances != null && maxInstances.length() > 0) {
            vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances));
        }

        String minInstances =
                getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES);

        if (minInstances != null && minInstances.length() > 0) {
            vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances));
        }
        return vfModuleCustomization;
    }

    protected VfModule createVfModule(IEntityDetails groupEntityDetails, ToscaResourceStructure toscaResourceStructure,
            IVfModuleData vfModuleData, Metadata vfMetadata) {
        VfModule vfModule = new VfModule();
        String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID();

        if (vfModuleModelUUID == null) {

            vfModuleModelUUID = testNull(
                    groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));

        } else if (vfModuleModelUUID.indexOf('.') > -1) {
            vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.'));
        }

        vfModule.setModelInvariantUUID(
                groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID));
        vfModule.setModelName(
                groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME));
        vfModule.setModelUUID(vfModuleModelUUID);
        vfModule.setModelVersion(
                groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION));
        vfModule.setDescription(groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));

        String vfModuleType = getLeafPropertyValue(groupEntityDetails, SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE);

        if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) {
            vfModule.setIsBase(true);
        } else {
            vfModule.setIsBase(false);
        }
        return vfModule;
    }

    protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure,
            VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization,
            Metadata vfMetadata) {

        Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream()
                .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID()
                        .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
                                SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)))
                .findFirst();

        if (matchingObject.isPresent()) {
            List<HeatFiles> heatFilesList = new ArrayList<>();
            List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<>();
            List<HeatTemplate> heatChildTemplates = new ArrayList<>();
            HeatTemplate parentHeatTemplate = new HeatTemplate();
            String parentArtifactType = null;
            Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts());
            for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {

                List<HeatTemplate> childNestedHeatTemplates = new ArrayList<>();

                if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) {
                    checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact,
                            childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure);
                }

                if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
                    parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact);

                    if (!childNestedHeatTemplates.isEmpty()) {

                        if (parentArtifactType != null
                                && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) {
                            volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0));
                        } else {
                            heatChildTemplates.add(childNestedHeatTemplates.get(0));
                        }
                    }
                }

            }
            if (!heatFilesList.isEmpty()) {
                vfModule.setHeatFiles(heatFilesList);
            }


            // Set all Child Templates related to HEAT_VOLUME
            if (!volumeHeatChildTemplates.isEmpty()) {
                if (vfModule.getVolumeHeatTemplate() != null) {
                    vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates);
                } else {
                    logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()");
                }
            }

            // Set all Child Templates related to HEAT
            if (!heatChildTemplates.isEmpty()) {
                if (vfModule.getModuleHeatTemplate() != null) {
                    vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates);
                } else {
                    logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()");
                }
            }
        }
    }

    protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization,
            List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates,
            HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) {
        if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) {
            vfModuleArtifact.incrementDeployedInDB();
            vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate());
        } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) {
            vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate());
            VfModuleArtifact volVfModuleArtifact =
                    this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
            vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment());
            vfModuleArtifact.incrementDeployedInDB();
        } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
            if (vfModuleArtifact.getHeatEnvironment() != null) {
                if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) {
                    vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment());
                } else {
                    vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment());
                }
            }
            vfModuleArtifact.incrementDeployedInDB();
        } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) {
            heatFilesList.add(vfModuleArtifact.getHeatFiles());
            vfModuleArtifact.incrementDeployedInDB();
        } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
            nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate());
            vfModuleArtifact.incrementDeployedInDB();
        }
    }

    protected VnfResourceCustomization createVnfResource(IEntityDetails entityDetails,
            ToscaResourceStructure toscaResourceStructure, Service service) throws ArtifactInstallerException {
        VnfResourceCustomization vnfResourceCustomization = null;
        if (vnfResourceCustomization == null) {

            VnfResource vnfResource = findExistingVnfResource(service,
                    entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

            if (vnfResource == null) {
                vnfResource = createVnfResource(entityDetails);
            }

            vnfResourceCustomization =
                    createVnfResourceCustomization(entityDetails, toscaResourceStructure, vnfResource);
            vnfResourceCustomization.setVnfResources(vnfResource);
            vnfResourceCustomization.setService(service);

            // setting resource input for vnf customization
            vnfResourceCustomization.setResourceInput(
                    getResourceInput(toscaResourceStructure, vnfResourceCustomization.getModelCustomizationUUID()));

        }
        return vnfResourceCustomization;
    }

    protected VnfResource findExistingVnfResource(Service service, String modelUUID) {
        VnfResource vnfResource = null;
        for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
            if (vnfResourceCustom.getVnfResources() != null
                    && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) {
                vnfResource = vnfResourceCustom.getVnfResources();
            }
        }
        if (vnfResource == null)
            vnfResource = vnfRepo.findResourceByModelUUID(modelUUID);

        return vnfResource;
    }

    protected VnfResourceCustomization createVnfResourceCustomization(IEntityDetails entityDetails,
            ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) {
        VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
        vnfResourceCustomization.setModelCustomizationUUID(
                entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

        vnfResourceCustomization.setModelInstanceName(entityDetails.getName());
        vnfResourceCustomization
                .setNfFunction(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
        vnfResourceCustomization.setNfNamingCode(getLeafPropertyValue(entityDetails, "nf_naming_code"));
        vnfResourceCustomization.setNfRole(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFROLE));
        vnfResourceCustomization.setNfType(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFTYPE));

        vnfResourceCustomization.setMultiStageDesign(getLeafPropertyValue(entityDetails, MULTI_STAGE_DESIGN));
        vnfResourceCustomization.setBlueprintName(getLeafPropertyValue(entityDetails, SDNC_MODEL_NAME));
        vnfResourceCustomization.setBlueprintVersion(getLeafPropertyValue(entityDetails, SDNC_MODEL_VERSION));

        String skipPostInstConfText = getLeafPropertyValue(entityDetails, SKIP_POST_INST_CONF);

        if (skipPostInstConfText != null) {
            vnfResourceCustomization.setSkipPostInstConf(
                    Boolean.parseBoolean(getLeafPropertyValue(entityDetails, SKIP_POST_INST_CONF)));
        }


        vnfResourceCustomization.setVnfResources(vnfResource);
        vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(
                entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)));

        entityDetails.getCapabilities().get(SCALABLE);


        if (entityDetails.getCapabilities() != null) {

            CapabilityAssignment capAssign = entityDetails.getCapabilities().get(SCALABLE);

            if (capAssign != null) {
                vnfResourceCustomization.setMinInstances(Integer
                        .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
                vnfResourceCustomization.setMaxInstances(Integer
                        .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
            }

        }

        if (vnfResourceCustomization.getMinInstances() == null && vnfResourceCustomization.getMaxInstances() == null) {
            vnfResourceCustomization.setMinInstances(Integer
                    .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
            vnfResourceCustomization.setMaxInstances(Integer
                    .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
        }

        toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization);

        return vnfResourceCustomization;
    }

    protected VnfResource createVnfResource(IEntityDetails entityDetails) {
        VnfResource vnfResource = new VnfResource();
        vnfResource.setModelInvariantUUID(
                testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
        vnfResource.setModelName(testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
        vnfResource.setModelUUID(testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));

        vnfResource.setModelVersion(
                testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
        vnfResource.setDescription(
                testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
        vnfResource.setOrchestrationMode(HEAT);
        vnfResource.setToscaNodeType(testNull(entityDetails.getToscaType()));
        vnfResource.setAicVersionMax(
                testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
        vnfResource.setAicVersionMin(
                testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
        vnfResource.setCategory(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
        vnfResource.setSubCategory(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));

        return vnfResource;
    }

    protected AllottedResourceCustomization createAllottedResource(IEntityDetails arEntity,
            ToscaResourceStructure toscaResourceStructure, Service service) {
        AllottedResourceCustomization allottedResourceCustomization =
                allottedCustomizationRepo.findOneByModelCustomizationUUID(
                        arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));

        if (allottedResourceCustomization == null) {
            AllottedResource allottedResource = findExistingAllottedResource(service,
                    arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));

            if (allottedResource == null)
                allottedResource = createAR(arEntity);

            toscaResourceStructure.setAllottedResource(allottedResource);
            allottedResourceCustomization = createAllottedResourceCustomization(arEntity, toscaResourceStructure);
            allottedResourceCustomization.setAllottedResource(allottedResource);
            allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization);
        }
        return allottedResourceCustomization;
    }

    protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) {
        AllottedResource allottedResource = null;
        for (AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()) {
            if (allottedResourceCustom.getAllottedResource() != null
                    && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) {
                allottedResource = allottedResourceCustom.getAllottedResource();
            }
        }
        if (allottedResource == null)
            allottedResource = allottedRepo.findResourceByModelUUID(modelUUID);

        return allottedResource;
    }

    protected AllottedResourceCustomization createAllottedResourceCustomization(IEntityDetails arEntity,
            ToscaResourceStructure toscaResourceStructure) {
        AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization();
        allottedResourceCustomization.setModelCustomizationUUID(
                testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
        allottedResourceCustomization.setModelInstanceName(arEntity.getName());

        allottedResourceCustomization
                .setNfFunction(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
        allottedResourceCustomization.setNfNamingCode(getLeafPropertyValue(arEntity, "nf_naming_code"));
        allottedResourceCustomization.setNfRole(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFROLE));
        allottedResourceCustomization.setNfType(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFTYPE));

        EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.VFC).build();

        TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.VF)
                .customizationUUID(allottedResourceCustomization.getModelCustomizationUUID()).build();

        List<IEntityDetails> vfcEntities =
                toscaResourceStructure.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, false);


        if (vfcEntities != null) {
            for (IEntityDetails vfcEntity : vfcEntities) {

                allottedResourceCustomization
                        .setProvidingServiceModelUUID(getLeafPropertyValue(vfcEntity, "providing_service_uuid"));
                allottedResourceCustomization.setProvidingServiceModelInvariantUUID(
                        getLeafPropertyValue(vfcEntity, "providing_service_invariant_uuid"));
                allottedResourceCustomization
                        .setProvidingServiceModelName(getLeafPropertyValue(vfcEntity, "providing_service_name"));
            }
        }

        Map<String, CapabilityAssignment> capAssignmentList = arEntity.getCapabilities();

        if (capAssignmentList != null) {

            for (Map.Entry<String, CapabilityAssignment> entry : capAssignmentList.entrySet()) {
                CapabilityAssignment arCapability = entry.getValue();

                if (arCapability != null) {

                    String capabilityName = arCapability.getName();

                    if (capabilityName.equals(SCALABLE)) {

                        allottedResourceCustomization
                                .setMinInstances(Integer.getInteger(getCapabilityLeafPropertyValue(arCapability,
                                        SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
                        allottedResourceCustomization
                                .setMinInstances(Integer.getInteger(getCapabilityLeafPropertyValue(arCapability,
                                        SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));

                    }
                }

            }
        }

        return allottedResourceCustomization;
    }

    protected AllottedResource createAR(IEntityDetails arEntity) {
        AllottedResource allottedResource = new AllottedResource();
        allottedResource.setModelUUID(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
        allottedResource.setModelInvariantUUID(
                testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
        allottedResource.setModelName(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
        allottedResource
                .setModelVersion(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
        allottedResource.setToscaNodeType(testNull(arEntity.getToscaType()));
        allottedResource
                .setSubcategory(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
        allottedResource.setDescription(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
        return allottedResource;
    }

    protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) {
        // Scan the payload downloadResult and extract the HeatTemplate
        // parameters
        YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes());
        return yamlEditor.getParameterList(artifactUUID);
    }

    protected String testNull(Object object) {

        if (object == null) {
            return null;
        } else if ("NULL".equals(object)) {
            return null;
        } else if (object instanceof Integer) {
            return object.toString();
        } else if (object instanceof String) {
            return (String) object;
        } else {
            return "Type not recognized";
        }
    }

    protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,
            VfModuleArtifact heatNestedArtifact) {

        if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure
                .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) {
            for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0)
                    .getArtifactInfo().getRelatedArtifacts()) {
                if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
                    return ASDCConfiguration.HEAT;
                }

            }
        }

        if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null
                && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo()
                        .getRelatedArtifacts() != null) {
            for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL)
                    .get(0).getArtifactInfo().getRelatedArtifacts()) {
                if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
                    return ASDCConfiguration.HEAT_VOL;
                }

            }
        }

        // Does not belong to anything
        return null;

    }

    protected static String createVNFName(VfResourceStructure vfResourceStructure) {

        return vfResourceStructure.getNotification().getServiceName() + "/"
                + vfResourceStructure.getResourceInstance().getResourceInstanceName();
    }

    protected static String createVfModuleName(VfModuleStructure vfModuleStructure) {

        return createVNFName(vfModuleStructure.getParentVfResource()) + "::"
                + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName();
    }

    public List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct,
            EntityQueryBuilder entityType, TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) {

        EntityQuery entityQuery = entityType.build();
        TopologyTemplateQuery topologyTemplateQuery = topologyTemplateBuilder.build();
        List<IEntityDetails> entityDetails =
                toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch);

        return entityDetails;

    }

    public String getLeafPropertyValue(IEntityDetails entityDetails, String propName) {

        Property leafProperty = entityDetails.getProperties().get(propName);

        if (leafProperty != null && leafProperty.getValue() != null) {
            return leafProperty.getValue().toString();
        }

        return null;
    }

    protected String getCapabilityLeafPropertyValue(CapabilityAssignment capAssign, String propName) {

        Property leafProperty = capAssign.getProperties().get(propName);

        if (leafProperty != null && leafProperty.getValue() != null) {
            return leafProperty.getValue().toString();
        }

        return null;
    }

    protected String getPropertyInput(String propertyName) {

        String inputName = new String();

        if (propertyName != null) {
            int getInputIndex = propertyName.indexOf("{get_input=");
            int getClosingIndex = propertyName.indexOf("}");
            if (getInputIndex > -1) {
                inputName = propertyName.substring(getInputIndex + 11, getClosingIndex);
            }
        }

        return inputName;
    }

    // this method add provided vnfCustomization to service with
    // existing customization available in db.
    private void addVnfCustomization(Service service, VnfResourceCustomization vnfResourceCustomization) {
        List<Service> services = serviceRepo.findByModelUUID(service.getModelUUID());
        if (!services.isEmpty()) {
            // service exist in db
            Service existingService = services.get(0);
            List<VnfResourceCustomization> existingVnfCustomizations = existingService.getVnfCustomizations();
            if (existingService != null) {
                // it is duplicating entries, so added a check
                for (VnfResourceCustomization existingVnfResourceCustomization : existingVnfCustomizations) {
                    if (!service.getVnfCustomizations().contains(existingVnfResourceCustomization)) {
                        service.getVnfCustomizations().add(existingVnfResourceCustomization);
                    }
                }
            }
        }
        service.getVnfCustomizations().add(vnfResourceCustomization);

    }


    protected static Timestamp getCurrentTimeStamp() {

        return new Timestamp(new Date().getTime());
    }

}