aboutsummaryrefslogtreecommitdiffstats
path: root/build.gradle
blob: b80295eff8f8722c4507c7f477daaf2ae2f57f1b (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
import java.awt.Color
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean

import static Services.*
import static ServiceControl.*
import java.awt.AWTException
import java.awt.Font
import java.awt.Image
import java.awt.Menu
import java.awt.MenuItem
import java.awt.PopupMenu
import java.awt.SystemTray
import java.awt.TrayIcon
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JOptionPane
import javax.imageio.ImageIO


group 'com.att.ecomp'
version '1.01-SNAPSHOT'

apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: "org.hidetake.ssh"
apply plugin: 'java-gradle-plugin'
apply plugin: 'idea'

sourceCompatibility = 1.8

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'org.codehaus.groovy:groovy-all:2.4.12'
        classpath "org.hidetake:gradle-ssh-plugin:2.9.0"
    }
}

enum Services {
    BACKEND ,   //be
    FRONTEND ,  //fe
    DB ,        //cassandra
    CACHING ,   //elawsrticsearch
    SECURITY ,   //webseal
    ALL //all services
}
enum ServiceControl {
    HEALTH ,
    START ,
    RESTART ,
    STOP ,
    KILL
}
//env variables
//fill YOUR_WINDOWS_USER_HOME
project.ext.set("NEW_VAG",Boolean.FALSE) //flags to use new vagrant configuration
project.ext.set("IS_HOTSWAP",Boolean.FALSE) //flags to use new vagrant configuration
project.ext.set("PROJECT_PATH", System.getenv("SDC")) //ex. 'C:\\GIT_WORK\\asdc\\sdc')
project.ext.set("VAGRANT_HOME", NEW_VAG ? System.getenv("NEW_VAG") : System.getenv("VAG")) //ex. 'C:\\GIT_WORK\\vagrant-asdc-all-in-one')
project.ext.set("USER_HOME", "${System.getenv("USERPROFILE")}\\.ssh")
project.ext.set("BE_REMOTE", NEW_VAG ? '/opt/app/jetty/base/be' : '/home/vagrant/catalog-be' )
project.ext.set("FE_REMOTE", NEW_VAG ? '/opt/app/jetty/base/fe' : '/home/vagrant/catalog-fe' )
project.ext.set("VAGRANT_USER",     NEW_VAG ? 'm11981' : 'vagrant' )
project.ext.set("RSA_PRIVATE_KEY_PATH", NEW_VAG ? "$VAGRANT_HOME/id_rsa" : '' )
project.ext.set("VAGRANT_PASSWORD", NEW_VAG ? 'Aa123456' : 'vagrant' )
project.ext.set("X_FOLDER",'/xFolder' )
project.ext.set("BE_DEPENDENCIES", 'common-be,common-app-api,catalog-dao,catalog-model,security-utils' )
project.ext.set("command", [ (ALL) :  [  (HEALTH) : { NEW_VAG ? 'sudo curl -i http://localhost:8181/sdc1/rest/healthCheck' : 'curl -i localhost:8080/sdc2/rest/healthCheck' } ,
                                         (KILL) : { NEW_VAG ? 'sudo pkill java' : 'pkill java'} ]  ,   //  TODO: refine kill only for services
                             (BACKEND) : [  (START) : { NEW_VAG ? 'sudo service jettyBE start' : 'service catalog-be start'} ,
                                            (STOP) : { NEW_VAG ? 'sudo service jettyBE stop' : 'service catalog-be stop'} ,
                                            (RESTART) : { NEW_VAG ? 'sudo service jettyBE restart' : 'service catalog-be restart'}]  ,
                             (DB) : [  (START) : { NEW_VAG ? 'sudo service cassandra start' : 'start-asdc-storage.sh' } ,
                                       (STOP) : { NEW_VAG ? 'sudo service cassandra stop' : 'service cassandra stop'} ,
                                       (RESTART) : { NEW_VAG ? 'sudo service cassandra restart' : 'service cassandra restart'} ]  ,
                             (FRONTEND): [  (START) : {  NEW_VAG ? 'sudo service jettyFE start' : 'service catalog-fe start'   } ,
                                            (STOP) : { NEW_VAG ? 'sudo service jettyFE stop' : 'service catalog-fe stop'} ,
                                            (RESTART) : {  NEW_VAG ? 'sudo service jettyFE restart' : 'service catalog-fe restart'   } ]  ,
                             (CACHING): [  (START) : { NEW_VAG ? 'sudo service elasticsearch start' : 'echo "starting es is not yet supported"'   } ],
                             (SECURITY): [  (START) : {  NEW_VAG ? 'sudo docker start sdc-WebSeal-Simulator' : 'service webseal-simulator start'   } ,
                                            (STOP) : { NEW_VAG ? 'sudo docker stop sdc-WebSeal-Simulator' : 'service webseal-simulator stop'} ,
                                            (RESTART) : { NEW_VAG ? 'sudo docker restart sdc-WebSeal-Simulator' : 'service webseal-simulator restart'}]
                             ] )      //abstraction level to shell scripts , support old and new vagrant bash commands

