JAL-3210 improved gradle jalviewjsServerStart
[jalview.git] / build.gradle
1 import org.apache.tools.ant.filters.ReplaceTokens
2 import org.gradle.internal.os.OperatingSystem
3 import org.gradle.plugins.ide.eclipse.model.*
4 import groovy.transform.ExternalizeMethods
5
6
7 plugins {
8   id 'java'
9   id 'application'
10   id 'eclipse'
11 }
12
13 repositories {
14   jcenter()
15   mavenCentral()
16   mavenLocal()
17   flatDir {
18     dirs gradlePluginsDir
19   }
20 }
21
22 mainClassName = launcherClass
23 def classes = "$jalviewDir/$classesDir"
24
25 // configure classpath/args for j8/j11 compilation
26
27 def jalviewDirAbsolutePath = file(jalviewDir).getAbsolutePath()
28 def libDir
29 def libDistDir
30 def compile_source_compatibility
31 def compile_target_compatibility
32
33 ext {
34   buildProperties = jalviewDir + "/" + classesDir +"/" + buildPropertiesFile
35
36   gitHash = ""
37   gitBranch = ""
38
39   jalviewjsServer = ""
40 }
41
42 def JAVA_INTEGER_VERSION
43 //def additional_compiler_args = []
44 // this property is for the Java library used in eclipse
45 def eclipse_java_runtime_name
46 if (JAVA_VERSION.equals("1.8")) {
47   JAVA_INTEGER_VERSION = "8"
48   //libDir = j8libDir
49   libDir = j11libDir
50   libDistDir = j8libDir
51   compile_source_compatibility = 1.8
52   compile_target_compatibility = 1.8
53   eclipse_java_runtime_name = "JavaSE-1.8"
54 } else if (JAVA_VERSION.equals("11")) {
55   JAVA_INTEGER_VERSION = "11"
56   libDir = j11libDir
57   libDistDir = j11libDir
58   compile_source_compatibility = 11
59   compile_target_compatibility = 11
60   eclipse_java_runtime_name = "JavaSE-11"
61   /* compile without modules -- using classpath libraries
62   additional_compiler_args += [
63   '--module-path', ext.modules_compileClasspath.asPath,
64   '--add-modules', j11modules
65   ]
66   */
67 } else if (JAVA_VERSION.equals("12") || JAVA_VERSION.equals("13")) {
68   JAVA_INTEGER_VERSION = JAVA_VERSION
69   libDir = j11libDir
70   libDistDir = j11libDir
71   compile_source_compatibility = JAVA_VERSION
72   compile_target_compatibility = JAVA_VERSION
73   eclipse_java_runtime_name = "JavaSE-11"
74   /* compile without modules -- using classpath libraries
75   additional_compiler_args += [
76   '--module-path', ext.modules_compileClasspath.asPath,
77   '--add-modules', j11modules
78   ]
79   */
80 } else {
81   throw new GradleException("JAVA_VERSION=$JAVA_VERSION not currently supported by Jalview")
82 }
83
84 sourceSets {
85
86   main {
87     java {
88       srcDirs "$jalviewDir/$sourceDir"
89       outputDir = file("$classes")
90     }
91
92     resources {
93       srcDirs "$jalviewDir/$resourceDir"
94     }
95
96     compileClasspath = files(sourceSets.main.java.outputDir)
97     compileClasspath += fileTree(dir: "$jalviewDir/$libDir", include: ["*.jar"])
98
99     runtimeClasspath = compileClasspath
100   }
101
102 }
103
104 eclipse {
105   project {
106     name = eclipse_project_name
107
108     natures 'org.eclipse.jdt.core.javanature',
109     'org.eclipse.buildship.core.gradleprojectnature'
110
111     buildCommand 'org.eclipse.jdt.core.javabuilder'
112     buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
113   }
114
115   classpath {
116     //defaultOutputDir = sourceSets.main.java.outputDir
117     def removeThese = []
118     configurations.each{ if (it.isCanBeResolved()) {
119         removeThese += it
120       }
121     }
122
123     minusConfigurations += removeThese
124     plusConfigurations = [ ]
125     file {
126
127       whenMerged { cp ->
128         def removeTheseToo = []
129         HashMap<String, Boolean> addedSrcPath = new HashMap<>();
130         cp.entries.each { entry ->
131           if (entry.kind == 'src') {
132             if (addedSrcPath.getAt(entry.path) || !(entry.path == "src" || entry.path == "test")) {
133               removeTheseToo += entry
134             } else {
135               addedSrcPath.putAt(entry.path, true)
136             }
137           }
138         }
139         cp.entries.removeAll(removeTheseToo)
140
141         cp.entries += new Output(eclipse_bin_dir+"/main")
142         cp.entries += new Library(fileReference(helpParentDir))
143         cp.entries += new Library(fileReference(resourceDir))
144
145         HashMap<String, Boolean> addedLibPath = new HashMap<>();
146
147         // changing from sourcesets.main.classpath to specific Java version lib
148         //sourceSets.main.compileClasspath.each{
149         fileTree("$jalviewDir/$libDistDir").include("**/*.jar").include("*.jar").each {
150           //don't want to add outputDir as eclipse is using its own output dir in bin/main
151           if (it.isDirectory() || ! it.exists()) {
152             // don't add dirs to classpath
153             return
154           }
155           def itPath = it.toString()
156           if (itPath.startsWith(jalviewDirAbsolutePath+"/")) {
157             itPath = itPath.substring(jalviewDirAbsolutePath.length()+1)
158           }
159           if (addedLibPath.get(itPath)) {
160             //println("Not adding duplicate entry "+itPath)
161           } else {
162             //println("Adding entry "+itPath)
163             cp.entries += new Library(fileReference(itPath))
164             addedLibPath.put(itPath, true)
165           }
166         }
167       } // whenMerged
168
169     } // file
170
171     containers 'org.eclipse.buildship.core.gradleclasspathcontainer'
172   } // classpath
173
174   jdt {
175     // for the IDE, use java 11 compatibility
176     sourceCompatibility = compile_source_compatibility
177     targetCompatibility = compile_target_compatibility
178     javaRuntimeName = eclipse_java_runtime_name
179
180     /*
181     file {
182     withProperties { props ->
183     def jalview_prefs = new Properties()
184     def ins = new FileInputStream(jalviewDirAbsolutePath+"/"+eclipse_extra_jdt_prefs_file)
185     jalview_prefs.load(ins)
186     ins.close()
187     jalview_prefs.forEach { t, v ->
188     if (props.getAt(t) == null) {
189     props.putAt(t, v)
190     }
191     }
192     }
193     }
194      */
195   } // jdt
196
197   //synchronizationTasks eclipseClasspath
198   //autoBuildTasks eclipseClasspath
199 } // eclipse
200
201 /*
202 compileJava {
203
204   doFirst {
205     sourceCompatibility = compile_source_compatibility
206     targetCompatibility = compile_target_compatibility
207     //options.compilerArgs = additional_compiler_args
208     print ("Setting target compatibility to "+targetCompatibility+"\n")
209   }
210
211 }
212
213 clean {
214   delete sourceSets.main.java.outputDir
215 }
216 */
217
218 task jalviewjsUnzipFiles {
219   def zipFiles = fileTree(dir: jalviewjs_utils_dir+"/"+jalviewjs_libjs_dir).include("*.zip")
220   zipFiles += jalviewjs_utils_dir+"/"+jalviewjs_swingjs_zip
221
222   doLast {
223     zipFiles.each { file_zip -> 
224       copy {
225         from zipTree(file_zip)
226         into jalviewjs_site_dir
227       }
228     }
229   }
230
231   inputs.files zipFiles
232   outputs.dir jalviewjs_site_dir
233 }
234
235 def eclipseBinary
236 def eclipseDropinsDir
237 def eclipsePluginsDir
238 task jalviewjsEclipsePaths {
239   def eclipseRoot = jalviewjs_eclipse_root
240   if (eclipseRoot.startsWith("~")) {
241     eclipseRoot = System.getProperty("user.home") + eclipseRoot.substring(1)
242   }
243         if (OperatingSystem.current().isMacOsX()) {
244     eclipseRoot += "/Eclipse.app"
245                 eclipseDropinsDir = eclipseRoot+"/Contents/Eclipse/dropins"
246                 eclipsePluginsDir = eclipseRoot+"/Contents/Eclipse/plugins"
247                 eclipseBinary = eclipseRoot+"/Contents/MacOS/eclipse"
248         } else if (OperatingSystem.current().isWindows()) { // check these paths!!
249                 eclipseDropinsDir = eclipseRoot+"/dropins"
250                 eclipsePluginsDir = eclipseRoot+"/plugins"
251                 eclipseBinary = eclipseRoot+"/eclipse"
252         } else { // linux or unix
253                 eclipseDropinsDir = eclipseRoot+"/dropins"
254                 eclipsePluginsDir = eclipseRoot+"/plugins"
255                 eclipseBinary = eclipseRoot+"/eclipse"
256         }
257   println("ECLIPSE ROOT: "+eclipseRoot)
258 }
259
260 task jalviewjsEclipseCopyDropins (type: Copy) {
261   dependsOn jalviewjsEclipsePaths
262   def inputFiles = fileTree(jalviewjs_utils_dir+"/"+jalviewjs_eclipse_dropins_dir)
263   def outputDir = eclipseDropinsDir
264
265   from inputFiles
266   into outputDir
267   def outputFiles = []
268   rename { filename ->
269     outputFiles += outputDir+"/"+filename
270     null
271   }
272   outputs.files outputFiles
273   inputs.files inputFiles
274 }
275
276 task jalviewjsEclipseCopyPlugins (type: Copy) {
277   dependsOn jalviewjsEclipsePaths
278   def inputFiles = fileTree(jalviewjs_utils_dir+"/"+jalviewjs_eclipse_plugins_dir)
279   def outputDir = eclipsePluginsDir
280
281   from inputFiles
282   into outputDir
283   def outputFiles = []
284   rename { filename ->
285     outputFiles += outputDir+"/"+filename
286     null
287   }
288   outputs.files outputFiles
289   inputs.files inputFiles
290 }
291
292 def tempEclipseWorkspace = ""
293
294 task jalviewjsSetTempEclipseWorkspace {
295   tempEclipseWorkspace = file(jalviewjs_eclipse_workspace)
296   if (!tempEclipseWorkspace.exists()) {
297     tempEclipseWorkspace = File.createTempDir()
298     tempEclipseWorkspace.deleteOnExit()
299   }
300   println("ECLIPSE WORKSPACE: "+tempEclipseWorkspace.getPath())
301 }
302
303 task jalviewjsEclipseSetup {
304   dependsOn jalviewjsEclipseCopyDropins
305   dependsOn jalviewjsEclipseCopyPlugins
306   dependsOn jalviewjsSetTempEclipseWorkspace
307 }
308
309
310 task jalviewjsCreateJ2sSettings(type: WriteProperties) {
311   outputFile (jalviewDir+"/"+jalviewjs_j2s_settings)
312   def props = project.properties.sort { it.key }
313   props.each { prop, val ->
314     if (prop.startsWith("j2s.") && val != null) {
315       property(prop,val)
316     }
317   }
318   outputs.file(outputFile)
319 }
320
321 task jalviewjsCopyResources (type: Copy) {
322   def inputFiles = fileTree(dir: jalviewjs_resource_dir)
323   def outputDir = jalviewjs_site_dir+"/"+jalviewjs_j2s_subdir
324
325   from inputFiles
326   into outputDir
327   def outputFiles = []
328   rename { filename ->
329     outputFiles += outputDir+"/"+filename
330     null
331   }
332   outputs.files outputFiles
333   inputs.files inputFiles
334 }
335
336 task jalviewjsCopySiteResources (type: Copy) {
337   def inputFiles = fileTree(dir: jalviewjs_utils_dir+"/"+jalviewjs_site_resource_dir)
338   def outputDir = jalviewjs_site_dir
339
340   from inputFiles
341   into outputDir
342   def outputFiles = []
343   rename { filename ->
344     outputFiles += outputDir+"/"+filename
345     null
346   }
347   outputs.files outputFiles
348   inputs.files inputFiles
349 }
350
351 task cleanJalviewjs {
352   /*
353   delete jalviewDir+"/"+jalviewjs_site_dir
354   delete jalviewDir+"/"+eclipse_bin_dir
355   delete file(tempEclipseWorkspace.getAbsolutePath()+"/.metadata")
356   delete jalviewDir+"/"+jalviewjs_j2s_settings
357   */
358 }
359
360 task jalviewjsProjectImport(type: Exec) {
361   // work out how to do this!
362   dependsOn eclipseProject
363   dependsOn eclipseClasspath
364   dependsOn eclipseJdt
365   dependsOn jalviewjsEclipsePaths
366   dependsOn jalviewjsEclipseSetup
367   executable(eclipseBinary)
368   args(["-nosplash", "--launcher.suppressErrors", "-application", "com.seeq.eclipse.importprojects.headlessimport", "-data", tempEclipseWorkspace.getPath(), "-import", jalviewDirAbsolutePath])
369
370   def projdir = tempEclipseWorkspace.getPath()+"/.metadata/.plugins/org.eclipse.core.resources/.projects/jalview/org.eclipse.jdt.core/"
371   inputs.file(jalviewDir+"/.project")
372   outputs.dir(projdir)
373 }
374
375 task jalviewjsTranspile(type: Exec) {
376   dependsOn jalviewjsCreateJ2sSettings 
377   dependsOn jalviewjsProjectImport
378   dependsOn jalviewjsEclipsePaths
379   executable(eclipseBinary)
380   args(["-nosplash", "--launcher.suppressErrors", "-application", "org.eclipse.jdt.apt.core.aptBuild", "-data", tempEclipseWorkspace, "-"+jalviewjs_eclipseBuildArg, eclipse_project_name ])
381   inputs.dir(sourceDir)
382   outputs.dir(eclipse_bin_dir+"/main")
383   outputs.file(eclipse_bin_dir+"/main/jalview/bin/Jalview.class")
384   outputs.dir(jalviewjs_site_dir+"/"+jalviewjs_j2s_subdir)
385 }
386
387 task jalviewjsBuildSite {
388   dependsOn jalviewjsUnzipFiles
389   dependsOn jalviewjsCopyResources
390   dependsOn jalviewjsCopySiteResources
391   dependsOn jalviewjsTranspile
392 }
393
394 task jalviewjsSiteTar(type: Tar) {
395   dependsOn jalviewjsBuildSite
396   def outputFilename = "site.tar.gz"
397   try {
398     archiveFileName = outputFilename
399   } catch (Exception e) {
400     archiveName = outputFilename
401   }
402
403   compression Compression.GZIP
404
405   from jalviewjs_site_dir
406   into jalviewjs_site_dir // this is inside the tar file
407
408   inputs.dir(jalviewjs_site_dir)
409 }
410
411 task jalviewjs {
412   dependsOn jalviewjsBuildSite
413 }
414
415 def jalviewjsServer = null
416 task jalviewjsServerStart {
417   doLast {
418
419     if (jalviewjsServer != null) {
420       println("SERVER ALREADY RUNNING. Go to "+jalviewjsServer.getResourceUrl(jalviewjs_server_resource)+" . Run  gradle jalviewjsServerStop  to stop.")
421     } else {
422
423       SimpleHttpFileServerFactory factory = new SimpleHttpFileServerFactory()
424       def port = Integer.valueOf(jalviewjs_server_port)
425       def start = port
426       def running = false
427       while(port < start+1000 && !running) {
428         try {
429           jalviewjsServer = factory.start(new File(jalviewDirAbsolutePath+"/"+jalviewjs_site_dir), port)
430           running = true
431           println("SERVER STARTED. Go to "+jalviewjsServer.getResourceUrl(jalviewjs_server_resource)+" . Run  gradle jalviewjsServerStop  to stop.")
432           //println("Ctrl-c to stop.");java.lang.Thread.sleep(Integer.valueOf(jalviewjs_server_wait)*1000);
433         } catch (Exception e) {
434           port++;
435         }
436       }
437
438     }
439
440   }
441
442 }
443
444 /* server persists in gradle daemon but reference is not accessible across builds
445 task jalviewjsServerStop {
446   doLast {
447
448     if (jalviewjsServer != null) {
449
450       println("SERVER ON PORT "+jalviewjsServer.getPort()+" STOPPING. Run  gradle jalviewjsServerStart  to start again.")
451       jalviewjsServer.stop()
452
453     } else {
454       println("SERVER NOT RUNNING. Run  gradle jalviewjsServerStart  to start.")
455     }
456
457   }
458 }
459 */