-
Notifications
You must be signed in to change notification settings - Fork 707
Expand file tree
/
Copy pathbuild.gradle
More file actions
1510 lines (1378 loc) · 67.1 KB
/
Copy pathbuild.gradle
File metadata and controls
1510 lines (1378 loc) · 67.1 KB
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import groovy.xml.MarkupBuilder
import groovy.xml.XmlSlurper
import org.apache.tools.ant.filters.ReplaceTokens
import org.asciidoctor.gradle.jvm.AsciidoctorTask
/* ========================================================
* Project setup
* ======================================================== */
plugins {
id 'application' // plugins that are versioned as part of Gradle are using simple quotes to differentiate them
id 'groovy'
id 'eclipse'
id 'checkstyle'
id 'codenarc'
id 'maven-publish'
id "org.asciidoctor.jvm.convert" version "4.0.5" // For now we can not update above. See "production-ready version" warning in https://plugins.gradle.org/plugin/org.asciidoctor.jvm
id "org.asciidoctor.jvm.pdf" version "4.0.5" // For now we can not update above. See "production-ready version" warning in https://plugins.gradle.org/plugin/org.asciidoctor.jvm
id "org.owasp.dependencycheck" version "latest.release" apply false
id "se.patrikerdes.use-latest-versions" version "latest.release" apply false
id "com.github.ben-manes.versions" version "latest.release" apply false
id "com.github.ManifestClasspath" version "latest.release"
id "com.github.jakemarsden.git-hooks" version "latest.release"
id "com.github.node-gradle.node" version "latest.release" apply false
}
/* OWASP plugin
*
* If project property "enableOwasp" is flagged then
* gradle will download required dependencies and
* activate Gradle's OWASP plugin and its related tasks.
*
* Syntax: gradlew -PenableOwasp dependencyCheckAnalyze
*/
if (project.hasProperty('enableOwasp')) {
apply plugin: 'org.owasp.dependencycheck'
}
/* DependencyUpdates plugin
*
* If project property "enableDependencyUpdates" is flagged then
* gradle will download required dependencies and
* activate Gradle's DependencyUpdates plugin and its related tasks.
*
* Syntax: gradlew -PenableDependencyUpdates dependencyUpdates -Drevision=release
*
* You may want to use the use-latest-versions plugin to help you in your work
* Syntax:
* Check only: gradlew -PenableDependencyUpdates useLatestVersions && gradlew -PenableDependencyUpdates useLatestVersionsCheck
* Automated update: gradlew -PenableDependencyUpdates useLatestVersions
* Beware that this is only a help.
* If you use it without check you will need to check things by yourself (can be as tedious as not using this plugin)
*/
if (project.hasProperty('enableDependencyUpdates')) {
apply plugin: 'com.github.ben-manes.versions'
apply plugin: 'se.patrikerdes.use-latest-versions'
}
/* Configuration and default values. By default not available as it breacks Gradle build even when useLatestVersionsCheck (see above) is used.
useLatestVersions {
// A whitelist of dependencies to update, in the format of group:name
// Equal to command line: --update-dependency=[values]
updateWhitelist = []
// A blacklist of dependencies to update, in the format of group:name
// Equal to command line: --ignore-dependency=[values]
updateBlacklist = []
// When enabled, root project gradle.properties will also be populated with
// versions from subprojects in multi-project build
// Equal to command line: --update-root-properties
updateRootProperties = false
// By default plugin tries to find all relevant gradle files (e.g. *.gradle, gradle.properties etc).
// This can be slow in some cases when project has a lot of gradle files. For example when using conventions
// in buildSrc. With this option you can specify what files should plugin search and check. Plugin will ignore
// files that don't exist. Empty list means use default strategy. File paths are relative to project dir.
//
// Example:
// versionFiles = ["gradle.build", "gradle.properties"]
// Will check just $projectDir/gradle.build and $projectDir/gradle.properties
//
// Note:
// You always have to specify file that has dependencies in some common dependency format with artifact coordinates,
// e.g. compileOnly "group:module:version" or compileOnly("group:module:version") or val dependency = "group:module:version" etc.
// For example if you set just versionFiles = ["gradle.properties"] this won't work, since plugin
// won't be able to correlate variable with artifact coordinates.
//
// Equal to command line: --version-files=[values]
versionFiles = []
// List of root project files to update when updateRootProperties is enabled.
// `build.gradle` is not an acceptable entry here as it breaks other expected
// functionality. Version variables in `build.gradle` need to be moved into
// a separate file which can be listed here.
// Equal to command line: --root-version-files=[values]
//rootVersionFiles = ['gradle.properties']
}*/
apply from: 'common.gradle'
apply from: 'dependencies.gradle'
apply from: 'test-reports.gradle'
// global properties
ext.os = System.getProperty('os.name').toLowerCase()
ext.gradlew = os.contains('windows') ? 'gradlew.bat' : './gradlew'
ext.pluginsDir = "${rootDir}/plugins"
// "./gradlew ofbiz" command reflects them directly, with no separate command-line flag to remember.
def debugProperties = new Properties()
file('framework/base/config/debug.properties').withInputStream { debugProperties.load(it) }
ext.jsonLogsEnabled = debugProperties.getProperty('json.logs.enabled', 'false').toBoolean()
ext.jsonLogsTemplate = debugProperties.getProperty('json.logs.template', 'classpath:templates/ecs-layout.json')
application {
mainClass = 'org.apache.ofbiz.base.start.Start'
applicationDefaultJvmArgs = project.hasProperty('jvmArgs')
? jvmArgs.tokenize()
: ['-Xms128M', '-Xmx1024M',
'-Djdk.serialFilter=maxarray=100000;maxdepth=20;maxrefs=1000;maxbytes=500000', // OFBIZ-12592 and OFBIZ-12716
// Required for embedded Tomcat 10.1 and libraries (Groovy 5, Spring 6) under Java 17+ strong encapsulation
'--add-opens=java.base/java.lang=ALL-UNNAMED',
'--add-opens=java.base/java.io=ALL-UNNAMED',
'--add-opens=java.base/java.util=ALL-UNNAMED', // OFBIZ-12726
'--add-opens=java.base/java.util.concurrent=ALL-UNNAMED',
'--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED',
// Allow libraries using the stable Foreign Function & Memory API (Apache SSHD, Tika)
'--enable-native-access=ALL-UNNAMED',
"-Dofbiz.json.logs=${jsonLogsEnabled}",
"-Dofbiz.json.logs.template=${jsonLogsTemplate}",
]
}
distributions.main.contents.from(rootDir) {
include 'framework/**', 'applications/**', 'themes/**', 'plugins/**'
// Excludes each node-gradle subproject's downloaded Node.js runtime cache --
// it's build-tool cache, never read at runtime.
exclude '**/.gradle/**'
}
javadoc {
title="OFBiz " + getCurrentGitBranch() + " API"
failOnError = true
options {
source '17'
encoding 'UTF-8'
charSet 'UTF-8'
// Those external Javadoc links should correspond to the actual
// versions declared in the 'dependencies' block.
links(
'https://docs.oracle.com/en/java/javase/17/docs/api/',
'https://tomcat.apache.org/tomcat-10.1-doc/servletapi/',
'http://docs.groovy-lang.org/docs/groovy-4.0.22/html/api',
'https://commons.apache.org/proper/commons-cli/apidocs'
)
}
options as StandardJavadocDocletOptions
// Generate Javadocs quietly, validate everything except missing documentation
options.addStringOption('Xdoclint:all,-missing', '-quiet')
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
// Java compile options, syntax gradlew -PXlint:none build
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
if (!project.hasProperty('Xlint:none')) {
options.compilerArgs << '-Xlint:all'
// Exclude varargs warnings which are not silenced by @SafeVarargs.
options.compilerArgs << '-Xlint:-varargs'
// this-escape lint was introduced in JDK 21's javac and is an invalid flag on JDK 17,
// so only pass it when compiling with a JDK that recognizes it.
if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_21)) {
// Exclude this-escape warnings pending proper refactoring of widget/service classes.
options.compilerArgs << '-Xlint:-this-escape'
}
}
}
// Enables Zip larger than 4 GB and more than 65535 entries
tasks.withType(Zip) { zip64 = true }
// Multiple SecretProvider plugins each contribute the same META-INF/services/ filename.
// Only one provider should be enabled at a time (via ofbiz-component.xml enabled="true/false").
// FIRST keeps the alphabetically first file during transitional states where two are temporarily enabled.
processResources {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
// Only used for release branches
def getCurrentGitBranch() {
return "git branch --show-current".execute().text.trim()
}
// defines the footer files for git info
def File gitFooterFile = file("${rootDir}/runtime/GitInfo.ftl")
// root and subproject settings
defaultTasks 'jar', 'test'
allprojects {
repositories {
mavenCentral()
// the switch from jCenter to mavenCentral needs some additional repositories to be configured here
// this should be checked frequently to remove obsolete configurations if the artifacts are available
// on mavenCentral directly
maven {
// org.restlet and org.restlet.ext.servlet
url = 'https://maven.restlet.talend.com'
}
maven {
// net.fortuna.ical4j:ical4j:1.0-rc3-atlassian-11
url = 'https://packages.atlassian.com/maven-3rdparty/'
}
maven {
// org/milyn/flute/1.3/flute-1.3.jar
// need artifact only because of wrong pom metadata in maven central
// Required by: plugins:birt > org.eclipse.birt.runtime:viewservlets:4.5.0 > org.eclipse.birt.runtime:org.eclipse.birt.runtime:4.4.1
// TODO Maybe this will no longer needed wheh upgrading viewservlets to 4.9.0
url = "https://repo1.maven.org/maven2"
metadataSources {
artifact()
}
}
maven {
url = 'https://clojars.org/repo'
}
maven {
url = "https://artifacts.alfresco.com/nexus/content/repositories/public/"
}
/* maven {
// To test not released FreeMarker versions, see OFBIZ-12934 and sub-tasks for details
url = "https://repository.apache.org/content/repositories/snapshots/"
} */
}
}
subprojects {
configurations {
// compile-time plugin libraries
pluginLibsCompile
// runtime plugin libraries
pluginLibsRuntime
//compile-only libraries
pluginLibsCompileOnly
}
}
configurations {
ofbizPlugins {
description = 'ofbiz plugin dependencies configuration'
transitive = true
}
}
configurations.all {
exclude group: 'log4j', module: 'log4j'
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
exclude group: 'xml-apis', module: 'xml-apis'
exclude group: 'jaxen', module: 'jaxen'
exclude group: 'javax.xml.stream', module: 'stax-api'
exclude group: 'org.apache.geronimo.specs', module: 'geronimo-stax-api_1.0_spec'
exclude group: 'org.apache.geronimo.specs', module: 'geronimo-jta_1.1_spec'
exclude group: 'javax.transaction', module: 'jta'
}
dependencies {
// Dependencies defined by the plugins
subprojects.each { subProject ->
implementation project(path: subProject.path, configuration: 'pluginLibsCompile')
runtimeOnly project(path: subProject.path, configuration: 'pluginLibsRuntime')
compileOnly project(path: subProject.path, configuration: 'pluginLibsCompileOnly')
}
// Libraries downloaded manually
implementation fileTree(dir: file("${rootDir}/lib"), include: '**/*.jar')
getDirectoryInActiveComponentsIfExists('lib').each { libDir ->
implementation fileTree(dir: libDir, include: '**/*.jar')
}
}
def excludedJavaSources = [
]
sourceSets {
// This is for integration tests (needs DB access or simply creation of delegator or dispatcher that ultimately needs use of dispatcherFactory)
main {
java {
srcDirs = getDirectoryInActiveComponentsIfExists('src/main/java')
exclude excludedJavaSources
}
groovy {
srcDirs = getDirectoryInActiveComponentsIfExists('src/main/groovy')
}
resources {
srcDirs = getDirectoryInActiveComponentsIfExists('src/main/resources')
srcDirs += getDirectoryInActiveComponentsIfExists('config')
srcDirs += getDirectoryInActiveComponentsIfExists('dtd')
}
}
// This is for unit tests (no DB access need, or simply creation of delegator or dispatcher that ultimately needs use of dispatcherFactory)
test {
java {
srcDirs = getDirectoryInActiveComponentsIfExists('src/test/java')
}
// Groovy tests often fail, because JUNIT does not have access to the ofbiz environment.
// If a groovy test is supposed to be tested this way, it can be added here.
groovy {
srcDirs = getDirectoryInActiveComponentsIfExists('src/test/groovy')
}
resources {
srcDirs = getDirectoryInActiveComponentsIfExists('src/test/resources')
}
}
}
jar.manifest.attributes(
'Implementation-Title': project.name,
'Main-Class': application.mainClass,
'Class-Path': getJarClasspath()
)
// Checks OFBiz Java coding conventions.
checkstyle {
// Defining a maximum number of "tolerated" errors ensures that
// this number cannot increase in the future. It corresponds to
// the sum of errors found last time it was changed after using the
// 'checkstyle' tool present in the framework and in the official
// plugins.
tasks.checkstyleMain.maxErrors = 0
// Increase memory for checkstyleMain required for Gradle 8+.
tasks.checkstyleMain.maxHeapSize = '1g'
// Currently there are no errors so we can show new one when they appear
showViolations = true
// Specify tool version so we can keep it up-to-date
toolVersion = '10.20.2'
}
gitHooks {
// Resolve the real .git dir so this also works from a linked worktree,
// where "$rootDir/.git" (the plugin's default) is a gitlink file, not a directory.
def gitCommonDir = "git -C ${rootDir} rev-parse --git-common-dir".execute().text.trim()
hooksDirectory.set(new File(rootDir, gitCommonDir).toPath().resolve('hooks').toFile())
hooks = ['pre-push': 'checkstyleMain checkstyleTest codenarcMain codenarcTest']
}
// Checks OFBiz Groovy coding conventions.
codenarc {
setConfigFile(new File('config/codenarc/codenarc.groovy'))
setMaxPriority1Violations(0)
setMaxPriority2Violations(0)
setMaxPriority3Violations(0)
}
// Eclipse plugin settings
eclipse.classpath.file.whenMerged { classpath ->
/* The code inside this block removes unnecessary entries
* in the .classpath file which are generated automatically
* due to the settings in the sourceSets block
*/
def fileSep = System.getProperty('file.separator')
activeComponents().each { component ->
def componentName = component.toString() - rootDir.toString() - fileSep
def eclipseEntry = os.contains('windows') ? componentName.replaceAll("\\\\", '/') : componentName
classpath.entries.removeAll { entry ->
// remove any "src" entries in .classpath of the form /componentName
entry.kind == 'src' && (
entry.path ==~ '.*/+(' + componentName.tokenize(fileSep).last() + ')$' ||
entry.path ==~ /(\/+framework)$/ ||
entry.path ==~ /(\/+applications)$/ ||
entry.path ==~ /(\/+plugins)$/ ||
entry.path ==~ /(\/+themes)$/ )
}
}
// remove .pom artifacts from classpath
classpath.entries.removeAll { entry ->
entry.kind == 'lib' && entry.path.endsWith('.pom')
}
}
tasks.eclipse.dependsOn(cleanEclipse)
test {
useJUnitPlatform {
excludeTags 'jupiterIntegration' // see JupiterTestExtension.INTEGRATION_TAG
}
// Required for Mockito and Spring Test under Java 21
jvmArgs '--add-opens=java.base/java.lang=ALL-UNNAMED'
jvmArgs '--add-opens=java.base/java.lang.reflect=ALL-UNNAMED'
jvmArgs '--enable-native-access=ALL-UNNAMED'
testLogging {
events "passed", "skipped", "failed"
}
finalizedBy(reskinGradleTestReport)
}
// 'gradlew test --tests <ClassName>' against a @JunitJupiterTest class fails with Gradle's generic
// "No tests found for given includes" rather than pointing at testIntegration: the excludeTags
// filter above excludes the class from discovery entirely before --tests filtering ever runs, so
// from Gradle's perspective the class simply doesn't exist. This doesn't change that failure - it's
// otherwise a genuinely useful safety net for a real --tests typo - it just appends a pointer to the
// right command for the specific case where the cause is a Jupiter integration-test class.
gradle.taskGraph.afterTask { Task task, TaskState state ->
if (task.path == ':test' && state.failure) {
Throwable rootCause = state.failure
while (rootCause.cause != null) {
rootCause = rootCause.cause
}
if (rootCause.message?.contains('No tests found for given includes')) {
logger.error('')
logger.error('[hint] If the class above is annotated @JunitJupiterTest, this failure is expected: '
+ 'that tag excludes it from \'gradlew test\' discovery entirely (see JunitJupiterTest\'s '
+ 'javadoc), so --tests never gets a chance to filter it in. Run it via '
+ '\'gradlew testIntegration\' or \'ofbiz --test\' instead.')
logger.error('')
}
}
}
// ModelTestSuite.parseTestElement() resolves every <junit-test-suite>/<jupiter-test-suite>
// class-name attribute at runtime via ObjectType.loadClass(), but a lookup failure there is
// only Debug.logError()'d - the whole suite is silently dropped from testIntegration with no
// build failure and no signal short of reading the log output. This task repeats that same
// lookup at build time, against the compiled test classpath, so a typo'd or stale (post-rename)
// class-name fails the build instead of quietly vanishing from the test run.
task verifyTestdefClassNames(group: 'Verification', dependsOn: testClasses) {
description = 'Fails the build if any testdef XML class-name attribute cannot be resolved on the classpath'
def testdefDirs = getDirectoryInActiveComponentsIfExists('testdef')
def testdefXmlFiles = files(testdefDirs.collect { fileTree(it) { include '**/*.xml' } })
def testRuntimeClasspath = sourceSets.test.runtimeClasspath
inputs.files(testdefXmlFiles)
inputs.files(testRuntimeClasspath)
doLast {
URL[] classpathUrls = testRuntimeClasspath.files.collect { it.toURI().toURL() }
URLClassLoader classpathLoader = new URLClassLoader(classpathUrls, getClass().classLoader)
List<String> unresolved = []
testdefXmlFiles.each { xmlFile ->
def root = new XmlParser(false, false).parse(xmlFile)
root.depthFirst()
.findAll { it.name() == 'junit-test-suite' || it.name() == 'jupiter-test-suite' }
.each { node ->
String className = node.'@class-name'
if (!className) {
return
}
try {
Class.forName(className, false, classpathLoader)
} catch (Throwable t) {
unresolved << "${xmlFile}: <${node.name()} class-name=\"${className}\"/> - ${t}"
}
}
}
if (!unresolved.isEmpty()) {
throw new GradleException('The following testdef class-name references cannot be resolved on the '
+ 'classpath (typo, or the class was renamed/moved/deleted without updating the testdef XML):\n'
+ unresolved.collect { " - ${it}" }.join('\n'))
}
}
}
check.dependsOn verifyTestdefClassNames
// JunitJupiterTest's own javadoc documents that bare @ExtendWith(JupiterTestExtension.class)
// skips gradlew test's excludeTags-based exclusion - it's only caught at runtime by
// evaluateExecutionCondition(), reporting a skip instead of being excluded from discovery
// outright. That's an intentional, documented escape hatch for JupiterTestExtension's own home
// (JunitJupiterTest's definition and JupiterInjectionGuardsTest's fixtures, both under
// framework/testtools, use it deliberately to define/exercise the escape hatch itself), but
// nothing stops a future contributor from using the bare form on a real test class by habit or
// copy-paste. This cheap grep-based check catches that everywhere else.
task verifyNoBareJupiterExtendWith(group: 'Verification') {
description = 'Fails the build if a bare @ExtendWith(JupiterTestExtension.class) is used ' +
'outside framework/testtools instead of @JunitJupiterTest'
def testInfraDir = file('framework/testtools')
def sourceFiles = files(
(getDirectoryInActiveComponentsIfExists('src/main/java')
+ getDirectoryInActiveComponentsIfExists('src/main/groovy')
+ getDirectoryInActiveComponentsIfExists('src/test/java')
+ getDirectoryInActiveComponentsIfExists('src/test/groovy'))
.collect { dir -> fileTree(dir) { include '**/*.java', '**/*.groovy' } }
).filter { file -> !file.toPath().startsWith(testInfraDir.toPath()) }
inputs.files(sourceFiles)
doLast {
def bareExtendWith = ~/@ExtendWith\(\s*(org\.apache\.ofbiz\.testtools\.)?JupiterTestExtension(\.class)?\s*\)/
List<String> offenders = []
sourceFiles.each { file ->
file.readLines().eachWithIndex { line, idx ->
if (bareExtendWith.matcher(line).find()) {
offenders << "${file}:${idx + 1}: ${line.trim()}"
}
}
}
if (!offenders.isEmpty()) {
throw new GradleException('Bare @ExtendWith(JupiterTestExtension.class) found outside '
+ 'framework/testtools - use @JunitJupiterTest instead, so gradlew test\'s '
+ 'excludeTags-based exclusion actually applies (see JunitJupiterTest\'s javadoc):\n'
+ offenders.collect { " - ${it}" }.join('\n'))
}
}
}
check.dependsOn verifyNoBareJupiterExtendWith
// junit5-improvements item 3: the 8 real ordering bugs found during the JUnit3->JUnit5
// migration were caught reactively (a suite actually failing under a full testIntegration
// run), not via a systematic per-file audit - only 7 of 82 migrated classes were ever
// spot-checked. A multi-method Jupiter class with zero @Order annotations at all is
// implicitly relying on whatever order the JVM happens to return its test methods in - the
// exact shape of bug that produced those 8 failures. This task flags that pattern so it's at
// least visible, rather than depending on tests happening to catch it a second time.
// Deliberately NOT wired into check: plenty of multi-method classes are legitimately
// order-independent and would never need @Order, so hard-failing the build here would be
// noise, not signal - a human triages the flagged list instead. Reuses
// verifyTestdefClassNames' testdef-XML-scan + classloader pattern above.
task flagUnorderedJupiterTests(group: 'Verification', dependsOn: testClasses) {
description = 'Lists testdef-registered Jupiter classes with more than one test method ' +
'and no @Order annotations at all - report-only, never fails the build'
def testdefDirs = getDirectoryInActiveComponentsIfExists('testdef')
def testdefXmlFiles = files(testdefDirs.collect { fileTree(it) { include '**/*.xml' } })
def testRuntimeClasspath = sourceSets.test.runtimeClasspath
inputs.files(testdefXmlFiles)
inputs.files(testRuntimeClasspath)
doLast {
URL[] classpathUrls = testRuntimeClasspath.files.collect { it.toURI().toURL() }
new URLClassLoader(classpathUrls, getClass().classLoader).withCloseable { classpathLoader ->
def testAnnotation
def paramTestAnnotation
def orderAnnotation
try {
testAnnotation = classpathLoader.loadClass('org.junit.jupiter.api.Test')
paramTestAnnotation = classpathLoader.loadClass('org.junit.jupiter.params.ParameterizedTest')
orderAnnotation = classpathLoader.loadClass('org.junit.jupiter.api.Order')
} catch (Throwable t) {
logger.lifecycle("flagUnorderedJupiterTests: could not load JUnit Jupiter annotation "
+ "classes on the test runtime classpath - skipping check (${t}).")
return
}
Set<String> seenClasses = []
List<String> flagged = []
int skipped = 0
testdefXmlFiles.each { xmlFile ->
def root
try {
root = new XmlParser(false, false).parse(xmlFile)
} catch (Throwable ignored) {
skipped++
return // malformed/unreadable testdef XML - not this task's job to fail on
}
root.depthFirst()
.findAll { it.name() == 'jupiter-test-suite' }
.each { node ->
String className = node.'@class-name'
if (!className || !seenClasses.add(className)) {
return // no class-name, or already evaluated from another testdef file
}
try {
Class<?> clz = Class.forName(className, false, classpathLoader)
// declaredMethods (not the inherited-methods variant): every Jupiter
// test method in this codebase is declared directly on its own test
// class today, not inherited from a shared base class - if a future
// class inherits test methods from a common base, this task would
// silently miss them.
def testMethods = clz.declaredMethods.findAll {
it.isAnnotationPresent(testAnnotation) || it.isAnnotationPresent(paramTestAnnotation)
}
boolean anyOrdered = testMethods.any { it.isAnnotationPresent(orderAnnotation) }
// Flags only classes with zero total @Order usage. A class with
// @Order on some but not all methods is NOT flagged, even though its
// unannotated methods still get an arbitrary tie-broken position
// under the pinned OrderAnnotation orderer - a clean run here means
// "no class has zero @Order," not "every class is fully ordered."
if (testMethods.size() > 1 && !anyOrdered) {
flagged << "${className} (${testMethods.size()} test methods, no @Order) - ${xmlFile}"
}
} catch (Throwable ignored) {
// Class.forName or the reflection calls below it can throw for a
// testdef entry that doesn't resolve cleanly on this classpath -
// verifyTestdefClassNames (above) is what fails the build for that
// condition; this task only needs to not crash on it, but a silently
// dropped class would make a clean run indistinguishable from one
// that just failed to check everything, so it's counted instead.
skipped++
}
}
}
String skipNote = skipped > 0
? " (${skipped} class(es) or testdef file(s) could not be loaded/parsed cleanly and were skipped)"
: ''
if (flagged.isEmpty()) {
logger.lifecycle('flagUnorderedJupiterTests: no testdef-registered Jupiter class relies on '
+ "implicit declaration order.${skipNote}")
} else {
logger.lifecycle('flagUnorderedJupiterTests: the following classes have more than one test '
+ 'method and no @Order annotations at all - they are implicitly relying on '
+ "declaration order:${skipNote}\n"
+ flagged.collect { " - ${it}" }.join('\n'))
}
}
}
}
/* ========================================================
* Tasks
* ======================================================== */
// ========== Task group labels ==========
def cleanupGroup = 'Cleaning'
def docsGroup = 'Documentation'
def ofbizServer = 'OFBiz Server'
def ofbizPlugin = 'OFBiz Plugin'
def sysadminGroup = 'System Administration'
// ========== OFBiz Server tasks ==========
task loadAll(group: ofbizServer) {
dependsOn 'generateSecretKeys', 'ofbiz --load-data'
description = 'Load default data; meant for OFBiz development, testing, and demo purposes'
}
task testIntegration(group: ofbizServer) {
dependsOn 'ofbiz --test'
description = 'Run OFBiz integration tests; You must run loadAll before running this task'
}
task terminateOfbiz(group: ofbizServer,
description: 'Force termination of any running OFBiz servers, only use if \"--shutdown\" command fails') {
doLast {
if (os.contains('windows')) {
Runtime.getRuntime().exec("wmic process where \"CommandLine Like \'%org.apache.ofbiz.base.start.Start%\'\" Call Terminate")
} else {
def processOutput = new ByteArrayOutputStream()
exec {
commandLine 'ps', 'ax'
standardOutput = processOutput
}
processOutput.toString().split(System.lineSeparator()).each { line ->
if (line ==~ /.*org\.apache\.ofbiz\.base\.start\.Start.*/) {
exec { commandLine 'kill', '-9', line.tokenize().first() }
}
}
}
}
}
task loadAdminUserLogin(group: ofbizServer) {
description = 'Create admin user with temporary password equal to ofbiz. You must provide userLoginId'
createOfbizCommandTask('executeLoadAdminUser',
['--load-data', 'file=/runtime/tmp/AdminUserLoginData.xml'])
executeLoadAdminUser.doFirst {
copy {
from ("${rootDir}/framework/resources/templates/AdminUserLoginData.xml") {
filter(ReplaceTokens, tokens: [userLoginId: userLoginId])
}
into "${rootDir}/runtime/tmp/"
}
}
dependsOn executeLoadAdminUser
doLast {
delete("${rootDir}/runtime/tmp/AdminUserLoginData.xml")
}
}
task loadTenant(group: ofbizServer, description: 'Load data using tenantId') {
createOfbizCommandTask('executeLoadTenant', [])
if (project.hasProperty('tenantId')) {
executeLoadTenant.args '--load-data', "delegator=default#${tenantId}"
}
if (project.hasProperty('tenantReaders')) {
executeLoadTenant.args '--load-data', "readers=${tenantReaders}"
}
if (project.hasProperty('tenantComponent')) {
executeLoadTenant.args '--load-data', "component=${tenantComponent}"
}
executeLoadTenant.doFirst {
if (!project.hasProperty('tenantId')) {
throw new GradleException('Missing project property tenantId')
}
}
dependsOn executeLoadTenant
}
task createTenant(group: ofbizServer, description: 'Create a new tenant in your environment') {
def databaseTemplateFile = "${rootDir}/framework/resources/templates/AdminNewTenantData-H2.xml"
task prepareAndValidateTenantArguments {
doLast {
if (!project.hasProperty('tenantId')) {
throw new GradleException('Project property tenantId is missing')
}
// dbPlatform values: H(H2), M(MySQL), O(Oracle), P(PostgreSQL) (default D)
if (project.hasProperty('dbPlatform')) {
if (dbPlatform == 'H') {
databaseTemplateFile = "${rootDir}/framework/resources/templates/AdminNewTenantData-H2.xml"
} else if (dbPlatform == 'M') {
databaseTemplateFile = "${rootDir}/framework/resources/templates/AdminNewTenantData-MySQL.xml"
} else if (dbPlatform == 'O') {
databaseTemplateFile = "${rootDir}/framework/resources/templates/AdminNewTenantData-Oracle.xml"
} else if (dbPlatform == 'P') {
databaseTemplateFile = "${rootDir}/framework/resources/templates/AdminNewTenantData-PostgreSQL.xml"
} else {
throw new GradleException('Invalid value for property dbPlatform: ' + "${dbPlatform}")
}
}
}
}
task generateDatabaseTemplateFile(dependsOn: prepareAndValidateTenantArguments) {
doLast {
def filterTokens = ['tenantId': tenantId,
'tenantName': project.hasProperty('tenantName') ? tenantName : tenantId,
'domainName': project.hasProperty('domainName') ? domainName : 'org.apache.ofbiz',
'db-IP': project.hasProperty('dbIp') ? dbIp : '',
'db-User': project.hasProperty('dbUser') ? dbUser : '',
'db-Password': project.hasProperty('dbPassword') ? dbPassword : '']
generateFileFromTemplate(databaseTemplateFile, 'runtime/tmp',
filterTokens, 'tmpFilteredTenantData.xml')
}
}
task generateAdminUserTemplateFile(dependsOn: prepareAndValidateTenantArguments) {
doLast {
generateFileFromTemplate(
"${rootDir}/framework/resources/templates/AdminUserLoginData.xml",
'runtime/tmp',
['userLoginId': "${tenantId}-admin".toString()],
'tmpFilteredUserLogin.xml')
}
}
// Load the tenants master database
createOfbizCommandTask('loadTenantOnMasterTenantDb',
['--load-data', 'file=/runtime/tmp/tmpFilteredTenantData.xml',
'--load-data', 'readers=tenant'])
loadTenantOnMasterTenantDb.dependsOn(generateDatabaseTemplateFile, generateAdminUserTemplateFile)
// Load the actual tenant data
createOfbizCommandTask('loadTenantData', [])
loadTenantData.dependsOn(loadTenantOnMasterTenantDb)
// Load the tenant admin user account
createOfbizCommandTask('loadTenantAdminUserLogin', [])
loadTenantAdminUserLogin.dependsOn(loadTenantData)
/* pass arguments to tasks, must be done this way
* because we are in the configuration phase. We cannot
* set the parameters at the execution phase. */
if (project.hasProperty('tenantId')) {
loadTenantData.args '--load-data', "delegator=default#${tenantId}"
loadTenantAdminUserLogin.args(
'--load-data', "delegator=default#${tenantId}",
'--load-data', "file=${rootDir}/runtime/tmp/tmpFilteredUserLogin.xml"
)
}
if (project.hasProperty('tenantReaders')) {
loadTenantData.args '--load-data', "readers=${tenantReaders}"
}
dependsOn(loadTenantAdminUserLogin)
// cleanup
doLast {
delete("${rootDir}/runtime/tmp/tmpFilteredTenantData.xml")
delete("${rootDir}/runtime/tmp/tmpFilteredUserLogin.xml")
}
}
// ========== Documentation tasks ==========
tasks.withType(AsciidoctorTask) { task ->
executionMode = JAVA_EXEC
jvm {
jvmArgs("--add-opens","java.base/sun.nio.ch=ALL-UNNAMED","--add-opens","java.base/java.io=ALL-UNNAMED")
}
outputOptions {
// I hate we have to do this - but JRuby (asciidoctorj-pdf) and Windows don't mix well
if (System.properties['os.name'].toLowerCase().contains('windows')) {
backends = ['html5']
} else {
backends = ['html5', 'pdf']
}
}
attributes \
'doctype': 'book',
'revnumber': getCurrentGitBranch(),
'experimental': '',
'allow-uri-read': true,
'icons': 'font',
'sectnums': '',
'chapter-label': '',
'toc': 'left@',
'toclevels': '3'
}
task deleteOfbizDocumentation {
doFirst { delete "${buildDir}/asciidoc/ofbiz" }
}
task deletePluginDocumentation {
doFirst {
if (!project.hasProperty('pluginId')) {
throw new GradleException('Missing property \"pluginId\"')
}
if(!(activeComponents().stream().anyMatch { it.name == pluginId })) {
throw new GradleException("Could not find plugin with id ${pluginId}")
}
delete "${buildDir}/asciidoc/plugins/${pluginId}"
}
}
task deleteAllPluginsDocumentation {
doFirst { delete "${buildDir}/asciidoc/plugins" }
}
task generateReadmeFiles(group: docsGroup, type: AsciidoctorTask) {
doFirst { delete "${buildDir}/asciidoc/readme" }
description = 'Generate OFBiz README files'
sourceDir "${rootDir}"
// CHANGELOG.adoc should be only present in the current stable version
sources {
include 'README.adoc', 'CHANGELOG.adoc', 'CONTRIBUTING.adoc', 'DOCKER.adoc'
}
outputDir = file("${buildDir}/asciidoc/readme/")
}
task generateOfbizDocumentation(group: docsGroup, type: AsciidoctorTask) {
dependsOn deleteOfbizDocumentation
description = 'Generate OFBiz documentation manuals'
activeComponents().each { component ->
copy {
from "${component}/src/docs/asciidoc/images/${component.name}"
include '**/*.*'
into "${rootDir}/docs/asciidoc/images/${component.name}"
}
}
sourceDir "${rootDir}/docs/asciidoc"
outputDir = file("${buildDir}/asciidoc/ofbiz")
doLast {
activeComponents().each { component ->
delete "${rootDir}/docs/asciidoc/images/${component.name}"
}
}
}
task generatePluginDocumentation(group: docsGroup) {
dependsOn deletePluginDocumentation
description = 'Generate plugin documentation. Expects pluginId flag'
activeComponents()
.findAll { project.hasProperty('pluginId') && it.name == pluginId }
.each { component ->
def pluginAsciidoc = task "${component.name}Documentation" (type: AsciidoctorTask) {
def asciidocFolder = new File("${component}/src/docs/asciidoc")
if (asciidocFolder.exists()) {
copy {
from "${rootDir}/docs/asciidoc/images/OFBiz-Logo.svg"
into "${component}/src/docs/asciidoc/images"
}
sourceDir file("${component}/src/docs/asciidoc")
outputDir file("${buildDir}/asciidoc/plugins/${component.name}")
doLast { println "Documentation generated for plugin ${component.name}" }
} else {
println "No documentation found for plugin ${component.name}"
}
doLast { delete "${component}/src/docs/asciidoc/images/OFBiz-Logo.svg" }
mustRunAfter deletePluginDocumentation
}
dependsOn pluginAsciidoc
doLast { delete "${component}/src/docs/asciidoc/images/OFBiz-Logo.svg" }
}
}
task generateAllPluginsDocumentation(group: docsGroup,
description: 'Generate all plugins documentation.') {
dependsOn deleteAllPluginsDocumentation
File pluginsDirectory = file(pluginsDir)
if (!pluginsDirectory.exists()) {
println("Plugins directory not found.")
return
}
pluginsDirectory.eachDir { plugin ->
activeComponents().each { component ->
if (component.name == plugin.name) {
if (subprojectExists(":plugins:${plugin.name}")) {
// Note: the "-" between "component.name" and "Documentation" allows to differentiate from
// the other inner task temporary created by the generatePluginDocumentation task
def pluginAsciidoc = task "${component.name}-Documentation" (type: AsciidoctorTask) {
def asciidocFolder = new File("${component}/src/docs/asciidoc")
doFirst {
if (asciidocFolder.exists()) {
copy {
from "${rootDir}/docs/asciidoc/images/OFBiz-Logo.svg"
into "${component}/src/docs/asciidoc/images"
}
}
}
if (asciidocFolder.exists()) {
sourceDir file("${component}/src/docs/asciidoc")
outputDir = file("${buildDir}/asciidoc/plugins/${component.name}")
doLast { println "Documentation generated for plugin ${component.name}" }
}
mustRunAfter deleteAllPluginsDocumentation
doLast { delete "${component}/src/docs/asciidoc/images/OFBiz-Logo.svg" }
}
dependsOn pluginAsciidoc
}
}
}
}
}
// ========== System Administration tasks ==========
// createTestReport/createFramedTestReport moved to test-reports.gradle
// (applied above) - kept out of this file since they're self-contained and sizable.
task gitInfoFooter(group: sysadminGroup, description: 'Update the Git Branch-revision info in the footer if Git is used') {
doLast {
def branch
def revision
def timestamp = new Date().format 'yyyy-MM-dd HH:mm:ss'
def gitFolder = rootProject.file('.git')
if (!gitFolder.exists()) {
println ('Git is not used')
return
}
def branchOutput = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
standardOutput = branchOutput
}
branch = branchOutput.toString()
def revisionOutput = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', 'HEAD'
standardOutput = revisionOutput
}
revision = revisionOutput.toString()
gitFooterFile.delete()
gitFooterFile.createNewFile()
gitFooterFile << System.lineSeparator()
gitFooterFile << '${uiLabelMap.CommonBranch} : ' + "${branch}" + System.lineSeparator()
gitFooterFile << '${uiLabelMap.CommonRevision} : ' + "${revision}" + System.lineSeparator()
gitFooterFile << '${uiLabelMap.CommonBuiltOn} : ' + "${timestamp}" + System.lineSeparator()
gitFooterFile << '${uiLabelMap.CommonJavaVersion} : ' + "${org.gradle.internal.jvm.Jvm.current()}"
}
}
// System.console() is unreliable under Gradle (it is almost always null, even with
// --console=plain), so read directly from stdin instead. This still requires --no-daemon,
// since the Gradle daemon is detached from the terminal and stdin is not forwarded to it.
def stdinReader = new BufferedReader(new InputStreamReader(System.in))
// Reads a non-sensitive value (e.g. a lookup key) from stdin.
def promptValue = { String prompt ->
print prompt
System.out.flush()
def line = stdinReader.readLine()
if (!line) {
throw new GradleException("No value entered. Re-run with --no-daemon from an interactive "
+ "terminal, or pass the value via -P.")
}
line
}
// Reads a sensitive value (password/master key) from stdin, masking the terminal echo via
// `stty` (when a tty is available) so it never appears in shell history, `ps`, or CI logs.
def promptSecret = { String prompt ->
print prompt
System.out.flush()
def ttyAvailable = new File('/dev/tty').exists()
if (ttyAvailable) {
['sh', '-c', 'stty -echo < /dev/tty'].execute().waitFor()
}
try {
def line = stdinReader.readLine()
if (!line) {
throw new GradleException("No value entered. Re-run with --no-daemon from an interactive "
+ "terminal, or pass the value via -P.")