//icons
project.ext.set("warnImg",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADvSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPb/enUwzdh4E0xzttxHNQRoABOUCQYYmj+9QrCBACQHUoMM4AYga74ZDiRAmvnEwHwQGywGBOiGgA1A16wmJYjQDAJANkgMmyEosYBVMzIAuuTWs/cM6iuhfCCAGwDWrAHxKyFw68ZNuCE40wGygcga0AEkEEHRiIxxASzqUKKRHIAwAJgo4BgXwKIGxQUgf8MwOsAlh+EFUMDBMAxgE0MGoLwAignSMFQPzmgkDjAwAACSmn13nChk1QAAAABJRU5ErkJggg==')
project.ext.set("okImg1",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAD4SURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYLbSRh8wfc9/C5jmbLmPagjQACYoEwwwNLMxgzHMIJAcSA0ygBuArFm81gyi+ddfCAaywWJAgG4I2AB0zdxWkhCNMABkg8SwGYISC1g1IwOgS74ee87wsvkUVADJAJjpyIDbRAxMfz3zCkwjA5ghONMB2DVIBiDbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAA4gXvZorg7ZgAAAABJRU5ErkJggg==')
project.ext.set("okImg2" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADjSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPbWZ7Jg2lvqMZjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGuetFsUTCMDmBi6IWAD0DUra3OA2cgAJIbNEJRYwKUZGdy9+oMhz/U1lIdkADZnwwwDaUIHMENwpgNk16DbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAAZD3X55epfOAAAAABJRU5ErkJggg==')
project.ext.set("errorImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADlSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPZbGRUwLfzkDpjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGtexisCppEBTAzdELAB6Jrd+QXAbGQAEsNmCEos4NKMDHZ+/MAQ9fkNlIdkADZnwwwDaUIHyIaADMDAQAP/AwMPjEFsbGpAGGs6AEUPsnfgzsaiDiUayQUgF2A4jaAXoHpQXAByNgyjA1xyGF4A+RuGYQCbGDLA6gWCGKoHJSGRDhgYAL/hkunRq+joAAAAAElFTkSuQmCC')
project.ext.set("unavailableImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABJ0AAASdAHeZh94AAAAB3RJTUUH4QwNDgEDrNoaqgAAAOhJREFUOMulkz8OgjAUhz8MQ7mBkwnnkBAH4mbCCdxcXLwAoxdwYXHjBCRupoMheg4TJ29QNhwshMofSfpLOry2v6/vta8OUGEhF4DsbUx6L8XytkNKCUAURTxWZ9TCM93buQb8mFXiI4E43gCQ5xeQPt7x2YG4fWa0OQwDhBANRCVdyGyKOQyDJhuV+HgvZQLGzABCiEGI036FPnNbZVlSFPfvnWg1gJpea72OjPh6lUZcQ5yhPkjTkxHv94fpfcB23t81PftmWMr9e+pQZjobd6zuobX2fViXAFCRvSv9GtOH9ji23/kDswRrCVqtQOAAAAAASUVORK5CYII=')


//health params
project.ext.set("trayIcon", null)
project.ext.set("lastStatus", null)
project.ext.set("isStopHealthCheck", false)
project.ext.set("isHaltHealth", new AtomicBoolean(false) )
project.ext.set("startedAwait", Long.MAX_VALUE)
project.ext.set("logFile", 'C:/ProgramData/all.log')
project.ext.set("pomList" , ["${System?.getenv('SDC')}/catalog-fe/pom.xml" ,"${System?.getenv('SDC')}/catalog-be/pom.xml" ] )   //empty list will scan all openecomp poms
project.ext.set("pomChangesMap" , [:] )
project.ext.set("beConfigFilesToCopyMapping" , [ 'src/main/resources/config/*.yaml' : 'config/catalog-be/' ,
                                               'src/main/resources/config/*.properties' : 'config/catalog-be/'] )

//menu item strings
project.ext.set("toggleHealthString" , "Halt Health" )
//menu item
project.ext.set("toggleHealthItemView" , null )

//other
project.ext.set("IS_MVN_INSTALL",false)
project.ext.set("executor" , null )
project.ext.set("lockObj" , new Object() )
/*compile?.doLast {
    println "2. hello compile2"
}*/

/*def post(String host , String serviceName,String msg){
    // POST
    def post = new URL("$host/$serviceName").openConnection();
    def message = '{"message":"this is a message"}'
    post.setRequestMethod("POST")
    post.setDoOutput(true)
    post.setRequestProperty("Content-Type", "application/json")
    post.getOutputStream().write(message.getBytes("UTF-8"));
    def postRC = post.getResponseCode();
    println(postRC);
    if( postRC.equals(200)) {
        println(post.getInputStream().getText());
    }
}

def postStat( long operationTime, String user , String meta  ){
    def host = 'http://135.76.123.70:8888'
    def params = "user=$user&meta=$meta"
    post host , "UserStats" , params
}*/


def hash( List list ){
    def map = list?.collectEntries { File file -> [(file?.absolutePath) : file?.text?.hashCode() ]}

    map
}

def pomChanges(){
    long started = System.currentTimeMillis()
    if ( !pomList )
        listPom()
    //find hash changes
    def changes = pomList?.findAll {
        def File file = new File(it);
        pomChangesMap[it] != file?.text?.hashCode()
    }
    println "\n\n[MasterD][POM]--> detected changes for -> $changes"
    //update changes in map
    changes?.each { pomChangesMap[it] = new File(it)?.text?.hashCode() }
    println "\n\n[MasterD][POM]--> pom map -> $pomChangesMap"

    println """ 
            ****** POM changes detection finished after -> ${System.currentTimeMillis()- started}ms  ******
            """

    changes
}
//list pom with updated file hashes
def listPom(){
    long started = System.currentTimeMillis()
    if (!pomList) {
        def tree = fileTree( PROJECT_PATH ).include '**/pom.xml'//.filter { it.isFile() && it?.toString()?.toLowerCase()?.endsWith('pom.xml') }
        //println "$PROJECT_PATH list is ->${ list?.collect { it?.absolutePath } }"
        //flatten and filter openecomp poms
        pomList = tree?.flatten()?.findAll { File file -> file?.text?.contains('org.openecomp.sdc') }?.collect {File file -> file?.absolutePath }
    }
    pomChangesMap = pomList.collectEntries { absolutePath ->[ ( absolutePath ) : new File(absolutePath)?.text?.hashCode() ] }

    println """ [MasterD][Init] intializing POM detector

            *********       POM listing finished after -> ${System.currentTimeMillis()- started}ms    *********
            """
    return pomList
}


task initialization(){
    listPom()
    executor = Executors.newCachedThreadPool();
}

def parallel( closure ){
    executor?.submit(new Callable<Object>(){
        @Override
        public Object call() {
            closure();
            return null;
        }
    })
}
/*class Preferences {
    def String Username
    def String IsNewVagrant
    def String IsRapidMode
}

def initXFolder(){
    def folder = new File(X_FOLDER);
    folder?.exists() ?: folder?.mkdirs()

    new File("${folder?.absolutePath}/$PREFERENCES_FILENAME")
}*/

task tester{
    /*doLast{
        //postStat(10000, "shay" , "report/index")
        listPom()
        new File('catalog-be\\pom.xml') << "#hello"
        pomChanges()
    }*/
}


def fetchFilesByExtention(remote, local , ext ){
    ssh.run {
        def started = System.currentTimeMillis()
        println "folder diff"
        session(remotes.vagrant) {
            //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
            get from: remote  , into: local , filter: {  it?.absolutePath =~ /jetty.*catalog-be.*\.dir.*\.$ext/  } // {  it?.absolutePath =~ /.*catalog-be.*dir.*classes.*/  }
        }
        println "fetched files in ${System.currentTimeMillis() - started} ms"
    }
}

def updateRemoteFile(String remote , String local){
    ssh.run {
        def to = "$BE_REMOTE${remote[remote?.indexOf("tmp\\")..remote.size()-1].replaceAll("\\\\","/")}"
        println "copying $local \nto\n $to"
        session(remotes.vagrant) {
            put from: local  , into: to }
    }
}

def compareAndSwap(){
    def final LIMIT = 10
    def newClasses = new File("$PROJECT_PATH\\catalog-be\\target\\classes")
    def File jettyClasses ;
    //locate classes
    println "traversing.."
    new File("build/hotswap").traverse { if (it?.directory && it?.name?.equals("classes")){
        jettyClasses = it
        return;
    }  }
    def jettyClassesList = []
    jettyClasses?.traverse { jettyClassesList << it }

    println "$jettyClasses"
    //Sort compiled classes
    def files = []
    newClasses?.traverse {  files << it }
    def result = files.sort{ a,b -> b.lastModified() <=> a.lastModified() }
    println "show only last $LIMIT changes"
    result[0..LIMIT]?.each{ println it?.lastModified() +" | "+ it?.name + (it?.directory ? "[Directory]" : "") } //show only last 10 changes

    //update
    def changesMap = [ : ] //<old,new>
    println "updating changes"
    result[0..LIMIT]?.each { File f -> def File other = jettyClassesList.find{ File other-> other?.absolutePath?.endsWith(f?.name) };
        if ( !(f.directory) && f?.text?.hashCode() != other?.text?.hashCode() )
            updateRemoteFile( other?.getAbsolutePath() , f?.getAbsolutePath() )
    } //use hashing
}

task hotswap(){
    doLast {
        new File("build/hotswap")?.deleteDir()
        new File("build/hotswap")?.mkdirs()
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        fetchFilesByExtention( "$BE_REMOTE/tmp/" , 'build/hotswap' , "class")
        compareAndSwap()
    }
}

remotes {
    vagrant {
        host = '127.0.0.1'
        port = 2222
        user = VAGRANT_USER
        password = VAGRANT_PASSWORD
        identity = NEW_VAG ? new File(RSA_PRIVATE_KEY_PATH) : null
    }

}

def gitLatest(){

}

def newEcoSystem(){
    //cleanTitan()
    backupDB() //and clean all
    //restoreDB() //restore latest
    createSchema()
    fillSchema()
    postCreate()
    startAll()
    //todo- conside updating from git
    updaterBEFull()
    updaterFE()
}
def importHeatTypes(){
   //todo- impl
}
def postCreate(){
    importNormative()
    importHeatTypes()
}
def fillSchema(){
    // add conformence level
}
def createSchemaPreStep(){
    //todo- DB up
}
def createSchemaPostStep(){
    ////todo- impl create amdocs dox
}
def createSchema(){
    createSchemaPreStep()
    //todo- create schema
    //todo- create titan
    createSchemaPostStep()
}

def cleanTitan(){
    execSafe{
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                execute "cqlsh -e 'DROP KEYSPACE titan;'"
                println "[MasterD][DB_DROP]-> Dropped 'titan' KEYSPACE."
            }
        }
    }
}
task cleanTitan {
    doLast{
        cleanTitan()
    }
}

task fetchE2EDB(){
    doLast{
        fetchE2EDB()
    }
}
def fetchE2EDB(){
    execSafe{
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                def tmp = '$CASSANDRA_HOME/backup/e2e'
                //execute 'mkdir $CASSANDRA_HOME/backup/e2e/'
                //execute 'wget http://135.76.210.202:8080/ETE_backup_files/latest_ETE_backup_file.zip -P /vagrant/db'
                println "[MasterD] download finished, unzipping.."
                execute "unzip -u $tmp/latest_ETE_backup_file.zip" //execute 'unzip -u /vagrant/db/latest_ETE_backup_file.zip'//'
                def folder = execute "cd $tmp; ls -d -- */"
                println "[MasterD] unzipping finished into -> $folder , untaring.."
                execute "tar zxf $tmp/$folder/* --strip 3 -C" +'$CASSANDRA_HOME/data | pv -l >/dev/null'
                println "[MasterD][E2E_DB]-> Downloaded & unzipped e2e data successfully."
            }
        }
    }
}
def copyExplodedBE() {
    execSafe{
        println "[MasterD][BackEnd] copying exploded war."
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        long started = System.currentTimeMillis()
        def dirPath = "${PROJECT_PATH}/catalog-be/target/catalog-be-1.1.0-SNAPSHOT"
        def dir = new File(dirPath);
        println "[MasterD][BackEnd] copying ${dir?.directorySize()/(1024*1024)} MB, from ${dir?.name} to $BE_REMOTE/webapps"
                ssh.run {
                    session(remotes.vagrant) {
                        execute "rm -R $BE_REMOTE/webapps/catalog-be-1.1.0-SNAPSHOT"
                        put from: dir?.absolutePath , into: "$BE_REMOTE/webapps"
                    }
                }
        println "[MasterD][BackEnd] Successfully copied exploded war in ${System.currentTimeMillis()-started}ms."
    }
}
task copyExplodedBE(){
    doLast{
        copyExplodedBE()
    }
}
def backupDB() {
    execSafe{
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                execute 'mkdir -p $CASSANDRA_HOME/backup'
                def res = execute 'mv $CASSANDRA_HOME/data $CASSANDRA_HOME/backup/data_$(date +\'%Y_%m_%d__%H:%M:%S\')'
                println "[MasterD][DB_BACKUP]-> snapshot DB finished. $res"
            }
        }
    }
}
task backupDB{
    doLast{
        backupDB()
    }
}

