Update release notes for R3 MR
[sdc.git] / build.gradle
1 import java.util.concurrent.Callable
2 import java.util.concurrent.Executors
3 import java.util.concurrent.atomic.AtomicBoolean
4 import java.awt.AWTException
5 import java.awt.Font
6 import java.awt.Image
7 import java.awt.Menu
8 import java.awt.MenuItem
9 import java.awt.PopupMenu
10 import java.awt.SystemTray
11 import java.awt.TrayIcon
12 import java.awt.event.ActionEvent
13 import java.awt.event.ActionListener
14 import javax.swing.JOptionPane
15 import javax.imageio.ImageIO
16
17 import static Services.*
18 import static ServiceControl.*
19 /*
20 * open CMD  -> gradle health
21 *
22 * */
23
24 group 'org.onap.sdc'
25 version '1.01-SNAPSHOT'
26
27 apply plugin: 'groovy'
28 apply plugin: 'java'
29 apply plugin: "org.hidetake.ssh"
30 apply plugin: 'java-gradle-plugin'
31 apply plugin: 'idea'
32
33 sourceCompatibility = 1.8
34
35 buildscript {
36     repositories {
37         jcenter()
38         mavenCentral()
39     }
40     dependencies {
41         classpath 'org.codehaus.groovy:groovy-all:2.4.12'
42         classpath "org.hidetake:gradle-ssh-plugin:2.9.0"
43     }
44 }
45
46 enum Services {
47     BACKEND ,   //be
48     FRONTEND ,  //fe
49     DB ,        //cassandra
50     CACHING ,   //elawsrticsearch
51     SECURITY ,   //webseal
52     ALL //all services
53 }
54 enum ServiceControl {
55     HEALTH ,
56     START ,
57     RESTART ,
58     STOP ,
59     KILL
60 }
61 enum Environment {
62     OLD_VAGRANT , PROD_VAGRANT , ONAP_VAGRANT
63 }
64 //env variables
65 //fill YOUR_WINDOWS_USER_HOME
66 project.ext.set("VM_TYPE", Environment.ONAP_VAGRANT) //flags to use new vagrant configuration
67 //project.ext.set("NEW_VAG",Boolean.FALSE) //flags to use new vagrant configuration
68 project.ext.set("IS_HOTSWAP",Boolean.FALSE) //flags to use new vagrant configuration
69 project.ext.set("PROJECT_PATH", System.getenv("SDC")) //ex. 'C:\\GIT_WORK\\asdc\\sdc')
70 project.ext.set("VAGRANT_HOME", isProductionVM() ? System.getenv("NEW_VAG") : isOnapVM() ? System.getenv("ONAP_VAG") :System.getenv("VAG")) //ex. 'C:\\GIT_WORK\\vagrant-asdc-all-in-one')
71 project.ext.set("USER_HOME", "${System.getenv("USERPROFILE")}\\.ssh")
72 project.ext.set("BE_REMOTE", isProductionVM() ? '/opt/app/jetty/base/be' : '/home/vagrant/catalog-be' )
73 project.ext.set("FE_REMOTE", isProductionVM() ? '/opt/app/jetty/base/fe' : '/home/vagrant/catalog-fe' )
74 project.ext.set("VAGRANT_USER",     isProductionVM() ? 'm11981' : 'vagrant' )
75 project.ext.set("RSA_PRIVATE_KEY_PATH", isProductionVM() ? "$VAGRANT_HOME/id_rsa" : '' )
76 project.ext.set("VAGRANT_PASSWORD", isProductionVM() ? 'Aa123456' : 'vagrant' )
77 project.ext.set("X_FOLDER",'/xFolder' )
78 project.ext.set("BE_DEPENDENCIES", 'common-be,common-app-api,catalog-dao,catalog-model,security-utils' )
79 project.ext.set("command", [ (ALL) :  [  (HEALTH) : { isProductionVM() ? 'sudo curl -i http://localhost:8181/sdc1/rest/healthCheck' : isOnapVM() ? 'sudo -i /data/scripts/docker_health.sh' : 'curl -i localhost:8080/sdc2/rest/healthCheck' } ,
80                                          (KILL) : { isProductionVM() ? 'sudo pkill java' : isOnapVM() ? 'sudo -i docker kill $(docker ps -q)' : 'pkill java'} ]  ,   //  TODO: refine kill only for services
81                              (BACKEND) : [  (START) : { isProductionVM() ? 'sudo service jettyBE start' : isOnapVM() ? 'sudo -i docker start sdc-BE' : 'service catalog-be start'} ,
82                                             (STOP) : { isProductionVM() ? 'sudo service jettyBE stop' : isOnapVM() ? 'sudo -i docker stop sdc-BE' : 'service catalog-be stop'} ,
83                                             (RESTART) : { isProductionVM() ? 'sudo service jettyBE restart' : isOnapVM() ? 'sudo -i docker restart sdc-BE' : 'service catalog-be restart'}]  ,
84                              (DB) : [  (START) : { isProductionVM() ? 'sudo service cassandra start' :  isOnapVM() ? 'sudo -i docker start sdc-cs' : 'start-asdc-storage.sh' } ,
85                                        (STOP) : { isProductionVM() ? 'sudo service cassandra stop' : isOnapVM() ? 'sudo -i docker stop sdc-cs' : 'service cassandra stop'} ,
86                                        (RESTART) : { isProductionVM() ? 'sudo service cassandra restart' : isOnapVM() ? 'sudo -i docker restart sdc-cs' : 'service cassandra restart'} ]  ,
87                              (FRONTEND): [  (START) : {  isProductionVM() ? 'sudo service jettyFE start' : isOnapVM() ? 'sudo -i docker start sdc-FE' : 'service catalog-fe start'   } ,
88                                             (STOP) : { isProductionVM() ? 'sudo service jettyFE stop' : isOnapVM() ? 'sudo -i docker stop sdc-FE' : 'service catalog-fe stop'} ,
89                                             (RESTART) : {  isProductionVM() ? 'sudo service jettyFE restart' : isOnapVM() ? 'sudo -i docker restart sdc-FE' : 'service catalog-fe restart'   } ]  ,
90                              (CACHING): [  (START) : { isProductionVM() ? 'sudo service elasticsearch start' : isOnapVM() ? 'sudo -i docker start sdc-es' : 'echo "starting es is not yet supported"'   } ],
91                              (SECURITY): [  (START) : {  isProductionVM() ? 'sudo docker start sdc-WebSeal-Simulator' : isOnapVM() ? 'sudo -i /data/scripts/simulator_docker_run.sh -r $(echo $(sudo -i docker images onap/sdc-simulator | grep onap/sdc-simulator | head -1 |  awk \'{print $2}\'))' :  'service webseal-simulator start'   } ,
92                                             (STOP) : { isProductionVM() ? 'sudo docker stop sdc-WebSeal-Simulator' : isOnapVM() ? 'sudo -i docker stop sdc-sim' : 'service webseal-simulator stop'} ,
93                                             (RESTART) : { isProductionVM() ? 'sudo docker restart sdc-WebSeal-Simulator' : isOnapVM() ? 'sudo -i docker restart sdc-sim' : 'service webseal-simulator restart'}]
94                              ] )      //abstraction level to shell scripts , support old and new vagrant bash commands
95
96 //icons
97 project.ext.set("warnImg",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADvSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPb/enUwzdh4E0xzttxHNQRoABOUCQYYmj+9QrCBACQHUoMM4AYga74ZDiRAmvnEwHwQGywGBOiGgA1A16wmJYjQDAJANkgMmyEosYBVMzIAuuTWs/cM6iuhfCCAGwDWrAHxKyFw68ZNuCE40wGygcga0AEkEEHRiIxxASzqUKKRHIAwAJgo4BgXwKIGxQUgf8MwOsAlh+EFUMDBMAxgE0MGoLwAignSMFQPzmgkDjAwAACSmn13nChk1QAAAABJRU5ErkJggg==')
98 project.ext.set("okImg1",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAD4SURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYLbSRh8wfc9/C5jmbLmPagjQACYoEwwwNLMxgzHMIJAcSA0ygBuArFm81gyi+ddfCAaywWJAgG4I2AB0zdxWkhCNMABkg8SwGYISC1g1IwOgS74ee87wsvkUVADJAJjpyIDbRAxMfz3zCkwjA5ghONMB2DVIBiDbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAA4gXvZorg7ZgAAAABJRU5ErkJggg==')
99 project.ext.set("okImg2" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADjSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPbWZ7Jg2lvqMZjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGuetFsUTCMDmBi6IWAD0DUra3OA2cgAJIbNEJRYwKUZGdy9+oMhz/U1lIdkADZnwwwDaUIHMENwpgNk16DbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAAZD3X55epfOAAAAABJRU5ErkJggg==')
100 project.ext.set("errorImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADlSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPZbGRUwLfzkDpjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGtexisCppEBTAzdELAB6Jrd+QXAbGQAEsNmCEos4NKMDHZ+/MAQ9fkNlIdkADZnwwwDaUIHyIaADMDAQAP/AwMPjEFsbGpAGGs6AEUPsnfgzsaiDiUayQUgF2A4jaAXoHpQXAByNgyjA1xyGF4A+RuGYQCbGDLA6gWCGKoHJSGRDhgYAL/hkunRq+joAAAAAElFTkSuQmCC')
101 project.ext.set("unavailableImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABJ0AAASdAHeZh94AAAAB3RJTUUH4QwNDgEDrNoaqgAAAOhJREFUOMulkz8OgjAUhz8MQ7mBkwnnkBAH4mbCCdxcXLwAoxdwYXHjBCRupoMheg4TJ29QNhwshMofSfpLOry2v6/vta8OUGEhF4DsbUx6L8XytkNKCUAURTxWZ9TCM93buQb8mFXiI4E43gCQ5xeQPt7x2YG4fWa0OQwDhBANRCVdyGyKOQyDJhuV+HgvZQLGzABCiEGI036FPnNbZVlSFPfvnWg1gJpea72OjPh6lUZcQ5yhPkjTkxHv94fpfcB23t81PftmWMr9e+pQZjobd6zuobX2fViXAFCRvSv9GtOH9ji23/kDswRrCVqtQOAAAAAASUVORK5CYII=')
102
103
104 //health params
105 project.ext.set("trayIcon", null)
106 project.ext.set("lastStatus", null)
107 project.ext.set("isStopHealthCheck", false)
108 project.ext.set("isHaltHealth", new AtomicBoolean(false) )
109 project.ext.set("startedAwait", Long.MAX_VALUE)
110 project.ext.set("logFile", 'C:/ProgramData/all.log')
111 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
112 project.ext.set("pomChangesMap" , [:] )
113 project.ext.set("beConfigFilesToCopyMapping" , [ 'src/main/resources/config/*.yaml' : 'config/catalog-be/' ,
114                                                'src/main/resources/config/*.properties' : 'config/catalog-be/'] )
115
116 //menu item strings
117 project.ext.set("toggleHealthString" , "Halt Health" )
118 //menu item
119 project.ext.set("toggleHealthItemView" , null )
120
121 //other
122 project.ext.set("IS_MVN_INSTALL",false)
123 project.ext.set("executor" , null )
124 project.ext.set("lockObj" , new Object() )
125
126 def hash( List list ){
127     def map = list?.collectEntries { File file -> [(file?.absolutePath) : file?.text?.hashCode() ]}
128
129     map
130 }
131
132 def pomChanges(){
133     long started = System.currentTimeMillis()
134     if ( !pomList )
135         listPom()
136     //find hash changes
137     def changes = pomList?.findAll {
138         def File file = new File(it);
139         pomChangesMap[it] != file?.text?.hashCode()
140     }
141     println "\n\n[MasterD][POM]--> detected changes for -> $changes"
142     //update changes in map
143     changes?.each { pomChangesMap[it] = new File(it)?.text?.hashCode() }
144     println "\n\n[MasterD][POM]--> pom map -> $pomChangesMap"
145
146     println """
147             ****** POM changes detection finished after -> ${System.currentTimeMillis()- started}ms  ******
148             """
149
150     changes
151 }
152 //list pom with updated file hashes
153 def listPom(){
154     long started = System.currentTimeMillis()
155     if (!pomList) {
156         def tree = fileTree( PROJECT_PATH ).include '**/pom.xml'//.filter { it.isFile() && it?.toString()?.toLowerCase()?.endsWith('pom.xml') }
157         //println "$PROJECT_PATH list is ->${ list?.collect { it?.absolutePath } }"
158         //flatten and filter openecomp poms
159         pomList = tree?.flatten()?.findAll { File file -> file?.text?.contains('org.openecomp.sdc') }?.collect {File file -> file?.absolutePath }
160     }
161     pomChangesMap = pomList.collectEntries { absolutePath ->[ ( absolutePath ) : new File(absolutePath)?.text?.hashCode() ] }
162
163     println """ [MasterD][Init] intializing POM detector
164
165             *********       POM listing finished after -> ${System.currentTimeMillis()- started}ms    *********
166             """
167     return pomList
168 }
169
170
171 task initialization(){
172     listPom()
173     executor = Executors.newCachedThreadPool();
174 }
175
176 def parallel( closure ){
177     executor?.submit(new Callable<Object>(){
178         @Override
179         public Object call() {
180             closure();
181             return null;
182         }
183     })
184 }
185 /*class Preferences {
186     def String Username
187     def String IsNewVagrant
188     def String IsRapidMode
189 }
190
191 def initXFolder(){
192     def folder = new File(X_FOLDER);
193     folder?.exists() ?: folder?.mkdirs()
194
195     new File("${folder?.absolutePath}/$PREFERENCES_FILENAME")
196 }*/
197
198 task tester{
199     /*doLast{
200         //postStat(10000, "shay" , "report/index")
201         listPom()
202         new File('catalog-be\\pom.xml') << "#hello"
203         pomChanges()
204     }*/
205 }
206
207
208 def fetchFilesByExtention(remote, local , ext ){
209     ssh.run {
210         def started = System.currentTimeMillis()
211         println "folder diff"
212         session(remotes.vagrant) {
213             //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
214             get from: remote  , into: local , filter: {  it?.absolutePath =~ /jetty.*catalog-be.*\.dir.*\.$ext/  } // {  it?.absolutePath =~ /.*catalog-be.*dir.*classes.*/  }
215         }
216         println "fetched files in ${System.currentTimeMillis() - started} ms"
217     }
218 }
219
220 def updateRemoteFile(String remote , String local){
221     ssh.run {
222         def to = "$BE_REMOTE${remote[remote?.indexOf("tmp\\")..remote.size()-1].replaceAll("\\\\","/")}"
223         println "copying $local \nto\n $to"
224         session(remotes.vagrant) {
225             put from: local  , into: to }
226     }
227 }
228
229 def compareAndSwap(){
230     def final LIMIT = 10
231     def newClasses = new File("$PROJECT_PATH\\catalog-be\\target\\classes")
232     def File jettyClasses ;
233     //locate classes
234     println "traversing.."
235     new File("build/hotswap").traverse { if (it?.directory && it?.name?.equals("classes")){
236         jettyClasses = it
237         return;
238     }  }
239     def jettyClassesList = []
240     jettyClasses?.traverse { jettyClassesList << it }
241
242     println "$jettyClasses"
243     //Sort compiled classes
244     def files = []
245     newClasses?.traverse {  files << it }
246     def result = files.sort{ a,b -> b.lastModified() <=> a.lastModified() }
247     println "show only last $LIMIT changes"
248     result[0..LIMIT]?.each{ println it?.lastModified() +" | "+ it?.name + (it?.directory ? "[Directory]" : "") } //show only last 10 changes
249
250     //update
251     def changesMap = [ : ] //<old,new>
252     println "updating changes"
253     result[0..LIMIT]?.each { File f -> def File other = jettyClassesList.find{ File other-> other?.absolutePath?.endsWith(f?.name) };
254         if ( !(f.directory) && f?.text?.hashCode() != other?.text?.hashCode() )
255             updateRemoteFile( other?.getAbsolutePath() , f?.getAbsolutePath() )
256     } //use hashing
257 }
258
259 task hotswap(){
260     doLast {
261         new File("build/hotswap")?.deleteDir()
262         new File("build/hotswap")?.mkdirs()
263         ssh.settings {
264             knownHosts = allowAnyHosts
265         }
266         fetchFilesByExtention( "$BE_REMOTE/tmp/" , 'build/hotswap' , "class")
267         compareAndSwap()
268     }
269 }
270
271 remotes {
272     vagrant {
273         host = '127.0.0.1'
274         port = 2222
275         user = VAGRANT_USER
276         password = VAGRANT_PASSWORD
277         identity = isProductionVM() ? new File(RSA_PRIVATE_KEY_PATH) : null
278     }
279
280 }
281
282 def isProductionVM(){
283   return VM_TYPE?.equals(Environment.PROD_VAGRANT)
284 }
285
286 def isOnapVM(){
287     return VM_TYPE?.equals(Environment.ONAP_VAGRANT)
288 }
289
290 def gitLatest(){
291
292 }
293
294 def newEcoSystem(){
295     //cleanTitan()
296     backupDB() //and clean all
297     //restoreDB() //restore latest
298     createSchema()
299     fillSchema()
300     postCreate()
301     startAll()
302     //todo- conside updating from git
303     updaterBEFull()
304     updaterFE()
305 }
306 def importHeatTypes(){
307    //todo- impl
308 }
309 def postCreate(){
310     importNormative()
311     importHeatTypes()
312 }
313 def fillSchema(){
314     // add conformence level
315 }
316 def createSchemaPreStep(){
317     //todo- DB up
318 }
319 def createSchemaPostStep(){
320     ////todo- impl create amdocs dox
321 }
322 def createSchema(){
323     createSchemaPreStep()
324     //todo- create schema
325     //todo- create titan
326     createSchemaPostStep()
327 }
328
329 def cleanTitan(){
330     execSafe{
331         ssh.settings {
332             knownHosts = allowAnyHosts
333         }
334         ssh.run {
335             session(remotes.vagrant) {
336                 execute "sudo cqlsh -e 'DROP KEYSPACE titan;'"
337                 println "[MasterD][DB_DROP]-> Dropped 'titan' KEYSPACE."
338             }
339         }
340     }
341 }
342 task cleanTitan {
343     doLast{
344         cleanTitan()
345     }
346 }
347
348 task fetchE2EDB(){
349     doLast{
350         fetchE2EDB()
351     }
352 }
353 def fetchE2EDB(){
354     execSafe{
355         ssh.settings {
356             knownHosts = allowAnyHosts
357         }
358         ssh.run {
359             session(remotes.vagrant) {
360                 def tmp = '$CASSANDRA_HOME/backup/e2e'
361                 //execute 'mkdir $CASSANDRA_HOME/backup/e2e/'
362                 //execute 'wget http://135.76.210.202:8080/ETE_backup_files/latest_ETE_backup_file.zip -P /vagrant/db'
363                 println "[MasterD] download finished, unzipping.."
364                 execute "unzip -u $tmp/latest_ETE_backup_file.zip" //execute 'unzip -u /vagrant/db/latest_ETE_backup_file.zip'//'
365                 def folder = execute "cd $tmp; ls -d -- */"
366                 println "[MasterD] unzipping finished into -> $folder , untaring.."
367                 execute "tar zxf $tmp/$folder/* --strip 3 -C" +'$CASSANDRA_HOME/data | pv -l >/dev/null'
368                 println "[MasterD][E2E_DB]-> Downloaded & unzipped e2e data successfully."
369             }
370         }
371     }
372 }
373 def copyExplodedBE() {
374     execSafe{
375         println "[MasterD][BackEnd] copying exploded war."
376         ssh.settings {
377             knownHosts = allowAnyHosts
378         }
379         long started = System.currentTimeMillis()
380         def dirPath = "${PROJECT_PATH}/catalog-be/target/catalog-be-1.1.0-SNAPSHOT"
381         def dir = new File(dirPath);
382         println "[MasterD][BackEnd] copying ${dir?.directorySize()/(1024*1024)} MB, from ${dir?.name} to $BE_REMOTE/webapps"
383                 ssh.run {
384                     session(remotes.vagrant) {
385                         execute "rm -R $BE_REMOTE/webapps/catalog-be-1.1.0-SNAPSHOT"
386                         put from: dir?.absolutePath , into: "$BE_REMOTE/webapps"
387                     }
388                 }
389         println "[MasterD][BackEnd] Successfully copied exploded war in ${System.currentTimeMillis()-started}ms."
390     }
391 }
392 task copyExplodedBE(){
393     doLast{
394         copyExplodedBE()
395     }
396 }
397 def backupDB() {
398     execSafe{
399         ssh.settings {
400             knownHosts = allowAnyHosts
401         }
402         ssh.run {
403             session(remotes.vagrant) {
404                 execute 'mkdir -p $CASSANDRA_HOME/backup'
405                 def res = execute 'mv $CASSANDRA_HOME/data $CASSANDRA_HOME/backup/data_$(date +\'%Y_%m_%d__%H:%M:%S\')'
406                 println "[MasterD][DB_BACKUP]-> snapshot DB finished. $res"
407             }
408         }
409     }
410 }
411 task backupDB{
412     doLast{
413         backupDB()
414     }
415 }
416
417 def restoreDB(){
418     execSafe{
419         ssh.settings {
420             knownHosts = allowAnyHosts
421         }
422         ssh.run {
423             session(remotes.vagrant) {
424                 println "[MasterD]-> restoring DB"
425                 execute 'mkdir -p $CASSANDRA_HOME/data'
426                 def res = execute 'mv $CASSANDRA_HOME/backup/data_*/* $CASSANDRA_HOME/data'
427                 println "[MasterD]-> DB restore FINISHED!! $res"
428             }
429         }
430     }
431 }
432 task restoreDB() {
433     doLast {
434         restoreDB()
435     }
436 }
437
438 def vm( ){
439     exec{
440         if (VAGRANT_HOME){
441             workingDir VAGRANT_HOME     //vagrant path
442             println "*****************\nworking dir -> $VAGRANT_HOME"
443             commandLine "cmd","/c", "vagrant up"
444             //args = [ ]
445         } else {
446             println "[MasterD]--> please define windows enviroment variable VAG pointing to vagrant project"
447         }
448     }
449 }
450
451 task vm{
452     doLast{
453         vm()
454     }
455 }
456
457 def copyFE() {
458     println "[MasterD][FrontEnd] starting war copy."
459     ssh.settings {
460         knownHosts = allowAnyHosts
461     }
462     long started = System.currentTimeMillis()
463     def target = "${PROJECT_PATH}/catalog-fe/target/"
464     def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
465     files?.each{ File file ->
466         if (!file?.name?.contains('classes')){
467             println "[MasterD][FrontEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $FE_REMOTE/webapps"
468             ssh.run {
469                 session(remotes.vagrant) {
470                     if ( isProductionVM() )
471                         execute 'sudo chmod -R 777 /opt/app/jetty/base/fe/webapps'
472                     put from: file?.absolutePath , into: "$FE_REMOTE/webapps"
473                 }
474             }
475         }
476
477     }
478     println "[MasterD][FrontEnd] Successfully copied war in ${System.currentTimeMillis()-started}ms."
479 }
480
481 task deployFE{
482     doLast {
483         copyFE()
484     }
485 }
486
487
488 def copyBE(){
489     println "[MasterD][BackEnd] starting war copy."
490     ssh.settings {
491         knownHosts = allowAnyHosts
492     }
493     def target = "${PROJECT_PATH}/catalog-be/target/"
494     def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
495     long started = System.currentTimeMillis()
496     files?.each{ File file ->
497         if (!file?.name?.contains('classes')){
498             println "[MasterD][BackEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $BE_REMOTE/webapps"
499             ssh.run {
500                 session(remotes.vagrant) {
501                     if (isProductionVM())
502                         execute 'sudo chmod -R 777 /opt/app/jetty/base/be/webapps'
503                     put from: file?.absolutePath , into: "$BE_REMOTE/webapps"
504                 }
505             }
506         }
507     }
508     println "[MasterD][BackEnd] SUCCESSFULY copied be war in ${System.currentTimeMillis()-started}ms."
509 }
510
511 task deployBE {
512     doLast {
513         copyBE()
514     }
515 }
516 def compileFE(){
517     exec{
518         println "[MasterD][FE]--> compiling project at -> ${PROJECT_PATH}\\catalog-fe"
519         workingDir "${PROJECT_PATH}"    //vagrant path
520         commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-fe,catalog-ui -am -Pcatalog -Dmaven.test.skip'
521     }
522 }
523 task compileFE(){
524     doLast{
525         compileFE()
526     }
527 }
528 def compileBE(){
529     exec{
530         println "[MasterD][BE]--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
531         workingDir "${PROJECT_PATH}"    //vagrant path
532         commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-be -Pcatalog -Dmaven.test.skip'
533     }
534 }
535 task compileBE{
536     doLast{
537         compileBE()
538     }
539 }
540
541 def compile(){
542     exec{
543         println "[MasterD]--> compiling project at -> ${PROJECT_PATH}"
544         workingDir "${PROJECT_PATH}"    //vagrant path
545         commandLine 'cmd','/c','mvn -T 2 compile -am -Pcatalog -Dmaven.test.skip'
546     }
547 }
548
549 task compile{
550     doLast{
551         compile()
552     }
553 }
554 def compileDependencies(){
555     def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
556     exec{
557         println "[MasterD]--> compiling BE dependencies  -> $BE_DEPENDENCIES [ SKIPPING TESTS!! ]"
558         workingDir "${PROJECT_PATH}"    //vagrant path
559         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'
560     }
561 }
562 task compileDependencies {
563     doLast{
564         compileDependencies()
565     }
566 }
567 def compileWar(){
568     def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
569     exec{
570         println "--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
571         workingDir "${PROJECT_PATH}"    //vagrant path
572         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'
573     }
574 }
575 task compileWar(){
576     doLast{
577         compileWar()
578     }
579 }
580
581 //deprecated - use deployBE()
582 task be() {
583     doLast{
584         def started = System.currentTimeMillis();
585         exec{
586             println "[MasterD]--> copying be... [from $VAGRANT_HOME]"
587             workingDir VAGRANT_HOME     //vagrant path
588             commandLine 'cmd','/c', 'copy_war_be.bat','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
589             //args = [ ]
590         }
591         println """
592                 ****    copying finished in -> ${System.currentTimeMillis() - started}ms         ****
593                 """
594     }
595 }
596
597 task beConfig( ) {
598     doLast{
599         exec{
600             workingDir "${System.env.VAG}"      //vagrant path
601             commandLine 'cmd','/c','copy_war_be_with_configuration','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
602             //args = [ ]
603         }
604     }
605
606 }
607 task feConfig( ) {
608     doLast{
609         exec{
610             workingDir "${System.env.VAG}"      //vagrant path
611             commandLine 'cmd','/c','copy_war_fe_with_configuration','localhost' , "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war" , "$FE_REMOTE/webapps"
612             //args = [ ]
613         }
614     }
615
616 }
617
618 task fe() {
619     doLast{
620         exec {
621             workingDir "${System.env.VAG}"    //vagrant path
622             commandLine 'cmd','/c', 'copy_war_fe.bat', 'localhost', "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war", "$FE_REMOTE/webapps"
623             //args = [ ]
624         }
625     }
626 }
627
628 def installAllProject(){
629     exec{
630         println "[MasterD]--> Compiling&Installing project at -> ${PROJECT_PATH}"
631         workingDir "${PROJECT_PATH}"    //vagrant path
632         commandLine 'cmd','/c','mvn -T 2 clean install -U -Pcatalog -Dmaven.test.skip'
633     }
634 }
635 task installAllProject {
636     doLast {
637         installAllProject()
638     }
639 }
640
641 task installAll {
642     doLast{
643         println '[MasterD]--> Finished!!'
644     }
645 }
646 installAll.dependsOn { tasks.findAll { task -> task.name.startsWith('install_') } }
647
648 def install_BE(){
649     exec {
650             println '[MasterD][Install]--> Installing BE!!'
651             workingDir "${PROJECT_PATH}"
652             commandLine 'cmd','/c', 'mvn clean install -pl catalog-be -am -Pcatalog -Dmaven.test.skip'
653             //args = [ ]
654     }
655 }
656
657 task install_BE() {
658     doLast{
659         install_BE()
660     }
661 }
662
663 def install_FE() {
664     exec {
665         workingDir "${PROJECT_PATH}"
666         commandLine 'cmd','/c', 'mvn clean install -pl catalog-ui,catalog-fe -am -Pcatalog -Dmaven.test.skip'
667     }
668 }
669 task install_FE() {
670     doLast {
671         install_FE()
672     }
673 }
674
675 def updaterBERapid(){
676     /* if ( ticket() > PREVIOUS_BUILD_VAR ){
677      PREVIOUS_BUILD_VAR = ticket()*/
678     def started = System.currentTimeMillis();
679     println "[MasterD][Rapid]--> compiling changes using maven"
680     compileWar()
681     println "[MasterD][Rapid]--> copying war"
682     copyBE() //use this if you want to deploy entire war //hotswap.execute()
683     restartBackend()
684     println msg(" redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
685 }
686 task updaterBERapid(){
687     doLast {
688         updaterBERapid()
689     }
690 }
691 def updaterBE(){
692     def started = System.currentTimeMillis();
693     IS_MVN_INSTALL = pomChanges() ? true :  false
694     println "[MasterD]--> compiling changes using maven"
695     compileDependencies()
696     compileWar()
697     println "[MasterD]--> copying war"
698     IS_HOTSWAP ? copyExplodedBE() : copyBE() //execute() //use this if you want to deploy entire war //hotswap.execute()
699     restartBackend()
700     println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
701 }
702 task updaterBE(){
703     doLast {
704         updaterBE()
705     }
706 }
707 def copyBEConfiguration(){
708 /*    execSafe {
709         ssh.settings {
710             knownHosts = allowAnyHosts
711         }
712         ssh.run {
713             session(remotes.vagrant) {
714                 println msg("Stopping BackEnd Server")
715                 execute command[BACKEND][STOP]()
716             }
717         }
718     }*/
719 }
720 def updaterBEFull(){
721     def started = System.currentTimeMillis();
722     compile()
723     println "[MasterD]--> copying war"
724     copyBE() //use this if you want to deploy entire war //hotswap.execute()
725     copyBEConfiguration()
726     println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
727 }
728 task updaterBEFull(){
729     doLast {
730         updaterBEFull()
731     }
732 }
733 def copyFEConfiguration(){
734     //todo- implement
735 }
736 def updaterFE(){
737     def started = System.currentTimeMillis();
738     println "[MasterD]--> compiling changes using maven"
739     compileFE()
740     println "[MasterD]--> copying war"
741     copyFE() //.execute() //use this if you want to deploy entire war //hotswap.execute()
742     copyFEConfiguration()
743     println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
744 }
745 task updaterFE(){
746     doLast {
747       updaterFE()
748     }
749 }
750 def stopBackend(){
751     execSafe {
752         ssh.settings {
753             knownHosts = allowAnyHosts
754         }
755         ssh.run {
756             session(remotes.vagrant) {
757                 println msg("Stopping BackEnd Server")
758                 execute command[BACKEND][STOP]()
759             }
760         }
761     }
762 }
763 task stopBackend(){
764     doLast {
765         stopBackend()
766     }
767 }
768
769 def startBackend(){
770     execSafe {
771         ssh.settings {
772             knownHosts = allowAnyHosts
773         }
774         ssh.run {
775             session(remotes.vagrant) {
776                 println msg("[MasterD] starting backend sever")
777
778                 execute command[BACKEND][START]()
779             }
780         }
781     }
782     println """[MasterD]->  finished !!
783                                             """
784 }
785 task startBackend(){
786     doLast{
787         startBackend()
788     }
789 }
790
791 def restartBackend(){
792     execSafe {
793         ssh.settings {
794             knownHosts = allowAnyHosts
795         }
796         ssh.run {
797             session(remotes.vagrant) {
798                 println msg("[MasterD] restarting backend server")
799
800                 execute command[BACKEND][RESTART]()
801             }
802         }
803     }
804     println """[MasterD]->  finished !!
805                                             """
806 }
807
808 def startSecurity(){
809     println "[MasterD] starting security&simulator engine"
810     execSafe {
811         ssh.settings {
812             knownHosts = allowAnyHosts
813         }
814         ssh.run {
815             session(remotes.vagrant) {
816                 execute command[SECURITY][START]()
817             }
818         }
819     }
820     println """[MasterD]->  finished !!
821                                             """
822 }
823 task startSecurity(){
824     doLast {
825         startSecurity()
826     }
827 }
828
829 def stopSecurity(){
830     println "[MasterD] stopping security&simulator engine"
831     execSafe {
832         ssh.settings {
833             knownHosts = allowAnyHosts
834         }
835         ssh.run {
836             session(remotes.vagrant) {
837                 execute command[SECURITY][STOP]()
838             }
839         }
840     }
841     println """[MasterD]->  finished !!
842                                             """
843 }
844
845 task stopSecurity(){
846     doLast {
847         stopSecurity()
848     }
849 }
850
851
852 //todo- remove this if you want to auto-deploy on every file save
853 /*
854 compileJava.doFirst{
855     updater?.execute()
856 }*/
857
858 enum STATUS { UP, DOWN , UNKNOWN , UNAVAILABLE }
859
860 task health(){
861     doLast {
862         prepareTray()
863     }
864 }
865
866 def execSafe( closure){
867    if (!lockObj) {
868         [0..4].forEach( {println "Critical ERROR : lock object is not initialized\n\nCritical ERROR : cannot run tasks\n"}() )
869         return;
870    }
871    synchronized (lockObj){
872            boolean prev = isHaltHealth.get()
873            try {
874                isHaltHealth.set(true)
875                closure()
876            } catch (Exception e) {
877                println e
878            } finally {
879                isHaltHealth.set(prev)
880            }
881    }
882 }
883
884 def fetchFiles( remote, local ){
885     ssh.run {
886         session(remotes.vagrant) {
887             //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
888             def f = get from: remote  , into: local
889             println f?.name
890             //return f
891         }
892         //println "fetched files in ${System.currentTimeMillis() - started} ms"
893     }
894
895     //return null
896 }
897
898
899 def killJava(){
900     execSafe {
901         def res
902         ssh.run {
903             session( remotes.vagrant ) {
904                 println """                                      *-*-****************************-*-*
905                                                                 killing all java proccesses
906                                                 *-*-****************************-*-*
907                                         """
908                 res = execute command[ALL][KILL]()
909             }
910         }
911         println res?.toString()
912     }
913 }
914
915 def importNormative(){
916     execSafe {
917         ssh.run {
918             session(remotes.vagrant) {
919                 println """                                      *-*-************************************-*-*
920                                                                                         importNormative
921                                                                 *-*-************************************-*-*
922                                                         """
923                 execute "sudo python -v $BE_REMOTE/scripts/import/tosca/importNormativeAll.py"
924             }
925         }
926     }
927 }
928
929 def startAll(){
930     def startCassandra = """
931                         #!/bin/bash
932
933                         cassandra&
934                         elasticsearch -d
935
936                         #Wait until ES is up
937                         until curl localhost:9200/_cluster/health;
938                         do
939                             printf "."
940                             sleep 3
941                         done
942
943                         # Create Elastic Mapping if not exist in ES
944                         createESMapping.sh
945                         """
946     execSafe {
947         ssh.run {
948             session(remotes.vagrant) {
949                 println """                                      *-*-************************************-*-*
950                                                                 starting all SDC services(DB,BE,FE,Webseal)
951                                                         *-*-************************************-*-*
952                                 """
953                 if ( isProductionVM() ){
954                     execute command[DB][START]()
955                     Thread.sleep(5000)
956                     execute command[CACHING][START]()
957                 }
958                 else
959                     execute startCassandra
960                 //[0..4]?.forEach( Thread?.sleep(2000) )
961                 Thread?.sleep(10000)
962                 Thread?.sleep(10000)
963                 execute command[BACKEND][START]()
964                 execute command[FRONTEND][START]()
965                 execute command[SECURITY][START]()
966             }
967         }
968     }
969 }
970
971
972 /*def clearLog(type: Delete){
973     delete{
974         delete 'C:/ProgramData/all.log'
975         followSymlinks = true
976     }
977 }*/
978 task clearLog(type: Delete){
979     doLast{
980         delete 'C:/ProgramData/all.log'
981         followSymlinks = true
982     }
983 }
984 def logBE(){
985     try{
986         println "\n*** logging BE all.log ***\n"
987
988             ssh.run {
989                 session( remotes.vagrant ) {
990                     //String now = execute 'echo \"\$(date +\'%Y_%m_%d\')\"'
991                     //println "\n\n*******************************************************\n\n"+now?.toString()
992                     clearLog?.execute() //todo- remove this .execute()
993                     fetchFiles( '/home/vagrant/catalog-be/logs/SDC/SDC-BE/all.log' , 'C:/ProgramData') //"%USERPROFILE%\AppData\Local\")
994                     //project.ext.set( "logFile" , 'C:/ProgramData/all.log' )
995
996                     //                          -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*'
997                 }
998             }
999
1000         parallel {
1001             exec {
1002                 //if ( logFile ){
1003                 String notepad = 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe'
1004                 println "logging $logFile to notepad++ [$notepad]"
1005                 commandLine 'cmd','/c' , notepad ,logFile
1006             }
1007         }
1008     }catch(Exception e){
1009         println "cannot open logs!!!"
1010         e.printStackTrace()
1011     }
1012 }
1013 task logBE(){
1014     doLast{
1015         logBE()
1016     }
1017 }
1018
1019 def toggleHealthPolling(){
1020     isHaltHealth.set(!isHaltHealth.get())
1021 }
1022 //converts predefined icon to Image
1023 def Image convert( imageName ){
1024     String encodedimage = project.ext.get(imageName);
1025     byte[] byteImage = encodedimage?.split(',')[1]?.decodeBase64()
1026     Image image = ImageIO.read(new ByteArrayInputStream(byteImage));
1027 }
1028
1029 def refreshMenu(String imageName){
1030     switch( imageName ) {
1031         case 'unavailableImg' : toggleHealthString = "Resume Health";  break;
1032         default : toggleHealthString = "Halt Health";
1033     }
1034     if (((MenuItem)toggleHealthItemView).getLabel() != toggleHealthString)
1035         ((MenuItem)toggleHealthItemView).setLabel(toggleHealthString);
1036 }
1037 def startDB(){
1038         println "[MasterD] Starting database.."
1039         execSafe {
1040             ssh.settings {
1041                 knownHosts = allowAnyHosts
1042             }
1043             ssh.run {
1044                 session(remotes.vagrant) {
1045                     execute command[DB][START]()
1046                 }
1047             }
1048         }
1049 }
1050 task startDB(){
1051     doLast {
1052         startDB()
1053     }
1054 }
1055 def stopDB(){
1056     execSafe {
1057         ssh.settings {
1058             knownHosts = allowAnyHosts
1059         }
1060         ssh.run {
1061             session(remotes.vagrant) {
1062                 execute command[DB][STOP]()
1063             }
1064         }
1065     }
1066 }
1067 task stopDB(){
1068     doLast {
1069         stopDB()
1070     }
1071 }
1072 def startFE(){
1073     execSafe {
1074         ssh.settings {
1075             knownHosts = allowAnyHosts
1076         }
1077         ssh.run {
1078             session(remotes.vagrant) {
1079                 execute command[FRONTEND][START]()
1080             }
1081         }
1082     }
1083 }
1084 task startFE(){
1085     doLast {
1086         startFE()
1087     }
1088 }
1089 def stopFE(){
1090     execSafe {
1091         ssh.settings {
1092             knownHosts = allowAnyHosts
1093         }
1094         ssh.run {
1095             session(remotes.vagrant) {
1096                 execute command[FRONTEND][STOP]()
1097             }
1098         }
1099     }
1100 }
1101 task stopFE(){
1102     doLast {
1103         stopFE()
1104     }
1105 }
1106
1107 def ActionListener newListener( closure  ){
1108     ActionListener listener = new ActionListener() {
1109         public void actionPerformed(ActionEvent e) {
1110             try {
1111                     closure()
1112             } catch (AWTException e1) {
1113                 System.err.println(e1);
1114             }
1115         }
1116     }
1117
1118     listener
1119 }
1120
1121 ext.updateTray = { STATUS status ->
1122     lastStatus = status
1123     if (SystemTray.isSupported()) {
1124         // get the SystemTray instance
1125         SystemTray tray = SystemTray.getSystemTray();
1126         // load an image
1127         String imageName = status==STATUS.UP ? (Math.random()>0.5 ?'okImg1':'okImg2') : status==STATUS.UNAVAILABLE ? 'unavailableImg' : status==STATUS.DOWN ? 'errorImg' : 'warnImg'
1128         Image image = convert imageName
1129         if (trayIcon != null) {
1130             trayIcon.setImage(image)
1131             refreshMenu(imageName);
1132             return ;
1133         }
1134         //region  -> Menu UI
1135         // create a popup menu
1136         PopupMenu popup = new PopupMenu();
1137         // create menu item for the default action
1138
1139         MenuItem hotswapItem = new MenuItem("===> WAR <===");
1140         hotswapItem.setFont(new Font("MONOSPACED" , Font.BOLD ,15f ))
1141
1142         //region Multilevel Menus
1143         Menu deployMasterMenu = new Menu("DeployMaster");
1144         Menu backendMenu = new Menu("Backend");
1145         Menu frontendMenu = new Menu("Frontend");
1146         Menu dbMenu = new Menu("Database");
1147         Menu securityMenu = new Menu("Security");
1148         try{
1149             deployMasterMenu.setFont(new Font("Cooper Black" ,Font.BOLD ,14f ))
1150             backendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
1151             frontendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
1152             dbMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
1153             securityMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
1154         }catch(Exception e){
1155             println e
1156         }
1157
1158         //DeployMaster Menu
1159         MenuItem updaterBeWithDependenciesItem = new MenuItem("[BE] Quick Compile -> Deploy");
1160         MenuItem updaterFullBeItem = new MenuItem("[BE] Full Install  -> Deploy");
1161         MenuItem updaterFeItem = new MenuItem("[FE] Quick Compile -> Deploy");
1162         MenuItem updaterFullFeItem = new MenuItem("[FE] Full Install -> Deploy");
1163
1164         //Menu UI build
1165
1166         deployMasterMenu.add(updaterFullBeItem);
1167         deployMasterMenu.add(updaterBeWithDependenciesItem);
1168
1169         deployMasterMenu.addSeparator();
1170         deployMasterMenu.add(updaterFullFeItem);
1171         deployMasterMenu.add(updaterFeItem);
1172
1173
1174         //BE menu
1175         MenuItem startItem = new MenuItem("[BE] Start");
1176         MenuItem stopItem = new MenuItem("[BE] Stop BackEnd");
1177         MenuItem copyBeWarItem = new MenuItem("[BE] Copy War");
1178         backendMenu.add(startItem);
1179         backendMenu.add(stopItem);
1180         (isOnapVM()) ?: backendMenu.add(copyBeWarItem);
1181
1182         //FE menu
1183         MenuItem startFEItem = new MenuItem("[FE] Start");
1184         MenuItem stopFEItem = new MenuItem("[FE] Stop");
1185         MenuItem copyFeWarItem = new MenuItem("[FE] Copy War");
1186         frontendMenu.add(startFEItem);
1187         frontendMenu.add(stopFEItem);
1188         (isOnapVM()) ?: frontendMenu.add(copyFeWarItem);
1189
1190         //DB menu
1191         MenuItem startDBItem = new MenuItem("[DB] Start");
1192         MenuItem stopDBItem = new MenuItem("[DB] Stop");
1193         MenuItem backupDBItem = new MenuItem("[DB] Backup");
1194         MenuItem restoreDBItem = new MenuItem("[DB] Restore");
1195         dbMenu.add(startDBItem);
1196         dbMenu.add(stopDBItem);
1197         dbMenu.add(backupDBItem);
1198         dbMenu.add(restoreDBItem);
1199         //endregion
1200         //Security Menu
1201         MenuItem startSecurityItem = new MenuItem("[Security] Start");
1202         MenuItem stopSecurityItem = new MenuItem("[Security] Stop");
1203         securityMenu.add(startSecurityItem)
1204         securityMenu.add(stopSecurityItem)
1205
1206         MenuItem killItem = new MenuItem("Kill All");
1207         MenuItem startAllItem = new MenuItem("Start All");
1208         MenuItem importItem = new MenuItem("Import Normative");
1209         MenuItem healthInfoItem = new MenuItem("[Info] Health");
1210         MenuItem toggleHealthItem = new MenuItem(toggleHealthString);
1211         MenuItem logsItem = new MenuItem("Logs [Beta]");
1212         MenuItem exitItem = new MenuItem("Exit");
1213
1214         toggleHealthItemView = toggleHealthItem;
1215
1216         (isOnapVM()) ?: popup.add(hotswapItem);
1217         (isOnapVM()) ?:popup?.addSeparator();
1218         (isOnapVM()) ?: popup.add(deployMasterMenu);
1219         (isOnapVM()) ?:popup?.addSeparator();
1220         popup.add(backendMenu)
1221         popup.add(frontendMenu)
1222         (isOnapVM()) ?: popup.add(dbMenu)
1223         popup?.addSeparator();
1224         popup?.add(securityMenu)
1225         popup?.addSeparator();
1226         popup.add(startAllItem);
1227         popup.add(killItem);
1228         popup?.addSeparator();
1229         popup.add(toggleHealthItem);
1230         popup.add(healthInfoItem);
1231         (isOnapVM()) ?:popup?.addSeparator();
1232         (isOnapVM()) ?: popup.add(importItem);
1233         (isOnapVM()) ?: popup.add(logsItem);
1234         popup?.addSeparator();
1235         popup.add(exitItem);
1236         //endregion UI
1237         // construct a TrayIcon
1238         trayIcon = new TrayIcon(image, "HealthTray", popup);
1239
1240         //region -> Button actions
1241         def listenerHotswap = newListener { project.ext.set("IS_HOTSWAP", !IS_HOTSWAP); hotswapItem?.setLabel( IS_HOTSWAP ? "==> HotSwap <==" : "===> WAR <===")   }
1242         // create a action listener to listen for default action executed on the tray icon
1243         def listenerFullBE = newListener { parallel { install_BE(); IS_HOTSWAP ? copyExplodedBE() : copyBE(); restartBackend() } }
1244         def listenerFullFE = newListener { parallel { install_FE(); copyFE() } }
1245         ActionListener listenerFE = newListener { parallel { updaterFE() } }
1246         ActionListener listenerBE = newListener { parallel { updaterBE() } }
1247         ActionListener exitListener = newListener {
1248                     executor?.isShutdown() ?: executor?.shutdown()
1249                     tray.remove(trayIcon);
1250                     project.ext.set("isStopHealthCheck", true)
1251                     println "Shutting down.. bye bye.."
1252                 }
1253         ActionListener stopBackendListener = newListener { stopBackend() }
1254         ActionListener startBEListener = newListener { parallel { startBackend() } }
1255         ActionListener killJavaListener = newListener { killJava() }
1256
1257         ActionListener startAllListener = newListener { parallel { startAll() } }
1258
1259         ActionListener startSecurityListener = newListener { startSecurity() }
1260         ActionListener stopSecurityListener = newListener { stopSecurity() }
1261
1262         ActionListener listener5 = new ActionListener() {
1263             public void actionPerformed(ActionEvent e) {
1264                 try {
1265                     parallel { importNormative() }
1266                 } catch (AWTException e1) {
1267                     System.err.println(e1);
1268                 }
1269             }
1270         };
1271
1272         ActionListener listener6 = new ActionListener() {
1273             public void actionPerformed(ActionEvent e) {
1274                 try {
1275                     parallel { healthPopup() }
1276                 } catch (AWTException e1) {
1277                     System.err.println(e1);
1278                 }
1279             }
1280         };
1281
1282         ActionListener listener7 = new ActionListener() {
1283             public void actionPerformed(ActionEvent e) {
1284                 try {
1285                     logBE()//tasks.logger.execute()
1286                 } catch (AWTException e1) {
1287                     System.err.println(e1);
1288                 }
1289             }
1290         };
1291         ActionListener listener8 = new ActionListener() {
1292             public void actionPerformed(ActionEvent e) {
1293                 try {
1294                     toggleHealthPolling()//tasks.logger.execute()
1295                 } catch (AWTException e1) {
1296                     System.err.println(e1);
1297                 }
1298             }
1299         };
1300         ActionListener copyBeWarListener = new ActionListener() {
1301             public void actionPerformed(ActionEvent e) {
1302                 try {
1303                     parallel { copyBE() }//.execute()//tasks.logger.execute()
1304                 } catch (AWTException e1) {
1305                     System.err.println(e1);
1306                 }
1307             }
1308         };
1309
1310         ActionListener startDBListener = new ActionListener() {
1311             public void actionPerformed(ActionEvent e) {
1312                 try {
1313                     parallel {
1314                         startDB()
1315                     }//tasks.logger.execute()
1316                 } catch (AWTException e1) {
1317                     System.err.println(e1);
1318                 }
1319             }
1320         }
1321
1322         ActionListener stopDBListener = new ActionListener() {
1323             public void actionPerformed(ActionEvent e) {
1324                 try {
1325                     stopDB()//tasks.logger.execute()
1326                 } catch (AWTException e1) {
1327                     System.err.println(e1);
1328                 }
1329             }
1330         }
1331
1332         ActionListener dbBackupListener = new ActionListener() {
1333             public void actionPerformed(ActionEvent e) {
1334                 try {
1335                     parallel {
1336                         backupDB()//tasks.logger.execute()
1337                     }
1338                 } catch (AWTException e1) {
1339                     System.err.println(e1);
1340                 }
1341             }
1342         }
1343
1344         ActionListener feStartListener = new ActionListener() {
1345             public void actionPerformed(ActionEvent e) {
1346                 try {
1347                     parallel {
1348                         startFE()
1349                     }//tasks.logger.execute()
1350                 } catch (AWTException e1) {
1351                     System.err.println(e1);
1352                 }
1353             }
1354         }
1355
1356         ActionListener feStopListener = new ActionListener() {
1357             public void actionPerformed(ActionEvent e) {
1358                 try {
1359                     stopFE()//tasks.logger.execute()
1360                 } catch (AWTException e1) {
1361                     System.err.println(e1);
1362                 }
1363             }
1364         }
1365
1366         ActionListener feCopyListener = new ActionListener() {
1367             public void actionPerformed(ActionEvent e) {
1368                 try {
1369                     parallel {
1370                         copyFE() //.execute()//tasks.logger.execute()
1371                     }
1372                 } catch (AWTException e1) {
1373                     System.err.println(e1);
1374                 }
1375             }
1376         }
1377
1378
1379         //def listenerFullModules = newListener { parallel { installAllProject() } }
1380         //region -> Button<=Listener
1381         hotswapItem.addActionListener(listenerHotswap)
1382         updaterFeItem.addActionListener(listenerFE)
1383         updaterFullBeItem.addActionListener( listenerFullBE )
1384         updaterBeWithDependenciesItem.addActionListener( listenerBE )
1385         updaterFullFeItem.addActionListener( listenerFullFE )
1386         stopItem.addActionListener(stopBackendListener)
1387         startItem.addActionListener(startBEListener)
1388         copyBeWarItem.addActionListener(copyBeWarListener);
1389         startSecurityItem.addActionListener(startSecurityListener)
1390         stopSecurityItem.addActionListener(stopSecurityListener)
1391         killItem.addActionListener(killJavaListener)
1392         startAllItem.addActionListener(startAllListener)
1393         importItem.addActionListener(listener5)
1394         healthInfoItem.addActionListener(listener6)
1395         toggleHealthItem.addActionListener(listener8)
1396         logsItem.addActionListener(listener7)
1397         exitItem.addActionListener(exitListener)
1398
1399         startDBItem.addActionListener( startDBListener )
1400         stopDBItem.addActionListener( stopDBListener )
1401         backupDBItem.addActionListener( dbBackupListener )
1402         copyFeWarItem.addActionListener( feCopyListener )
1403         startFEItem.addActionListener( feStartListener )
1404         stopFEItem.addActionListener( feStopListener )
1405         //endregion
1406         //endregion
1407         // set the TrayIcon properties
1408
1409         // ...
1410         // add the tray image
1411         try {
1412             tray.add(trayIcon);
1413
1414         } catch (AWTException e) {
1415             System.err.println(e);
1416         }
1417         // ...
1418     } else {
1419         println "Java TrayIcon Option is not supported in your System, try enabling it. Bye Bye"
1420     }
1421
1422 }
1423
1424 def prepareTray(){
1425     long UPDATE_THRESHOLD = 3500
1426     float SCALAR = 1
1427     ssh.settings {
1428         knownHosts = allowAnyHosts
1429     }
1430     while(!isStopHealthCheck) {
1431         if (!isHaltHealth.get()) {    //if await or await is more then 60 second return health check
1432             ssh.run {
1433                 session(remotes.vagrant) {
1434                     try {
1435                         def healthOutput = execute command[ALL][HEALTH]()
1436                         if (healthOutput?.contains("Failed command .* with status 7") || healthOutput?.contains("Problem accessing /sdc2/rest/healthCheck"))
1437                             updateTray(STATUS.DOWN)
1438                         def statusCollecion = healthOutput?.findAll "\"healthCheckStatus\": \".*\""
1439                         def upCount = statusCollecion?.count { it?.contains("UP") }
1440                         def downCount = statusCollecion?.count { it?.contains("DOWN") }
1441                         def uknownCount = (statusCollecion?.size() - upCount) - downCount
1442                         println " UP -> $upCount | downCount=$downCount | uknownCount=$uknownCount "
1443                         (uknownCount > 0 || (downCount > 0 && upCount > 0)) ? updateTray(STATUS.UNKNOWN) : ((upCount > 0) ? updateTray(STATUS.UP) : updateTray(STATUS.DOWN))
1444                         SCALAR = 1
1445                     } catch (Exception e) {
1446                         updateTray(STATUS.DOWN)
1447                         println e
1448                         SCALAR = Math.min(SCALAR * 1.1, 5) //slow down on errors
1449                     }
1450                     //green color effects
1451                     if (lastStatus && lastStatus == STATUS.UP) {
1452                         trayIcon.setImage(convert(Math.random() > 0.5 ? 'okImg1' : 'okImg2'))
1453                         //randomly green change color
1454                     }
1455                     Thread.yield()
1456                     Thread?.sleep((long) (UPDATE_THRESHOLD * SCALAR))
1457                 }
1458             }
1459         }else{
1460             updateTray(STATUS.UNAVAILABLE)
1461             Thread.yield()
1462         }
1463     }
1464 }
1465
1466 def healthPopup(){
1467     ssh.run {
1468         session(remotes.vagrant) {
1469             def healthOutput = execute command[ALL][HEALTH]()
1470             JOptionPane.showMessageDialog(null,
1471                     healthOutput,
1472                     "HEALTH",
1473                     JOptionPane.INFORMATION_MESSAGE);
1474         }
1475     }
1476 }
1477
1478 project.ext.set("msg", { content -> """
1479                         ************************************************************************************************
1480                         ************************************************************************************************
1481                         *******                                                                                *********
1482                         **************                                                                  ****************
1483                                                 $content      
1484
1485                         ************************************************************************************************
1486                         ************************************************************************************************
1487                         """} )