def restoreDB(){
    execSafe{
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                println "[MasterD]-> restoring DB"
                execute 'mkdir -p $CASSANDRA_HOME/data'
                def res = execute 'mv $CASSANDRA_HOME/backup/data_*/* $CASSANDRA_HOME/data'
                println "[MasterD]-> DB restore FINISHED!! $res"
            }
        }
    }
}
task restoreDB() {
    doLast {
        restoreDB()
    }
}

def vm( ){
    exec{
        if (VAGRANT_HOME){
            workingDir VAGRANT_HOME	//vagrant path
            println "*****************\nworking dir -> $VAGRANT_HOME"
            commandLine "cmd","/c", "vagrant up"
            //args = [ ]
        } else {
            println "[MasterD]--> please define windows enviroment variable VAG pointing to vagrant project"
        }
    }
}

task vm{
    doLast{
        vm()
    }
}

def copyFE() {
    println "[MasterD][FrontEnd] starting war copy."
    ssh.settings {
        knownHosts = allowAnyHosts
    }
    long started = System.currentTimeMillis()
    def target = "${PROJECT_PATH}/catalog-fe/target/"
    def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
    files?.each{ File file ->
        if (!file?.name?.contains('classes')){
            println "[MasterD][FrontEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $FE_REMOTE/webapps"
            ssh.run {
                session(remotes.vagrant) {
                    put from: file?.absolutePath , into: "$FE_REMOTE/webapps"
                }
            }
        }

    }
    println "[MasterD][FrontEnd] Successfully copied war in ${System.currentTimeMillis()-started}ms."
}

task deployFE{
    doLast {
        copyFE()
    }
}


def copyBE(){
    println "[MasterD][BackEnd] starting war copy."
    ssh.settings {
        knownHosts = allowAnyHosts
    }
    def target = "${PROJECT_PATH}/catalog-be/target/"
    def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
    long started = System.currentTimeMillis()
    files?.each{ File file ->
        if (!file?.name?.contains('classes')){
            println "[MasterD][BackEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $BE_REMOTE/webapps"
            ssh.run {
                session(remotes.vagrant) {
                    put from: file?.absolutePath , into: "$BE_REMOTE/webapps"
                }
            }
        }
    }
    println "[MasterD][BackEnd] SUCCESSFULY copied be war in ${System.currentTimeMillis()-started}ms."
}

task deployBE {
    doLast {
        copyBE()
    }
}
def compileFE(){
    exec{
        println "[MasterD][FE]--> compiling project at -> ${PROJECT_PATH}\\catalog-fe"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-fe,catalog-ui -am -Pcatalog -Dmaven.test.skip'
    }
}
task compileFE(){
    doLast{
        compileFE()
    }
}
def compileBE(){
    exec{
        println "[MasterD][BE]--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-be -Pcatalog -Dmaven.test.skip'
    }
}
task compileBE{
    doLast{
        compileBE()
    }
}

def compile(){
    exec{
        println "[MasterD]--> compiling project at -> ${PROJECT_PATH}"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c','mvn -T 2 compile -am -Pcatalog -Dmaven.test.skip'
    }
}

task compile{
    doLast{
        compile()
    }
}
def compileDependencies(){
    def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
    exec{
        println "[MasterD]--> compiling BE dependencies  -> $BE_DEPENDENCIES [ SKIPPING TESTS!! ]"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c',"mvn $cmd -pl $BE_DEPENDENCIES -Pcatalog -Dmaven.test.skip" //commandLine 'cmd', '/c','mvn -T 1C package -pl catalog-model,catalog-dao,catalog-be -P catalog -Dmaven.test.skip'
    }
}
task compileDependencies {
    doLast{
        compileDependencies()
    }
}
def compileWar(){
    def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
    exec{
        println "--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c',"mvn -T 1 $cmd war:war -pl catalog-be -Pcatalog -Dmaven.test.skip" //commandLine 'cmd', '/c','mvn -T 1C package -pl catalog-model,catalog-dao,catalog-be -P catalog -Dmaven.test.skip'
    }
}
task compileWar(){
    doLast{
        compileWar()
    }
}

//deprecated - use deployBE()
task be() {
    doLast{
        def started = System.currentTimeMillis();
        exec{
            println "[MasterD]--> copying be... [from $VAGRANT_HOME]"
            workingDir VAGRANT_HOME	//vagrant path
            commandLine 'cmd','/c', 'copy_war_be.bat','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
            //args = [ ]
        }
        println """
                ****    copying finished in -> ${System.currentTimeMillis() - started}ms         ****
                """
    }
}

task beConfig( ) {
    doLast{
        exec{
            workingDir "${System.env.VAG}"	//vagrant path
            commandLine 'cmd','/c','copy_war_be_with_configuration','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
            //args = [ ]
        }
    }

}
task feConfig( ) {
    doLast{
        exec{
            workingDir "${System.env.VAG}"	//vagrant path
            commandLine 'cmd','/c','copy_war_fe_with_configuration','localhost' , "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war" , "$FE_REMOTE/webapps"
            //args = [ ]
        }
    }

}

task fe() {
    doLast{
        exec {
            workingDir "${System.env.VAG}"    //vagrant path
            commandLine 'cmd','/c', 'copy_war_fe.bat', 'localhost', "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war", "$FE_REMOTE/webapps"
            //args = [ ]
        }
    }
}

def installAllProject(){
    exec{
        println "[MasterD]--> Compiling&Installing project at -> ${PROJECT_PATH}"
        workingDir "${PROJECT_PATH}"	//vagrant path
        commandLine 'cmd','/c','mvn -T 2 clean install -U -Pcatalog -Dmaven.test.skip'
    }
}
task installAllProject {
    doLast {
        installAllProject()
    }
}

task installAll {
    doLast{
        println '[MasterD]--> Finished!!'
    }
}
installAll.dependsOn { tasks.findAll { task -> task.name.startsWith('install_') } }

def install_BE(){
    exec {
            println '[MasterD][Install]--> Installing BE!!'
            workingDir "${PROJECT_PATH}"
            commandLine 'cmd','/c', 'mvn clean install -pl catalog-be -am -Pcatalog -Dmaven.test.skip'
            //args = [ ]
    }
}

task install_BE() {
    doLast{
        install_BE()
    }
}

def install_FE() {
    exec {
        workingDir "${PROJECT_PATH}"
        commandLine 'cmd','/c', 'mvn clean install -pl catalog-ui,catalog-fe -am -Pcatalog -Dmaven.test.skip'
    }
}
task install_FE() {
    doLast {
        install_FE()
    }
}

def updaterBERapid(){
    /* if ( ticket() > PREVIOUS_BUILD_VAR ){
     PREVIOUS_BUILD_VAR = ticket()*/
    def started = System.currentTimeMillis();
    println "[MasterD][Rapid]--> compiling changes using maven"
    compileWar()
    println "[MasterD][Rapid]--> copying war"
    copyBE() //use this if you want to deploy entire war //hotswap.execute()
    restartBackend()
    println msg(" redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
}
task updaterBERapid(){
    doLast {
        updaterBERapid()
    }
}
def updaterBE(){
    def started = System.currentTimeMillis();
    IS_MVN_INSTALL = pomChanges() ? true :  false
    println "[MasterD]--> compiling changes using maven"
    compileDependencies()
    compileWar()
    println "[MasterD]--> copying war"
    IS_HOTSWAP ? copyExplodedBE() : copyBE() //execute() //use this if you want to deploy entire war //hotswap.execute()
    restartBackend()
    println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
}
task updaterBE(){
    doLast {
        updaterBE()
    }
}
def copyBEConfiguration(){
/*    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                println msg("Stopping BackEnd Server")
                execute command[BACKEND][STOP]()
            }
        }
    }*/
}
def updaterBEFull(){
    def started = System.currentTimeMillis();
    compile()
    println "[MasterD]--> copying war"
    copyBE() //use this if you want to deploy entire war //hotswap.execute()
    copyBEConfiguration()
    println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
}
task updaterBEFull(){
    doLast {
        updaterBEFull()
    }
}
def copyFEConfiguration(){
    //todo- implement
}
def updaterFE(){
    def started = System.currentTimeMillis();
    println "[MasterD]--> compiling changes using maven"
    compileFE()
    println "[MasterD]--> copying war"
    copyFE() //.execute() //use this if you want to deploy entire war //hotswap.execute()
    copyFEConfiguration()
    println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
}
task updaterFE(){
    doLast {
      updaterFE()
    }
}
def stopBackend(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                println msg("Stopping BackEnd Server")
                execute command[BACKEND][STOP]()
            }
        }
    }
}
task stopBackend(){
    doLast {
        stopBackend()
    }
}

def startBackend(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                println msg("[MasterD] starting backend sever")

                execute command[BACKEND][START]()
            }
        }
    }
    println """[MasterD]->  finished !!
					    """
}
task startBackend(){
    doLast{
        startBackend()
    }
}

def restartBackend(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                println msg("[MasterD] restarting backend sever")

                execute command[BACKEND][RESTART]()
            }
        }
    }
    println """[MasterD]->  finished !!
					    """
}
//todo- remove this if you want to auto-deploy on every file save
/*
compileJava.doFirst{
    updater?.execute()
}*/

enum STATUS { UP, DOWN , UNKNOWN , UNAVAILABLE }

task health(){
    doLast {
        prepareTray()
    }
}

def execSafe( closure){
   if (!lockObj) {
        [0..4].forEach( {println "Critical ERROR : lock object is not initialized\n\nCritical ERROR : cannot run tasks\n"}() )
        return;
   }
   synchronized (lockObj){
           boolean prev = isHaltHealth.get()
           try {
               isHaltHealth.set(true)
               closure()
           } catch (Exception e) {
               println e
           } finally {
               isHaltHealth.set(prev)
           }
   }
}

def fetchFiles( remote, local ){
    ssh.run {
        session(remotes.vagrant) {
            //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
            def f = get from: remote  , into: local
            println f?.name
            //return f
        }
        //println "fetched files in ${System.currentTimeMillis() - started} ms"
    }

    //return null
}


def killJava(){
    execSafe {
        def res
        ssh.run {
            session( remotes.vagrant ) {
                println """					 *-*-****************************-*-*
								killing all java proccesses
						*-*-****************************-*-*
					"""
                res = execute command[ALL][KILL]()
            }
        }
        println res?.toString()
    }
}

def importNormative(){
    execSafe {
        ssh.run {
            session(remotes.vagrant) {
                println """					 *-*-************************************-*-*
											importNormative
								*-*-************************************-*-*
							"""
                execute "python -v $BE_REMOTE/scripts/import/tosca/importNormativeAll.py"
            }
        }
    }
}

def startAll(){
    def startCassandra = """
                        #!/bin/bash
                        
                        cassandra&
                        elasticsearch -d
                        
                        #Wait until ES is up
                        until curl localhost:9200/_cluster/health;
                        do
                            printf "."
                            sleep 3
                        done
                        
                        # Create Elastic Mapping if not exist in ES
                        createESMapping.sh
                        """
    execSafe {
        ssh.run {
            session(remotes.vagrant) {
                println """					 *-*-************************************-*-*
								starting all SDC services(DB,BE,FE,Webseal)
							*-*-************************************-*-*
				"""
                if ( NEW_VAG ){
                    execute command[DB][START]()
                    Thread.sleep(5000)
                    execute command[CACHING][START]()
                }
                else
                    execute startCassandra
                //[0..4]?.forEach( Thread?.sleep(2000) )
                Thread?.sleep(10000)
                Thread?.sleep(10000)
                execute command[BACKEND][START]()
                execute command[FRONTEND][START]()
                execute command[SECURITY][START]()
            }
        }
    }
}


/*def clearLog(type: Delete){
    delete{
        delete 'C:/ProgramData/all.log'
        followSymlinks = true
    }
}*/
task clearLog(type: Delete){
    doLast{
        delete 'C:/ProgramData/all.log'
        followSymlinks = true
    }
}
def logBE(){
    try{
        println "\n*** logging BE all.log ***\n"

            ssh.run {
                session( remotes.vagrant ) {
                    //String now = execute 'echo \"\$(date +\'%Y_%m_%d\')\"'
                    //println "\n\n*******************************************************\n\n"+now?.toString()
                    clearLog?.execute() //todo- remove this .execute()
                    fetchFiles( '/home/vagrant/catalog-be/logs/SDC/SDC-BE/all.log' , 'C:/ProgramData') //"%USERPROFILE%\AppData\Local\")
                    //project.ext.set( "logFile" , 'C:/ProgramData/all.log' )

                    //				-f /home/vagrant/catalog-fe/logs/*$now.stderrout.log -f /home/vagrant/catalog-be/logs/*$now.stderrout.log -f /home/vagrant/catalog-be/logs/ASDC/ASDC-BE/debug.log*'
                }
            }

        parallel {
            exec {
                //if ( logFile ){
                String notepad = 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe'
                println "logging $logFile to notepad++ [$notepad]"
                commandLine 'cmd','/c' , notepad ,logFile
            }
        }
    }catch(Exception e){
        println "cannot open logs!!!"
        e.printStackTrace()
    }
}
task logBE(){
    doLast{
        logBE()
    }
}

def toggleHealthPolling(){
    isHaltHealth.set(!isHaltHealth.get())
}
//converts predefined icon to Image
def Image convert( imageName ){
    String encodedimage = project.ext.get(imageName);
    byte[] byteImage = encodedimage?.split(',')[1]?.decodeBase64()
    Image image = ImageIO.read(new ByteArrayInputStream(byteImage));
}

def refreshMenu(String imageName){
    switch( imageName ) {
        case 'unavailableImg' : toggleHealthString = "Resume Health";  break;
        default : toggleHealthString = "Halt Health";
    }
    if (((MenuItem)toggleHealthItemView).getLabel() != toggleHealthString)
        ((MenuItem)toggleHealthItemView).setLabel(toggleHealthString);
}
def startDB(){
        println "[MasterD] Starting database.."
        execSafe {
            ssh.settings {
                knownHosts = allowAnyHosts
            }
            ssh.run {
                session(remotes.vagrant) {
                    execute command[DB][START]()
                }
            }
        }
}
task startDB(){
    doLast {
        startDB()
    }
}
def stopDB(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                execute command[DB][STOP]()
            }
        }
    }
}
task stopDB(){
    doLast {
        stopDB()
    }
}
def startFE(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                execute command[FRONTEND][START]()
            }
        }
    }
}
task startFE(){
    doLast {
        startFE()
    }
}
def stopFE(){
    execSafe {
        ssh.settings {
            knownHosts = allowAnyHosts
        }
        ssh.run {
            session(remotes.vagrant) {
                execute command[FRONTEND][STOP]()
            }
        }
    }
}
task stopFE(){
    doLast {
        stopFE()
    }
}

def ActionListener newListener( closure  ){
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                    closure()
            } catch (AWTException e1) {
                System.err.println(e1);
            }
        }
    }

    listener
}

ext.updateTray = { STATUS status ->
    lastStatus = status
    if (SystemTray.isSupported()) {
        // get the SystemTray instance
        SystemTray tray = SystemTray.getSystemTray();
        // load an image
        String imageName = status==STATUS.UP ? (Math.random()>0.5 ?'okImg1':'okImg2') : status==STATUS.UNAVAILABLE ? 'unavailableImg' : status==STATUS.DOWN ? 'errorImg' : 'warnImg'
        Image image = convert imageName
        if (trayIcon != null) {
            trayIcon.setImage(image)
            refreshMenu(imageName);
            return ;
        }
        //region  -> Menu UI
        // create a popup menu
        PopupMenu popup = new PopupMenu();
        // create menu item for the default action

        MenuItem hotswapItem = new MenuItem("===> WAR <===");
        hotswapItem.setFont(new Font("MONOSPACED" , Font.BOLD ,15f ))

        //region Multilevel Menus
        Menu deployMasterMenu = new Menu("DeployMaster");
        Menu backendMenu = new Menu("Backend");
        Menu frontendMenu = new Menu("Frontend");
        Menu dbMenu = new Menu("Database");
        try{
            deployMasterMenu.setFont(new Font("Cooper Black" ,Font.BOLD ,14f ))
            backendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
            frontendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
            dbMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
        }catch(Exception e){
            println e
        }

        //DeployMaster Menu
        MenuItem updaterBeWithDependenciesItem = new MenuItem("[BE] Quick Compile -> Deploy");
        MenuItem updaterFullBeItem = new MenuItem("[BE] Full Install  -> Deploy");
        MenuItem updaterFeItem = new MenuItem("[FE] Quick Compile -> Deploy");
        MenuItem updaterFullFeItem = new MenuItem("[FE] Full Install -> Deploy");

        //Menu UI build

        deployMasterMenu.add(updaterFullBeItem);
        deployMasterMenu.add(updaterBeWithDependenciesItem);

        deployMasterMenu.addSeparator();
        deployMasterMenu.add(updaterFullFeItem);
        deployMasterMenu.add(updaterFeItem);


        //BE menu
        MenuItem startItem = new MenuItem("[BE] Start");
        MenuItem stopItem = new MenuItem("[BE] Stop BackEnd");
        MenuItem copyBeWarItem = new MenuItem("[BE] Copy War");
        backendMenu.add(startItem);
        backendMenu.add(stopItem);
        backendMenu.add(copyBeWarItem);

        //FE menu
        MenuItem startFEItem = new MenuItem("[FE] Start");
        MenuItem stopFEItem = new MenuItem("[FE] Stop");
        MenuItem copyFeWarItem = new MenuItem("[FE] Copy War");
        frontendMenu.add(startFEItem);
        frontendMenu.add(stopFEItem);
        frontendMenu.add(copyFeWarItem);

        //DB menu
        MenuItem startDBItem = new MenuItem("[DB] Start");
        MenuItem stopDBItem = new MenuItem("[DB] Stop");
        MenuItem backupDBItem = new MenuItem("[DB] Backup");
        MenuItem restoreDBItem = new MenuItem("[DB] Restore");
        dbMenu.add(startDBItem);
        dbMenu.add(stopDBItem);
        dbMenu.add(backupDBItem);
        dbMenu.add(restoreDBItem);
        //endregion


        MenuItem killItem = new MenuItem("Kill All");
        MenuItem startAllItem = new MenuItem("Start All");
        MenuItem importItem = new MenuItem("Import Normative");
        MenuItem healthInfoItem = new MenuItem("[Info] Health");
        MenuItem toggleHealthItem = new MenuItem(toggleHealthString);
        MenuItem logsItem = new MenuItem("Logs [Beta]");
        MenuItem exitItem = new MenuItem("Exit");

        toggleHealthItemView = toggleHealthItem;

        popup.add(hotswapItem);
        popup?.addSeparator();
        popup.add(deployMasterMenu);
        popup?.addSeparator();
        popup.add(backendMenu)
        popup.add(frontendMenu)
        popup.add(dbMenu)
        popup?.addSeparator();
        popup.add(startAllItem);
        popup.add(killItem);
        popup?.addSeparator();
        popup.add(toggleHealthItem);
        popup.add(healthInfoItem);
        popup?.addSeparator();
        popup.add(importItem);
        popup.add(logsItem);
        popup?.addSeparator();
        popup.add(exitItem);
        //endregion UI
        // construct a TrayIcon
        trayIcon = new TrayIcon(image, "HealthTray", popup);

        //region -> Button actions
        def listenerHotswap = newListener { project.ext.set("IS_HOTSWAP", !IS_HOTSWAP); hotswapItem?.setLabel( IS_HOTSWAP ? "==> HotSwap <==" : "===> WAR <===")   }
        // create a action listener to listen for default action executed on the tray icon
        def listenerFullBE = newListener { parallel { install_BE(); IS_HOTSWAP ? copyExplodedBE() : copyBE(); restartBackend() } }
        def listenerFullFE = newListener { parallel { install_FE(); copyFE() } }
        ActionListener listenerFE = newListener { parallel { updaterFE() } }
        ActionListener listenerBE = newListener { parallel { updaterBE() } }
        ActionListener exitListener = newListener {
                    executor?.isShutdown() ?: executor?.shutdown()
                    tray.remove(trayIcon);
                    project.ext.set("isStopHealthCheck", true)
                    println "Shutting down.. bye bye.."
                }
        ActionListener stopBackendListener = newListener { stopBackend() }
        ActionListener startBEListener = newListener { parallel { startBackend() } }
        ActionListener killJavaListener = newListener { killJava() }

        ActionListener startAllListener = newListener { parallel { startAll() } }

        ActionListener listener5 = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel { importNormative() }
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        };

        ActionListener listener6 = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel { healthPopup() }
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        };

        ActionListener listener7 = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    logBE()//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        };
        ActionListener listener8 = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    toggleHealthPolling()//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        };
        ActionListener copyBeWarListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel { copyBE() }//.execute()//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        };

        ActionListener startDBListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel {
                        startDB()
                    }//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }

        ActionListener stopDBListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    stopDB()//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }

        ActionListener dbBackupListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel {
                        backupDB()//tasks.logger.execute()
                    }
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }

        ActionListener feStartListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel {
                        startFE()
                    }//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }

        ActionListener feStopListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    stopFE()//tasks.logger.execute()
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }

        ActionListener feCopyListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    parallel {
                        copyFE() //.execute()//tasks.logger.execute()
                    }
                } catch (AWTException e1) {
                    System.err.println(e1);
                }
            }
        }


        //def listenerFullModules = newListener { parallel { installAllProject() } }
        //region -> Button<=Listener
        hotswapItem.addActionListener(listenerHotswap)
        updaterFeItem.addActionListener(listenerFE)
        updaterFullBeItem.addActionListener( listenerFullBE )
        updaterBeWithDependenciesItem.addActionListener( listenerBE )
        updaterFullFeItem.addActionListener( listenerFullFE )
        stopItem.addActionListener(stopBackendListener)
        startItem.addActionListener(startBEListener)
        copyBeWarItem.addActionListener(copyBeWarListener);
        killItem.addActionListener(killJavaListener)
        startAllItem.addActionListener(startAllListener)
        importItem.addActionListener(listener5)
        healthInfoItem.addActionListener(listener6)
        toggleHealthItem.addActionListener(listener8)
        logsItem.addActionListener(listener7)
        exitItem.addActionListener(exitListener)

        startDBItem.addActionListener( startDBListener )
        stopDBItem.addActionListener( stopDBListener )
        backupDBItem.addActionListener( dbBackupListener )
        copyFeWarItem.addActionListener( feCopyListener )
        startFEItem.addActionListener( feStartListener )
        stopFEItem.addActionListener( feStopListener )
        //endregion
        //endregion
        // set the TrayIcon properties

        // ...
        // add the tray image
        try {
            tray.add(trayIcon);

        } catch (AWTException e) {
            System.err.println(e);
        }
        // ...
    } else {
        println "Java TrayIcon Option is not supported in your System, try enabling it. Bye Bye"
    }

}

def prepareTray(){
    long UPDATE_THRESHOLD = 3500
    float SCALAR = 1
    ssh.settings {
        knownHosts = allowAnyHosts
    }
    while(!isStopHealthCheck) {
        if (!isHaltHealth.get()) {    //if await or await is more then 60 second return health check
            ssh.run {
                session(remotes.vagrant) {
                    try {
                        def healthOutput = execute command[ALL][HEALTH]()
                        if (healthOutput?.contains("Failed command .* with status 7") || healthOutput?.contains("Problem accessing /sdc2/rest/healthCheck"))
                            updateTray(STATUS.DOWN)
                        def statusCollecion = healthOutput?.findAll "\"healthCheckStatus\": \".*\""
                        def upCount = statusCollecion?.count { it?.contains("UP") }
                        def downCount = statusCollecion?.count { it?.contains("DOWN") }
                        def uknownCount = (statusCollecion?.size() - upCount) - downCount
                        println " UP -> $upCount | downCount=$downCount | uknownCount=$uknownCount "
                        (uknownCount > 0 || (downCount > 0 && upCount > 0)) ? updateTray(STATUS.UNKNOWN) : ((upCount > 0) ? updateTray(STATUS.UP) : updateTray(STATUS.DOWN))
                        SCALAR = 1
                    } catch (Exception e) {
                        updateTray(STATUS.DOWN)
                        println e
                        SCALAR = Math.min(SCALAR * 1.1, 5) //slow down on errors
                    }
                    //green color effects
                    if (lastStatus && lastStatus == STATUS.UP) {
                        trayIcon.setImage(convert(Math.random() > 0.5 ? 'okImg1' : 'okImg2'))
                        //randomly green change color
                    }
                    Thread.yield()
                    Thread?.sleep((long) (UPDATE_THRESHOLD * SCALAR))
                }
            }
        }else{
            updateTray(STATUS.UNAVAILABLE)
            Thread.yield()
        }
    }
}

def healthPopup(){
    ssh.run {
        session(remotes.vagrant) {
            def healthOutput = execute command[ALL][HEALTH]()
            JOptionPane.showMessageDialog(null,
                    healthOutput,
                    "HEALTH",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

project.ext.set("msg", { content -> """
                        ************************************************************************************************
                        ************************************************************************************************
                        *******                                                                                *********
                        **************                                                                  ****************
                                                $content      

                        ************************************************************************************************
                        ************************************************************************************************
                        """} )