diff --git a/.gitignore b/.gitignore index c71b4410aa..0ded2a2277 100644 --- a/.gitignore +++ b/.gitignore @@ -14,8 +14,6 @@ nbproject/private framework/tests-results framework/src/version framework/src/play/version -framework/src/play/version -framework/src/play/version framework/tests/test-application/db framework/play-*.jar framework/docs @@ -33,7 +31,6 @@ eclipse .project id framework/tests-tmp -framework/docs dist modules/bespin/lib/bespin.jar modules/ecss/lib/ecss.jar @@ -42,7 +39,6 @@ resources/catalog.xml resources/nbproject/private modules/gae/lib/gae.jar catalog.xml -modules/gae/lib/gae.jar play-*.jar modules/gae/bin modules/gwt/lib/play-gwt.jar @@ -51,7 +47,6 @@ test-result logs db *.pyc -test-result samples-and-tests/with-gwt/nbproject samples-and-tests/jobboard/db samples-and-tests/jobboard/tmp @@ -133,11 +128,7 @@ atlassian-ide-plugin.xml modules/* build.classes modules/crud/nbproject -nbproject -samples-and-tests/jobboard/attachments samples-and-tests/jobboard/logs -samples-and-tests/jobboard/test-result -samples-and-tests/jobboard/tmp samples-and-tests/validation/logs samples-and-tests/zencontact/precompiled !modules/docviewer @@ -148,4 +139,3 @@ samples-and-tests/zencontact/precompiled !modules/testrunner !framework/src/play/db !framework/test-src/play/db -*~ diff --git a/documentation/manual/configuration.textile b/documentation/manual/configuration.textile index 48620bbd99..3c4bd74b13 100644 --- a/documentation/manual/configuration.textile +++ b/documentation/manual/configuration.textile @@ -758,7 +758,7 @@ Java source level, which overrides the @java.version@ system property. For examp bc. java.source=11 -Values: @1.7@ (No longer supported since 1.5.0), @1.8@ (No longer supported since 1.7.0), @9@ (No longer supported since 1.7.0), @10@ (No longer supported since 1.7.0), @11@, @12@, @13@, @14@, @15@, @17@. +Values: @1.7@ (No longer supported since 1.5.0), @1.8@ (No longer supported since 1.7.0), @9@ (No longer supported since 1.7.0), @10@ (No longer supported since 1.7.0), @11@, @12@, @13@, @14@, @15@, @17@, @18@. Default: @11@ diff --git a/documentation/manual/home.textile b/documentation/manual/home.textile index e81cfb6e94..5c2be8b276 100644 --- a/documentation/manual/home.textile +++ b/documentation/manual/home.textile @@ -189,6 +189,7 @@ h2. Version notes New versions of Play include certain changes. Check older release notes for: # "About Play releases":releases/releases +# "Play 1.7.1":releases/release1.7.x/releasenotes-1.7.1 # "Play 1.7.0":releases/release1.7.x/releasenotes-1.7.0 # "Play 1.6.0":releases/release1.6.x/releasenotes-1.6.0 # "Play 1.5.3":releases/release1.5.x/releasenotes-1.5.3 diff --git a/documentation/manual/releases/release1.7.x/releasenotes-1.7.1.textile b/documentation/manual/releases/release1.7.x/releasenotes-1.7.1.textile new file mode 100644 index 0000000000..cecb042823 --- /dev/null +++ b/documentation/manual/releases/release1.7.x/releasenotes-1.7.1.textile @@ -0,0 +1,25 @@ +# Play 1.7.1 -- Release notes + +Play 1.7.1 has been released of the master branch. + +The changes in this release are listed in the "1.7.1 on github":https://github.com/playframework/play1/milestone/7832586 including 13 resolved tickets. + + +## What's new in Play 1.7.1 + + +## What's fixed in Play 1.7.1 + +* "#1397":https://github.com/playframework/play1/issues/1397 : Third party dependency update 20220403 +* "#1399":https://github.com/playframework/play1/issues/1399 : [1.7.0] Regression: `play idealize` dies with `UnboundLocalError: local variable 'playHome' referenced before assignment` +* "#1400":https://github.com/playframework/play1/issues/1400 : fixed #1399 "UnboundLocalError: local variable 'playHome' referenced before assignment +* "#1401":https://github.com/playframework/play1/issues/1401 : Python3 incompatibilities in module manipulations +* "#1402":https://github.com/playframework/play1/issues/1402 : [#1401] 🐛 Fix python3 incompatibilities in module manipulation code +* "#1403":https://github.com/playframework/play1/issues/1403 : Temporary class of Groovy template is output directly under application dir +* "#1405":https://github.com/playframework/play1/issues/1405 : 1.7.0: concurrent modification exception +* "#1406":https://github.com/playframework/play1/issues/1406 : [#1403] 🐛 Fix Groovy compilation unit that tries to write in applicat… +* "#1408":https://github.com/playframework/play1/issues/1408 : #1405: replace HashMap be ConcurrentHashMap +* "#1409":https://github.com/playframework/play1/issues/1409 : update check of java version +* "#1411":https://github.com/playframework/play1/issues/1411 : Do not overwrite system property net.spy.log.LoggerImpl -> 1.7.1 +* "#1413":https://github.com/playframework/play1/issues/1413 : #1405: replace HashMap be ConcurrentHashMap +* "#1414":https://github.com/playframework/play1/issues/1414 : Memcached implementaion broken due to log4j update \ No newline at end of file diff --git a/documentation/manual/releases/releases.textile b/documentation/manual/releases/releases.textile index 2c744937f5..ea327f932a 100644 --- a/documentation/manual/releases/releases.textile +++ b/documentation/manual/releases/releases.textile @@ -4,6 +4,7 @@ You can download Play releases "here":https://www.playframework.com/download. Ea h2. Play 1.7.x +# "Play 1.7.1":release1.7.x/releasenotes-1.7.1 # "Play 1.7.0":release1.7.x/releasenotes-1.7.0 h2. Play 1.6.x diff --git a/framework/build.xml b/framework/build.xml index ed6055fdf9..516feec6e5 100644 --- a/framework/build.xml +++ b/framework/build.xml @@ -233,7 +233,7 @@ - + diff --git a/framework/dependencies.yml b/framework/dependencies.yml index 4f4664ea5a..11c94be58d 100644 --- a/framework/dependencies.yml +++ b/framework/dependencies.yml @@ -10,13 +10,13 @@ require: &allDependencies - antlr 2.7.7 - com.mchange -> c3p0 0.9.5.5 - com.zaxxer -> HikariCP 5.0.1 - - org.ow2.asm -> asm 9.2 - - org.ow2.asm -> asm-commons 9.2 - - org.ow2.asm -> asm-util 9.2 - - org.ow2.asm -> asm-tree 9.2 - - org.ow2.asm -> asm-analysis 9.2 + - org.ow2.asm -> asm 9.3 + - org.ow2.asm -> asm-commons 9.3 + - org.ow2.asm -> asm-util 9.3 + - org.ow2.asm -> asm-tree 9.3 + - org.ow2.asm -> asm-analysis 9.3 - cglib -> cglib 3.3.0 - - com.google.code.gson -> gson 2.8.9 + - com.google.code.gson -> gson 2.9.1 - com.jamonapi -> jamon 2.82 - com.ning -> async-http-client 1.9.40 - commons-beanutils 1.9.4 @@ -34,50 +34,51 @@ require: &allDependencies - javax.inject 1.0 - javax.validation -> validation-api 1.1.0.Final - jaxen 1.2.0 - - joda-time 2.10.13 + - joda-time 2.11.1 - org.hamcrest -> hamcrest-all 1.3 - junit 4.13.2 - jregex 1.2_01 - - log4j-api 2.17.1 - - log4j-core 2.17.1 + - log4j-api 2.18.0 + - log4j-core 2.18.0 - net.sf.ehcache -> ehcache 2.10.9.2 - net.sf.ezmorph -> ezmorph 1.0.6 - net.sf.jsr107cache -> jsr107cache 1.1 - net.sf.oval -> oval 3.1.0 - - mysql -> mysql-connector-java 8.0.28 + - mysql -> mysql-connector-java 8.0.30 - oauth.signpost -> signpost-core 1.2.1.2 - org.apache.geronimo.specs -> geronimo-servlet_2.5_spec 1.2 - org.apache.ivy -> ivy 2.5.0 - - org.bouncycastle -> bcprov-jdk15on 1.70 - - org.bouncycastle -> bcpkix-jdk15on 1.70 - - org.bouncycastle -> bcutil-jdk15on 1.70 - - org.codehaus.groovy -> groovy 3.0.9 - - org.codehaus.groovy -> groovy-xml 3.0.9 - - org.eclipse.jdt -> org.eclipse.jdt.core 3.28.0 + - org.bouncycastle -> bcprov-jdk18on 1.71.1 + - org.bouncycastle -> bcpkix-jdk18on 1.71.1 + - org.bouncycastle -> bcutil-jdk18on 1.71.1 + - org.codehaus.groovy -> groovy 3.0.12 + - org.codehaus.groovy -> groovy-xml 3.0.12 + - org.eclipse.jdt -> org.eclipse.jdt.core 3.31.0 - org.hibernate -> hibernate-core 5.6.5.Final.patched - - net.bytebuddy -> byte-buddy 1.12.7 + - net.bytebuddy -> byte-buddy 1.12.16 - javax.persistence -> javax.persistence-api 2.2 - org.hibernate.common -> hibernate-commons-annotations 5.1.2.Final - org.hibernate -> hibernate-validator 5.4.1.Final - - org.jboss.logging -> jboss-logging 3.4.3.Final + - org.jboss -> jandex 2.4.3.Final + - org.jboss.logging -> jboss-logging 3.5.0.Final - org.jboss.spec.javax.transaction -> jboss-transaction-api_1.2_spec 1.1.1.Final - javax.persistence -> javax.persistence-api 2.2 - javax.xml.bind -> jaxb-api 2.3.1 - org.glassfish.jaxb -> jaxb-runtime 2.3.6 - com.fasterxml -> classmate 1.5.1 - - org.hibernate -> hibernate-c3p0 5.6.5.Final - - org.hibernate -> hibernate-ehcache 5.6.5.Final + - org.hibernate -> hibernate-c3p0 5.6.11.Final + - org.hibernate -> hibernate-ehcache 5.6.11.Final - com.mchange -> mchange-commons-java 0.2.20 - - org.javassist -> javassist 3.28.0-GA + - org.javassist -> javassist 3.29.1-GA - io.netty -> netty 3.10.6.Final - - org.postgresql -> postgresql 42.3.1 - - org.slf4j -> slf4j-api 1.7.35 - - org.apache.logging.log4j -> log4j-slf4j-impl 2.17.1 - - org.yaml -> snakeyaml 1.30 + - org.postgresql -> postgresql 42.5.0 + - org.slf4j -> slf4j-api 1.7.36 + - org.apache.logging.log4j -> log4j-slf4j-impl 2.18.0 + - org.yaml -> snakeyaml 1.32 - net.spy -> spymemcached 2.12.3 - com.thoughtworks.xstream -> xstream 1.4.19 - xmlpull 1.1.3.4d_b4_min - - org.apache.logging.log4j -> log4j-web 2.17.1 + - org.apache.logging.log4j -> log4j-web 2.18.0 # Default repositories, used for all projects repositories: diff --git a/framework/lib/asm-9.2.jar b/framework/lib/asm-9.2.jar deleted file mode 100644 index 3557ae4140..0000000000 Binary files a/framework/lib/asm-9.2.jar and /dev/null differ diff --git a/framework/lib/asm-9.3.jar b/framework/lib/asm-9.3.jar new file mode 100644 index 0000000000..bd8b948601 Binary files /dev/null and b/framework/lib/asm-9.3.jar differ diff --git a/framework/lib/asm-analysis-9.2.jar b/framework/lib/asm-analysis-9.2.jar deleted file mode 100644 index 9d575ca1cc..0000000000 Binary files a/framework/lib/asm-analysis-9.2.jar and /dev/null differ diff --git a/framework/lib/asm-analysis-9.3.jar b/framework/lib/asm-analysis-9.3.jar new file mode 100644 index 0000000000..6bbfb05cbc Binary files /dev/null and b/framework/lib/asm-analysis-9.3.jar differ diff --git a/framework/lib/asm-commons-9.2.jar b/framework/lib/asm-commons-9.2.jar deleted file mode 100644 index 01028a0035..0000000000 Binary files a/framework/lib/asm-commons-9.2.jar and /dev/null differ diff --git a/framework/lib/asm-commons-9.3.jar b/framework/lib/asm-commons-9.3.jar new file mode 100644 index 0000000000..3ce4b82cb6 Binary files /dev/null and b/framework/lib/asm-commons-9.3.jar differ diff --git a/framework/lib/asm-tree-9.2.jar b/framework/lib/asm-tree-9.3.jar similarity index 56% rename from framework/lib/asm-tree-9.2.jar rename to framework/lib/asm-tree-9.3.jar index 0a6833a688..55ef2a925e 100644 Binary files a/framework/lib/asm-tree-9.2.jar and b/framework/lib/asm-tree-9.3.jar differ diff --git a/framework/lib/asm-util-9.2.jar b/framework/lib/asm-util-9.2.jar deleted file mode 100644 index 3afe6e6992..0000000000 Binary files a/framework/lib/asm-util-9.2.jar and /dev/null differ diff --git a/framework/lib/asm-util-9.3.jar b/framework/lib/asm-util-9.3.jar new file mode 100644 index 0000000000..15e5efde41 Binary files /dev/null and b/framework/lib/asm-util-9.3.jar differ diff --git a/framework/lib/bcpkix-jdk15on-1.70.jar b/framework/lib/bcpkix-jdk15on-1.70.jar deleted file mode 100644 index 07223f634c..0000000000 Binary files a/framework/lib/bcpkix-jdk15on-1.70.jar and /dev/null differ diff --git a/framework/lib/bcpkix-jdk18on-1.71.1.jar b/framework/lib/bcpkix-jdk18on-1.71.1.jar new file mode 100644 index 0000000000..40c84725f9 Binary files /dev/null and b/framework/lib/bcpkix-jdk18on-1.71.1.jar differ diff --git a/framework/lib/bcprov-jdk15on-1.70.jar b/framework/lib/bcprov-jdk15on-1.70.jar deleted file mode 100644 index 0e4198e5a4..0000000000 Binary files a/framework/lib/bcprov-jdk15on-1.70.jar and /dev/null differ diff --git a/framework/lib/bcprov-jdk18on-1.71.1.jar b/framework/lib/bcprov-jdk18on-1.71.1.jar new file mode 100644 index 0000000000..2bec110f1d Binary files /dev/null and b/framework/lib/bcprov-jdk18on-1.71.1.jar differ diff --git a/framework/lib/bcutil-jdk15on-1.70.jar b/framework/lib/bcutil-jdk15on-1.70.jar deleted file mode 100644 index c363f0c1fa..0000000000 Binary files a/framework/lib/bcutil-jdk15on-1.70.jar and /dev/null differ diff --git a/framework/lib/bcutil-jdk18on-1.71.1.jar b/framework/lib/bcutil-jdk18on-1.71.1.jar new file mode 100644 index 0000000000..b20e960461 Binary files /dev/null and b/framework/lib/bcutil-jdk18on-1.71.1.jar differ diff --git a/framework/lib/byte-buddy-1.12.16.jar b/framework/lib/byte-buddy-1.12.16.jar new file mode 100644 index 0000000000..3f70b08f8a Binary files /dev/null and b/framework/lib/byte-buddy-1.12.16.jar differ diff --git a/framework/lib/byte-buddy-1.12.7.jar b/framework/lib/byte-buddy-1.12.7.jar deleted file mode 100644 index 33faa1cc20..0000000000 Binary files a/framework/lib/byte-buddy-1.12.7.jar and /dev/null differ diff --git a/framework/lib/groovy-3.0.9.jar b/framework/lib/groovy-3.0.12.jar similarity index 74% rename from framework/lib/groovy-3.0.9.jar rename to framework/lib/groovy-3.0.12.jar index 7ef104694f..fc1b0378f1 100644 Binary files a/framework/lib/groovy-3.0.9.jar and b/framework/lib/groovy-3.0.12.jar differ diff --git a/framework/lib/groovy-xml-3.0.9.jar b/framework/lib/groovy-xml-3.0.12.jar similarity index 79% rename from framework/lib/groovy-xml-3.0.9.jar rename to framework/lib/groovy-xml-3.0.12.jar index 41b98c6c27..c49f8d8674 100644 Binary files a/framework/lib/groovy-xml-3.0.9.jar and b/framework/lib/groovy-xml-3.0.12.jar differ diff --git a/framework/lib/gson-2.8.9.jar b/framework/lib/gson-2.8.9.jar deleted file mode 100644 index 3351867c1c..0000000000 Binary files a/framework/lib/gson-2.8.9.jar and /dev/null differ diff --git a/framework/lib/gson-2.9.1.jar b/framework/lib/gson-2.9.1.jar new file mode 100644 index 0000000000..8a663ecceb Binary files /dev/null and b/framework/lib/gson-2.9.1.jar differ diff --git a/framework/lib/hibernate-c3p0-5.6.11.Final.jar b/framework/lib/hibernate-c3p0-5.6.11.Final.jar new file mode 100644 index 0000000000..5f03d02273 Binary files /dev/null and b/framework/lib/hibernate-c3p0-5.6.11.Final.jar differ diff --git a/framework/lib/hibernate-c3p0-5.6.5.Final.jar b/framework/lib/hibernate-c3p0-5.6.5.Final.jar deleted file mode 100644 index 4005114624..0000000000 Binary files a/framework/lib/hibernate-c3p0-5.6.5.Final.jar and /dev/null differ diff --git a/framework/lib/hibernate-ehcache-5.6.11.Final.jar b/framework/lib/hibernate-ehcache-5.6.11.Final.jar new file mode 100644 index 0000000000..4692e2080a Binary files /dev/null and b/framework/lib/hibernate-ehcache-5.6.11.Final.jar differ diff --git a/framework/lib/hibernate-ehcache-5.6.5.Final.jar b/framework/lib/hibernate-ehcache-5.6.5.Final.jar deleted file mode 100644 index eb954ef59a..0000000000 Binary files a/framework/lib/hibernate-ehcache-5.6.5.Final.jar and /dev/null differ diff --git a/framework/lib/jandex-2.4.2.Final.jar b/framework/lib/jandex-2.4.2.Final.jar deleted file mode 100644 index 8e17960e7f..0000000000 Binary files a/framework/lib/jandex-2.4.2.Final.jar and /dev/null differ diff --git a/framework/lib/jandex-2.4.3.Final.jar b/framework/lib/jandex-2.4.3.Final.jar new file mode 100644 index 0000000000..7f8e2a05f3 Binary files /dev/null and b/framework/lib/jandex-2.4.3.Final.jar differ diff --git a/framework/lib/javassist-3.28.0-GA.jar b/framework/lib/javassist-3.28.0-GA.jar deleted file mode 100644 index 5f28011f2c..0000000000 Binary files a/framework/lib/javassist-3.28.0-GA.jar and /dev/null differ diff --git a/framework/lib/javassist-3.29.1-GA.jar b/framework/lib/javassist-3.29.1-GA.jar new file mode 100644 index 0000000000..aa7b5a98e2 Binary files /dev/null and b/framework/lib/javassist-3.29.1-GA.jar differ diff --git a/framework/lib/jboss-logging-3.4.3.Final.jar b/framework/lib/jboss-logging-3.4.3.Final.jar deleted file mode 100644 index 31d55c6ce5..0000000000 Binary files a/framework/lib/jboss-logging-3.4.3.Final.jar and /dev/null differ diff --git a/framework/lib/jboss-logging-3.5.0.Final.jar b/framework/lib/jboss-logging-3.5.0.Final.jar new file mode 100644 index 0000000000..d39dfcfa58 Binary files /dev/null and b/framework/lib/jboss-logging-3.5.0.Final.jar differ diff --git a/framework/lib/joda-time-2.10.13.jar b/framework/lib/joda-time-2.10.13.jar deleted file mode 100644 index 00f20ad28c..0000000000 Binary files a/framework/lib/joda-time-2.10.13.jar and /dev/null differ diff --git a/framework/lib/joda-time-2.11.1.jar b/framework/lib/joda-time-2.11.1.jar new file mode 100644 index 0000000000..b1697b5510 Binary files /dev/null and b/framework/lib/joda-time-2.11.1.jar differ diff --git a/framework/lib/log4j-api-2.17.1.jar b/framework/lib/log4j-api-2.18.0.jar similarity index 51% rename from framework/lib/log4j-api-2.17.1.jar rename to framework/lib/log4j-api-2.18.0.jar index 605c45d043..b4e933f7ec 100644 Binary files a/framework/lib/log4j-api-2.17.1.jar and b/framework/lib/log4j-api-2.18.0.jar differ diff --git a/framework/lib/log4j-core-2.17.1.jar b/framework/lib/log4j-core-2.18.0.jar similarity index 50% rename from framework/lib/log4j-core-2.17.1.jar rename to framework/lib/log4j-core-2.18.0.jar index bbead1267d..d6486fdf3d 100644 Binary files a/framework/lib/log4j-core-2.17.1.jar and b/framework/lib/log4j-core-2.18.0.jar differ diff --git a/framework/lib/log4j-slf4j-impl-2.17.1.jar b/framework/lib/log4j-slf4j-impl-2.18.0.jar similarity index 68% rename from framework/lib/log4j-slf4j-impl-2.17.1.jar rename to framework/lib/log4j-slf4j-impl-2.18.0.jar index 8958169fe6..cc41910c32 100644 Binary files a/framework/lib/log4j-slf4j-impl-2.17.1.jar and b/framework/lib/log4j-slf4j-impl-2.18.0.jar differ diff --git a/framework/lib/log4j-web-2.17.1.jar b/framework/lib/log4j-web-2.17.1.jar deleted file mode 100644 index 3170793652..0000000000 Binary files a/framework/lib/log4j-web-2.17.1.jar and /dev/null differ diff --git a/framework/lib/log4j-web-2.18.0.jar b/framework/lib/log4j-web-2.18.0.jar new file mode 100644 index 0000000000..87e7a9bf74 Binary files /dev/null and b/framework/lib/log4j-web-2.18.0.jar differ diff --git a/framework/lib/mysql-connector-java-8.0.28.jar b/framework/lib/mysql-connector-java-8.0.28.jar deleted file mode 100644 index ac8904ee7d..0000000000 Binary files a/framework/lib/mysql-connector-java-8.0.28.jar and /dev/null differ diff --git a/framework/lib/mysql-connector-java-8.0.30.jar b/framework/lib/mysql-connector-java-8.0.30.jar new file mode 100644 index 0000000000..92ebe1b54a Binary files /dev/null and b/framework/lib/mysql-connector-java-8.0.30.jar differ diff --git a/framework/lib/org.eclipse.jdt.core-3.28.0.jar b/framework/lib/org.eclipse.jdt.core-3.31.0.jar similarity index 65% rename from framework/lib/org.eclipse.jdt.core-3.28.0.jar rename to framework/lib/org.eclipse.jdt.core-3.31.0.jar index 4383557086..3a49c313b8 100644 Binary files a/framework/lib/org.eclipse.jdt.core-3.28.0.jar and b/framework/lib/org.eclipse.jdt.core-3.31.0.jar differ diff --git a/framework/lib/postgresql-42.3.1.jar b/framework/lib/postgresql-42.5.0.jar similarity index 63% rename from framework/lib/postgresql-42.3.1.jar rename to framework/lib/postgresql-42.5.0.jar index 17af3fcd85..49b9556223 100644 Binary files a/framework/lib/postgresql-42.3.1.jar and b/framework/lib/postgresql-42.5.0.jar differ diff --git a/framework/lib/slf4j-api-1.7.35.jar b/framework/lib/slf4j-api-1.7.36.jar similarity index 63% rename from framework/lib/slf4j-api-1.7.35.jar rename to framework/lib/slf4j-api-1.7.36.jar index b60823f5c6..7d3ce68d25 100644 Binary files a/framework/lib/slf4j-api-1.7.35.jar and b/framework/lib/slf4j-api-1.7.36.jar differ diff --git a/framework/lib/snakeyaml-1.30.jar b/framework/lib/snakeyaml-1.30.jar deleted file mode 100644 index 6c9b2bc65b..0000000000 Binary files a/framework/lib/snakeyaml-1.30.jar and /dev/null differ diff --git a/framework/lib/snakeyaml-1.32.jar b/framework/lib/snakeyaml-1.32.jar new file mode 100644 index 0000000000..cd73a293a6 Binary files /dev/null and b/framework/lib/snakeyaml-1.32.jar differ diff --git a/framework/pym/play/application.py b/framework/pym/play/application.py index 644d041708..31730463ad 100644 --- a/framework/pym/play/application.py +++ b/framework/pym/play/application.py @@ -296,8 +296,8 @@ def java_cmd(self, java_args, cp_args=None, className='play.server.Server', args javaVersion = getJavaVersion() print("~ using java version \"%s\"" % javaVersion) - if javaVersion.startswith("1.5") or javaVersion.startswith("1.6") or javaVersion.startswith("1.7"): - print("~ ERROR: java version prior to 1.8 are no longer supported: current version \"%s\" : please update" % javaVersion) + if javaVersion.startswith("1.5") or javaVersion.startswith("1.6") or javaVersion.startswith("1.7") or javaVersion.startswith("1.8") or javaVersion.startswith("9") or javaVersion.startswith("10") : + print("~ ERROR: java version prior to 11 are no longer supported: current version \"%s\" : please update" % javaVersion) java_args.append('-noverify') diff --git a/framework/pym/play/commands/intellij.py b/framework/pym/play/commands/intellij.py index 4c61e9c7d6..2ac28acc62 100644 --- a/framework/pym/play/commands/intellij.py +++ b/framework/pym/play/commands/intellij.py @@ -25,6 +25,7 @@ def execute(**kargs): shutil.copyfile(os.path.join(play_env["basedir"], 'resources/idea/imlTemplate.xml'), imlFile) cpXML = "" + playHome = play_env["basedir"].replace('\\', '/') playHomeAlternative = app.toRelative(playHome).replace('\\', '/') if playHomeAlternative[0:2] == "..": playHome = "$MODULE_DIR$/" + playHomeAlternative diff --git a/framework/pym/play/commands/modulesrepo.py b/framework/pym/play/commands/modulesrepo.py index c05dbd125d..d76681cc42 100644 --- a/framework/pym/play/commands/modulesrepo.py +++ b/framework/pym/play/commands/modulesrepo.py @@ -239,7 +239,7 @@ def new(app, args, play_env): replaceAll(os.path.join(app.path, 'conf/messages'), r'%MODULE%', application_name) replaceAll(os.path.join(app.path, 'conf/dependencies.yml'), r'%MODULE%', application_name) replaceAll(os.path.join(app.path, 'conf/routes'), r'%MODULE%', application_name) - replaceAll(os.path.join(app.path, 'conf/routes'), r'%MODULE_LOWERCASE%', string.lower(application_name)) + replaceAll(os.path.join(app.path, 'conf/routes'), r'%MODULE_LOWERCASE%', application_name.lower()) os.mkdir(os.path.join(app.path, 'app')) os.mkdir(os.path.join(app.path, 'app/controllers')) os.mkdir(os.path.join(app.path, 'app/controllers/%s' % application_name)) diff --git a/framework/src/play/Invoker.java b/framework/src/play/Invoker.java index 2c11ce19d3..3f2b91bc2b 100644 --- a/framework/src/play/Invoker.java +++ b/framework/src/play/Invoker.java @@ -413,10 +413,9 @@ public String getErrorDescription() { static class WaitForTasksCompletion extends Thread { static WaitForTasksCompletion instance; - Map, Invocation> queue; + final Map, Invocation> queue = new ConcurrentHashMap<>(); public WaitForTasksCompletion() { - queue = new ConcurrentHashMap<>(); setName("WaitForTasksCompletion"); setDaemon(true); } diff --git a/framework/src/play/Logger.java b/framework/src/play/Logger.java index 6eedae5a4c..d2cb7ae1be 100644 --- a/framework/src/play/Logger.java +++ b/framework/src/play/Logger.java @@ -47,7 +47,7 @@ public class Logger { /** * When using java.util.logging. */ - public static java.util.logging.Logger juli = java.util.logging.Logger.getLogger("play"); + public static final java.util.logging.Logger juli = java.util.logging.Logger.getLogger("play"); /** * true if logger is configured manually (log4j-config file supplied by application) */ diff --git a/framework/src/play/Play.java b/framework/src/play/Play.java index 2b3024b0f6..2c17dfd51f 100644 --- a/framework/src/play/Play.java +++ b/framework/src/play/Play.java @@ -117,7 +117,7 @@ public boolean isProd() { /** * All paths to search for files */ - public static List roots = new ArrayList<>(16); + public static final List roots = new ArrayList<>(16); /** * All paths to search for Java files */ @@ -125,7 +125,7 @@ public boolean isProd() { /** * All paths to search for templates files */ - public static List templatesPath = new ArrayList<>(2); + public static final List templatesPath = new ArrayList<>(2); /** * Main routes file */ @@ -133,7 +133,7 @@ public boolean isProd() { /** * Plugin routes files */ - public static Map modulesRoutes = new HashMap<>(16); + public static final Map modulesRoutes = new HashMap<>(16); /** * The loaded configuration files */ @@ -168,7 +168,7 @@ public boolean isProd() { /** * Modules */ - public static Map modules = new HashMap<>(16); + public static final Map modules = new HashMap<>(16); /** * Framework version */ @@ -433,7 +433,7 @@ private static Properties readOneConfigurationFile(String filename) { for (Object key : propsFromFile.keySet()) { String value = propsFromFile.getProperty(key.toString()); Matcher matcher = pattern.matcher(value); - StringBuffer newValue = new StringBuffer(100); + StringBuilder newValue = new StringBuilder(100); while (matcher.find()) { String jp = matcher.group(1); String r; diff --git a/framework/src/play/PlayPlugin.java b/framework/src/play/PlayPlugin.java index 414295bdb4..ccdebe9f0e 100644 --- a/framework/src/play/PlayPlugin.java +++ b/framework/src/play/PlayPlugin.java @@ -527,7 +527,7 @@ public Collection getFunctionalTests() { * transaction around an action. The filter applies a transaction to the current Action. */ public abstract static class Filter { - String name; + final String name; public Filter(String name) { this.name = name; diff --git a/framework/src/play/cache/EhCacheImpl.java b/framework/src/play/cache/EhCacheImpl.java index a8f604620d..3b08410737 100644 --- a/framework/src/play/cache/EhCacheImpl.java +++ b/framework/src/play/cache/EhCacheImpl.java @@ -20,16 +20,15 @@ */ public class EhCacheImpl implements CacheImpl { + private static final String cacheName = "play"; private static EhCacheImpl uniqueInstance; - CacheManager cacheManager; + final CacheManager cacheManager = CacheManager.create(); - net.sf.ehcache.Cache cache; + final net.sf.ehcache.Cache cache; - private static final String cacheName = "play"; private EhCacheImpl() { - this.cacheManager = CacheManager.create(); this.cacheManager.addCache(cacheName); this.cache = cacheManager.getCache(cacheName); } diff --git a/framework/src/play/cache/MemcachedImpl.java b/framework/src/play/cache/MemcachedImpl.java index 59454ad14a..31d4726061 100644 --- a/framework/src/play/cache/MemcachedImpl.java +++ b/framework/src/play/cache/MemcachedImpl.java @@ -90,7 +90,10 @@ protected byte[] serialize(Object object) { } public void initClient() throws IOException { - System.setProperty("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.Log4JLogger"); + String loggerImpl = System.getProperty("net.spy.log.LoggerImpl"); + if (loggerImpl == null) { + System.setProperty("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.SLF4JLogger"); + } List addrs; if (Play.configuration.containsKey("memcached.host")) { diff --git a/framework/src/play/classloading/ApplicationClasses.java b/framework/src/play/classloading/ApplicationClasses.java index 3874f6ad9d..9e7eec9d5a 100644 --- a/framework/src/play/classloading/ApplicationClasses.java +++ b/framework/src/play/classloading/ApplicationClasses.java @@ -5,9 +5,9 @@ import java.io.FileOutputStream; import java.lang.annotation.Annotation; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import javassist.ClassPool; import javassist.CtClass; @@ -26,17 +26,17 @@ public class ApplicationClasses { /** * Reference to the eclipse compiler. */ - ApplicationCompiler compiler = new ApplicationCompiler(this); + final ApplicationCompiler compiler = new ApplicationCompiler(this); /** * Cache of all compiled classes */ - Map classes = new HashMap<>(); + Map classes = new ConcurrentHashMap<>(); /** * Clear the classes cache */ public void clear() { - classes = new HashMap<>(); + classes = new ConcurrentHashMap<>(); } /** diff --git a/framework/src/play/classloading/ApplicationClassloader.java b/framework/src/play/classloading/ApplicationClassloader.java index 53d9a20488..85d305f443 100644 --- a/framework/src/play/classloading/ApplicationClassloader.java +++ b/framework/src/play/classloading/ApplicationClassloader.java @@ -322,8 +322,7 @@ public void detectChanges() throws RestartNeededException { modifieds.add(applicationClass); } } - Set modifiedWithDependencies = new HashSet<>(); - modifiedWithDependencies.addAll(modifieds); + Set modifiedWithDependencies = new HashSet<>(modifieds); if (!modifieds.isEmpty()) { modifiedWithDependencies.addAll(Play.pluginCollection.onClassesChange(modifieds)); } @@ -449,7 +448,7 @@ public List getAllClasses() { } } - Collections.sort(result, Comparator.comparing(Class::getName)); + result.sort(Comparator.comparing(Class::getName)); } Map byNormalizedName = new HashMap<>(result.size()); diff --git a/framework/src/play/classloading/ApplicationClassloaderState.java b/framework/src/play/classloading/ApplicationClassloaderState.java index 20bbc73191..725ea9d7a7 100644 --- a/framework/src/play/classloading/ApplicationClassloaderState.java +++ b/framework/src/play/classloading/ApplicationClassloaderState.java @@ -13,7 +13,7 @@ * they could check if the state of the ApplicationClassloader has changed.. */ public class ApplicationClassloaderState { - private static AtomicLong nextStateValue = new AtomicLong(); + private static final AtomicLong nextStateValue = new AtomicLong(); private final long currentStateValue = nextStateValue.getAndIncrement(); @@ -24,9 +24,7 @@ public boolean equals(Object o) { ApplicationClassloaderState that = (ApplicationClassloaderState) o; - if (currentStateValue != that.currentStateValue) return false; - - return true; + return this.currentStateValue == that.currentStateValue; } @Override diff --git a/framework/src/play/classloading/ApplicationCompiler.java b/framework/src/play/classloading/ApplicationCompiler.java index d474a0a6d3..f0ce32ef34 100644 --- a/framework/src/play/classloading/ApplicationCompiler.java +++ b/framework/src/play/classloading/ApplicationCompiler.java @@ -34,20 +34,21 @@ */ public class ApplicationCompiler { - Map packagesCache = new HashMap<>(); - ApplicationClasses applicationClasses; - Map settings; private static final String JAVA_SOURCE_DEFAULT_VERSION = "11"; - static final Map compatibleJavaVersions = new HashMap<>(); - static { - compatibleJavaVersions.put("11", CompilerOptions.VERSION_11); - compatibleJavaVersions.put("12", CompilerOptions.VERSION_12); - compatibleJavaVersions.put("13", CompilerOptions.VERSION_13); - compatibleJavaVersions.put("14", CompilerOptions.VERSION_14); - compatibleJavaVersions.put("15", CompilerOptions.VERSION_15); - compatibleJavaVersions.put("16", CompilerOptions.VERSION_16); - compatibleJavaVersions.put("17", CompilerOptions.VERSION_17); - } + static final Map compatibleJavaVersions = Map.of( + "11", CompilerOptions.VERSION_11, + "12", CompilerOptions.VERSION_12, + "13", CompilerOptions.VERSION_13, + "14", CompilerOptions.VERSION_14, + "15", CompilerOptions.VERSION_15, + "16", CompilerOptions.VERSION_16, + "17", CompilerOptions.VERSION_17, + "18", CompilerOptions.VERSION_18 + ); + + final Map packagesCache = new HashMap<>(); + final ApplicationClasses applicationClasses; + final Map settings; /** * Try to guess the magic configuration options @@ -56,32 +57,33 @@ public class ApplicationCompiler { * The application classes container */ public ApplicationCompiler(ApplicationClasses applicationClasses) { - this.applicationClasses = applicationClasses; - this.settings = new HashMap<>(); - this.settings.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); - this.settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); - this.settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_Encoding, "UTF-8"); - this.settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); - final String runningJavaVersion = System.getProperty("java.version"); - if (Stream.of("1.5", "1.6", "1.7", "1.8", "9", "10").anyMatch(runningJavaVersion::startsWith)) { + if (Stream.of("1.5", "1.6", "1.7", "1.8", "9", "10").anyMatch(runningJavaVersion::startsWith)) { throw new CompilationException("JDK version prior to 11 are not supported to run the application"); } + final String configSourceVersion = Play.configuration.getProperty("java.source", JAVA_SOURCE_DEFAULT_VERSION); final String jdtVersion = compatibleJavaVersions.get(configSourceVersion); if (jdtVersion == null) { throw new CompilationException(String.format("Incompatible Java version specified (%s). Compatible versions are: %s", - configSourceVersion, compatibleJavaVersions.keySet())); + configSourceVersion, compatibleJavaVersions.keySet())); } - this.settings.put(CompilerOptions.OPTION_Source, jdtVersion); - this.settings.put(CompilerOptions.OPTION_TargetPlatform, jdtVersion); - this.settings.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); - this.settings.put(CompilerOptions.OPTION_Compliance, jdtVersion); - this.settings.put(CompilerOptions.OPTION_MethodParametersAttribute, CompilerOptions.GENERATE); + this.applicationClasses = applicationClasses; + this.settings = Map.ofEntries( + Map.entry(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE), + Map.entry(CompilerOptions.OPTION_MethodParametersAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_Encoding, "UTF-8"), + Map.entry(CompilerOptions.OPTION_Source, jdtVersion), + Map.entry(CompilerOptions.OPTION_TargetPlatform, jdtVersion), + Map.entry(CompilerOptions.OPTION_Compliance, jdtVersion) + ); } /** diff --git a/framework/src/play/classloading/enhancers/ContinuationEnhancer.java b/framework/src/play/classloading/enhancers/ContinuationEnhancer.java index 0340b5faaa..456f28704e 100644 --- a/framework/src/play/classloading/enhancers/ContinuationEnhancer.java +++ b/framework/src/play/classloading/enhancers/ContinuationEnhancer.java @@ -15,16 +15,14 @@ public class ContinuationEnhancer extends Enhancer { - static final List continuationMethods = new ArrayList<>(); - - static { - continuationMethods.add("play.mvc.Controller.await(java.lang.String)"); - continuationMethods.add("play.mvc.Controller.await(int)"); - continuationMethods.add("play.mvc.Controller.await(java.util.concurrent.Future)"); - continuationMethods.add("play.mvc.WebSocketController.await(java.lang.String)"); - continuationMethods.add("play.mvc.WebSocketController.await(int)"); - continuationMethods.add("play.mvc.WebSocketController.await(java.util.concurrent.Future)"); - } + private static final List continuationMethods = List.of( + "play.mvc.Controller.await(java.lang.String)", + "play.mvc.Controller.await(int)", + "play.mvc.Controller.await(java.util.concurrent.Future)", + "play.mvc.WebSocketController.await(java.lang.String)", + "play.mvc.WebSocketController.await(int)", + "play.mvc.WebSocketController.await(java.util.concurrent.Future)" + ); public static boolean isEnhanced(String appClassName) { ApplicationClass appClass = Play.classes.getApplicationClass( appClassName); diff --git a/framework/src/play/classloading/enhancers/Enhancer.java b/framework/src/play/classloading/enhancers/Enhancer.java index 5203f07d2d..04743fb644 100644 --- a/framework/src/play/classloading/enhancers/Enhancer.java +++ b/framework/src/play/classloading/enhancers/Enhancer.java @@ -29,7 +29,7 @@ */ public abstract class Enhancer { - protected ClassPool classPool; + protected final ClassPool classPool; public Enhancer() { this.classPool = newClassPool(); diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java index fc41da7ab1..17a26e408e 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java @@ -181,9 +181,7 @@ public static void checkEmpty() { } public static void clear() { - if (localVariables.get() != null) { - localVariables.set(null); - } + localVariables.remove(); } public static void enter() { @@ -280,43 +278,41 @@ public static void setLocalVariablesStateAfterAwait(Stack> s } } - static final Map storeByCode = new HashMap<>(); - /* * Useful instructions */ - static { - storeByCode.put(CodeIterator.ASTORE_0, 0); - storeByCode.put(CodeIterator.ASTORE_1, 1); - storeByCode.put(CodeIterator.ASTORE_2, 2); - storeByCode.put(CodeIterator.ASTORE_3, 3); - storeByCode.put(CodeIterator.ASTORE, -2); - - storeByCode.put(CodeIterator.ISTORE_0, 0); - storeByCode.put(CodeIterator.ISTORE_1, 1); - storeByCode.put(CodeIterator.ISTORE_2, 2); - storeByCode.put(CodeIterator.ISTORE_3, 3); - storeByCode.put(CodeIterator.ISTORE, -2); - storeByCode.put(CodeIterator.IINC, -2); - - storeByCode.put(CodeIterator.LSTORE_0, 0); - storeByCode.put(CodeIterator.LSTORE_1, 1); - storeByCode.put(CodeIterator.LSTORE_2, 2); - storeByCode.put(CodeIterator.LSTORE_3, 3); - storeByCode.put(CodeIterator.LSTORE, -2); - - storeByCode.put(CodeIterator.FSTORE_0, 0); - storeByCode.put(CodeIterator.FSTORE_1, 1); - storeByCode.put(CodeIterator.FSTORE_2, 2); - storeByCode.put(CodeIterator.FSTORE_3, 3); - storeByCode.put(CodeIterator.FSTORE, -2); - - storeByCode.put(CodeIterator.DSTORE_0, 0); - storeByCode.put(CodeIterator.DSTORE_1, 1); - storeByCode.put(CodeIterator.DSTORE_2, 2); - storeByCode.put(CodeIterator.DSTORE_3, 3); - storeByCode.put(CodeIterator.DSTORE, -2); - } + static final Map storeByCode = Map.ofEntries( + Map.entry(CodeIterator.ASTORE_0, 0), + Map.entry(CodeIterator.ASTORE_1, 1), + Map.entry(CodeIterator.ASTORE_2, 2), + Map.entry(CodeIterator.ASTORE_3, 3), + Map.entry(CodeIterator.ASTORE, -2), + + Map.entry(CodeIterator.ISTORE_0, 0), + Map.entry(CodeIterator.ISTORE_1, 1), + Map.entry(CodeIterator.ISTORE_2, 2), + Map.entry(CodeIterator.ISTORE_3, 3), + Map.entry(CodeIterator.ISTORE, -2), + Map.entry(CodeIterator.IINC, -2), + + Map.entry(CodeIterator.LSTORE_0, 0), + Map.entry(CodeIterator.LSTORE_1, 1), + Map.entry(CodeIterator.LSTORE_2, 2), + Map.entry(CodeIterator.LSTORE_3, 3), + Map.entry(CodeIterator.LSTORE, -2), + + Map.entry(CodeIterator.FSTORE_0, 0), + Map.entry(CodeIterator.FSTORE_1, 1), + Map.entry(CodeIterator.FSTORE_2, 2), + Map.entry(CodeIterator.FSTORE_3, 3), + Map.entry(CodeIterator.FSTORE, -2), + + Map.entry(CodeIterator.DSTORE_0, 0), + Map.entry(CodeIterator.DSTORE_1, 1), + Map.entry(CodeIterator.DSTORE_2, 2), + Map.entry(CodeIterator.DSTORE_3, 3), + Map.entry(CodeIterator.DSTORE, -2) + ); /** * Debug utility. Display a byte code op as plain text. diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java index 6fd8929bec..df718a8cf3 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java @@ -56,7 +56,7 @@ public void enhanceThisClass(ApplicationClass applicationClass) throws Exception parameterNames.add(new T2<>(localVariableAttribute.startPc(i) + localVariableAttribute.index(i), localVariableAttribute.variableName(i))); } } - Collections.sort(parameterNames, Comparator.comparing(o -> o._1)); + parameterNames.sort(Comparator.comparing(o -> o._1)); } List names = new ArrayList<>(); for (int i = 0; i < method.getParameterTypes().length + (Modifier.isStatic(method.getModifiers()) ? 0 : 1); i++) { diff --git a/framework/src/play/classloading/enhancers/MailerEnhancer.java b/framework/src/play/classloading/enhancers/MailerEnhancer.java index 49a468cf9e..92d0fe5d9d 100644 --- a/framework/src/play/classloading/enhancers/MailerEnhancer.java +++ b/framework/src/play/classloading/enhancers/MailerEnhancer.java @@ -30,7 +30,7 @@ public void enhanceThisClass(ApplicationClass applicationClass) throws Exception if (Modifier.isPublic(ctMethod.getModifiers()) && Modifier.isStatic(ctMethod.getModifiers())) { try { ctMethod.insertBefore("if(infos.get() != null) {play.Logger.warn(\"You call " + ctMethod.getLongName() + " from \" + ((java.util.Map)infos.get()).get(\"method\") + \". It's forbidden in a Mailer. It will probably fail...\", new Object[0]);}; infos.set(new java.util.HashMap());((java.util.Map)infos.get()).put(\"method\", \"" + ctMethod.getLongName() + "\");"); - ctMethod.insertAfter("infos.set(null);", true); + ctMethod.insertAfter("infos.remove();", true); } catch (Exception e) { Logger.error(e, "Error in MailerEnhancer"); throw new UnexpectedException("Error in MailerEnhancer", e); diff --git a/framework/src/play/classloading/enhancers/PropertiesEnhancer.java b/framework/src/play/classloading/enhancers/PropertiesEnhancer.java index 61dd4ce85e..137c95d09d 100644 --- a/framework/src/play/classloading/enhancers/PropertiesEnhancer.java +++ b/framework/src/play/classloading/enhancers/PropertiesEnhancer.java @@ -29,8 +29,8 @@ */ public class PropertiesEnhancer extends Enhancer { - private boolean enabled = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.enabled", "true")); - private boolean generateAccessors = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.generateAccessors", "true")); + private final boolean enabled = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.enabled", "true")); + private final boolean generateAccessors = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.generateAccessors", "true")); private static final boolean constructorsOnly = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.constructorsOnly", "false")); diff --git a/framework/src/play/data/MemoryUpload.java b/framework/src/play/data/MemoryUpload.java index be13600c9b..3489c1d4b2 100644 --- a/framework/src/play/data/MemoryUpload.java +++ b/framework/src/play/data/MemoryUpload.java @@ -7,7 +7,7 @@ public class MemoryUpload implements Upload { - FileItem fileItem; + final FileItem fileItem; public MemoryUpload(FileItem fileItem) { this.fileItem = fileItem; diff --git a/framework/src/play/data/binding/AnnotationHelper.java b/framework/src/play/data/binding/AnnotationHelper.java index 8b5153ce3f..16ae1bb031 100644 --- a/framework/src/play/data/binding/AnnotationHelper.java +++ b/framework/src/play/data/binding/AnnotationHelper.java @@ -88,8 +88,8 @@ public static Tuple getLocale(String[] langs) { */ private static class Tuple { - public int index = -1; - public Locale locale; + public final int index; + public final Locale locale; public Tuple(int index, Locale locale) { this.locale = locale; diff --git a/framework/src/play/data/binding/BeanWrapper.java b/framework/src/play/data/binding/BeanWrapper.java index 1a1d854749..1b16333869 100644 --- a/framework/src/play/data/binding/BeanWrapper.java +++ b/framework/src/play/data/binding/BeanWrapper.java @@ -16,12 +16,12 @@ public class BeanWrapper { static final int notwritableField = Modifier.FINAL | Modifier.NATIVE | Modifier.STATIC; static final int notaccessibleMethod = Modifier.NATIVE | Modifier.STATIC; - private Class beanClass; - - /** + /** * a cache for our properties and setters */ - private Map wrappers = new HashMap<>(); + private final Map wrappers = new HashMap<>(); + + private final Class beanClass; public BeanWrapper(Class forClass) { if (Logger.isTraceEnabled()) { @@ -143,12 +143,12 @@ private void registerSetters(Class clazz, boolean isScala) { public static class Property { - private Annotation[] annotations; + private final Annotation[] annotations; + private final Class type; + private final Type genericType; + private final String name; private Method setter; private Field field; - private Class type; - private Type genericType; - private String name; private String[] profiles; Property(String propertyName, Method setterMethod) { diff --git a/framework/src/play/data/binding/Binder.java b/framework/src/play/data/binding/Binder.java index 96266587cf..e2a02b6143 100644 --- a/framework/src/play/data/binding/Binder.java +++ b/framework/src/play/data/binding/Binder.java @@ -81,7 +81,7 @@ public static void unregister(Class clazz) { supportedTypes.remove(clazz); } - static Map, BeanWrapper> beanwrappers = new HashMap<>(); + static final Map, BeanWrapper> beanwrappers = new HashMap<>(); static BeanWrapper getBeanWrapper(Class clazz) { return beanwrappers.computeIfAbsent(clazz, BeanWrapper::new); @@ -90,7 +90,7 @@ static BeanWrapper getBeanWrapper(Class clazz) { public static class MethodAndParamInfo { public final Object objectInstance; public final Method method; - public int parameterIndex; + public final int parameterIndex; public MethodAndParamInfo(Object objectInstance, Method method, int parameterIndex) { this.objectInstance = objectInstance; diff --git a/framework/src/play/data/binding/CachedBoundActionMethodArgs.java b/framework/src/play/data/binding/CachedBoundActionMethodArgs.java index db8e4caeaa..0acd1000af 100644 --- a/framework/src/play/data/binding/CachedBoundActionMethodArgs.java +++ b/framework/src/play/data/binding/CachedBoundActionMethodArgs.java @@ -11,7 +11,7 @@ public class CachedBoundActionMethodArgs { private static final ThreadLocal current = new ThreadLocal<>(); - private Map preBoundActionMethodArgs = new HashMap<>(1); + private final Map preBoundActionMethodArgs = new HashMap<>(1); public static void init() { current.set( new CachedBoundActionMethodArgs()); diff --git a/framework/src/play/data/binding/types/DateBinder.java b/framework/src/play/data/binding/types/DateBinder.java index 2116a05a14..24d4509249 100644 --- a/framework/src/play/data/binding/types/DateBinder.java +++ b/framework/src/play/data/binding/types/DateBinder.java @@ -18,7 +18,7 @@ public class DateBinder implements TypeBinder { @Override public Date bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } diff --git a/framework/src/play/data/binding/types/DateTimeBinder.java b/framework/src/play/data/binding/types/DateTimeBinder.java index 3fb6d1ecea..0421745adf 100644 --- a/framework/src/play/data/binding/types/DateTimeBinder.java +++ b/framework/src/play/data/binding/types/DateTimeBinder.java @@ -12,11 +12,11 @@ */ public class DateTimeBinder implements TypeBinder { - private static DateBinder dateBinder = new DateBinder(); + private static final DateBinder dateBinder = new DateBinder(); @Override public DateTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } return new DateTime(dateBinder.bind(name, annotations, value, actualClass, genericType)); diff --git a/framework/src/play/data/binding/types/FileArrayBinder.java b/framework/src/play/data/binding/types/FileArrayBinder.java index 8b31e37a3b..b85a8e4a2d 100644 --- a/framework/src/play/data/binding/types/FileArrayBinder.java +++ b/framework/src/play/data/binding/types/FileArrayBinder.java @@ -19,7 +19,7 @@ public class FileArrayBinder implements TypeBinder { @SuppressWarnings("unchecked") @Override public File[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/FileBinder.java b/framework/src/play/data/binding/types/FileBinder.java index f3c198220a..3cad419f4b 100644 --- a/framework/src/play/data/binding/types/FileBinder.java +++ b/framework/src/play/data/binding/types/FileBinder.java @@ -17,7 +17,7 @@ public class FileBinder implements TypeBinder { @Override @SuppressWarnings("unchecked") public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/LocalDateBinder.java b/framework/src/play/data/binding/types/LocalDateBinder.java index b620a4bb4a..b7a40e28bb 100644 --- a/framework/src/play/data/binding/types/LocalDateBinder.java +++ b/framework/src/play/data/binding/types/LocalDateBinder.java @@ -13,6 +13,6 @@ public class LocalDateBinder implements TypeBinder { @Override public LocalDate bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalDate.parse(value) : null; + return value != null && !value.isBlank() ? LocalDate.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/LocalDateTimeBinder.java b/framework/src/play/data/binding/types/LocalDateTimeBinder.java index 9017d8a27a..d1704ce6ca 100644 --- a/framework/src/play/data/binding/types/LocalDateTimeBinder.java +++ b/framework/src/play/data/binding/types/LocalDateTimeBinder.java @@ -10,6 +10,6 @@ public class LocalDateTimeBinder implements TypeBinder { @Override public LocalDateTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalDateTime.parse(value) : null; + return value != null && !value.isBlank() ? LocalDateTime.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/LocalTimeBinder.java b/framework/src/play/data/binding/types/LocalTimeBinder.java index d3caab52f9..86cb938ac6 100644 --- a/framework/src/play/data/binding/types/LocalTimeBinder.java +++ b/framework/src/play/data/binding/types/LocalTimeBinder.java @@ -13,6 +13,6 @@ public class LocalTimeBinder implements TypeBinder { @Override public LocalTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalTime.parse(value) : null; + return value != null && !value.isBlank() ? LocalTime.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/UploadArrayBinder.java b/framework/src/play/data/binding/types/UploadArrayBinder.java index 7a87bc663a..f57bb9f5ed 100644 --- a/framework/src/play/data/binding/types/UploadArrayBinder.java +++ b/framework/src/play/data/binding/types/UploadArrayBinder.java @@ -19,7 +19,7 @@ public class UploadArrayBinder implements TypeBinder { @SuppressWarnings("unchecked") @Override public Upload[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/UploadBinder.java b/framework/src/play/data/binding/types/UploadBinder.java index fcaee068f5..2fd855cdaa 100644 --- a/framework/src/play/data/binding/types/UploadBinder.java +++ b/framework/src/play/data/binding/types/UploadBinder.java @@ -18,7 +18,7 @@ public class UploadBinder implements TypeBinder { @Override @SuppressWarnings("unchecked") public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } try { diff --git a/framework/src/play/data/parsing/ApacheMultipartParser.java b/framework/src/play/data/parsing/ApacheMultipartParser.java index 90d2c4cdea..72e2bb49f7 100644 --- a/framework/src/play/data/parsing/ApacheMultipartParser.java +++ b/framework/src/play/data/parsing/ApacheMultipartParser.java @@ -99,11 +99,7 @@ private static void putMapEntry(Map map, String name, String v */ public static class AutoFileItem implements FileItem { - private static FileCleaningTracker fileTracker; - - static { - fileTracker = new FileCleaningTracker(); - } + private static final FileCleaningTracker fileTracker = new FileCleaningTracker(); // ----------------------------------------------------- Manifest constants /** @@ -112,10 +108,6 @@ public static class AutoFileItem implements FileItem { * HTTP. */ public static final String DEFAULT_CHARSET = "ISO-8859-1"; - /** - * Size of buffer to use when writing an item to disk. - */ - private static final int WRITE_BUFFER_SIZE = 2048; // ----------------------------------------------------------- Data members /** @@ -604,12 +596,12 @@ public Map parse(InputStream body) { * The maximum size permitted for the complete request, as opposed to * {@link #maxFileSize}. A value of -1 indicates no maximum. */ - private long maxRequestSize = Integer.parseInt(Play.configuration.getProperty("upload.maxRequestSize", "-1")); + private final long maxRequestSize = Integer.parseInt(Play.configuration.getProperty("upload.maxRequestSize", "-1")); /** * The maximum size permitted for a single uploaded file, as opposed to * {@link #maxRequestSize}. A value of -1 indicates no maximum. */ - private long maxFileSize = Integer.parseInt(Play.configuration.getProperty("upload.maxFileSize", "-1")); + private final long maxFileSize = Integer.parseInt(Play.configuration.getProperty("upload.maxFileSize", "-1")); // ------------------------------------------------------ Protected methods diff --git a/framework/src/play/data/parsing/MultipartStream.java b/framework/src/play/data/parsing/MultipartStream.java index 796449e9da..e4991d4909 100644 --- a/framework/src/play/data/parsing/MultipartStream.java +++ b/framework/src/play/data/parsing/MultipartStream.java @@ -195,11 +195,11 @@ private void notifyListener() { * The amount of data, in bytes, that must be kept in the buffer in order * to detect delimiters reliably. */ - private int keepRegion; + private final int keepRegion; /** * The byte sequence that partitions the stream. */ - private byte[] boundary; + private final byte[] boundary; /** * The length of the buffer used for processing the request. */ diff --git a/framework/src/play/data/parsing/TempFilePlugin.java b/framework/src/play/data/parsing/TempFilePlugin.java index d2d8e1c505..fc7d07b8e6 100644 --- a/framework/src/play/data/parsing/TempFilePlugin.java +++ b/framework/src/play/data/parsing/TempFilePlugin.java @@ -15,8 +15,7 @@ */ public class TempFilePlugin extends PlayPlugin { - private static DecimalFormat format = new DecimalFormat("##########"); - + private static final DecimalFormat format = new DecimalFormat("##########"); static { format.setMinimumIntegerDigits(10); diff --git a/framework/src/play/data/validation/CheckWithCheck.java b/framework/src/play/data/validation/CheckWithCheck.java index b81e131dfa..e44c47335f 100644 --- a/framework/src/play/data/validation/CheckWithCheck.java +++ b/framework/src/play/data/validation/CheckWithCheck.java @@ -14,7 +14,7 @@ public class CheckWithCheck extends AbstractAnnotationCheck { static final String mes = "validation.invalid"; - Map variables = new TreeMap<>(); + final Map variables = new TreeMap<>(); Check check; @Override diff --git a/framework/src/play/data/validation/EmailCheck.java b/framework/src/play/data/validation/EmailCheck.java index 7bc20a7053..ca91c7f642 100644 --- a/framework/src/play/data/validation/EmailCheck.java +++ b/framework/src/play/data/validation/EmailCheck.java @@ -9,7 +9,7 @@ public class EmailCheck extends AbstractAnnotationCheck { static final String mes = "validation.email"; - static Pattern emailPattern = Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?"); + static final Pattern emailPattern = Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?"); @Override public void configure(Email email) { diff --git a/framework/src/play/data/validation/PhoneCheck.java b/framework/src/play/data/validation/PhoneCheck.java index dd2893468a..3aade43327 100644 --- a/framework/src/play/data/validation/PhoneCheck.java +++ b/framework/src/play/data/validation/PhoneCheck.java @@ -11,7 +11,7 @@ public class PhoneCheck extends AbstractAnnotationCheck { static final String mes = "validation.phone"; - static Pattern phonePattern = Pattern.compile("^([\\+][0-9]{1,3}([ \\.\\-]))?([\\(]{1}[0-9]{1,6}[\\)])?([0-9 \\.\\-/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$"); + static final Pattern phonePattern = Pattern.compile("^([\\+][0-9]{1,3}([ \\.\\-]))?([\\(]{1}[0-9]{1,6}[\\)])?([0-9 \\.\\-/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$"); @Override public void configure(Phone phone) { diff --git a/framework/src/play/data/validation/URLCheck.java b/framework/src/play/data/validation/URLCheck.java index f288c1e801..f109a5db1c 100644 --- a/framework/src/play/data/validation/URLCheck.java +++ b/framework/src/play/data/validation/URLCheck.java @@ -9,7 +9,7 @@ public class URLCheck extends AbstractAnnotationCheck { static final String mes = "validation.url"; - static Pattern urlPattern = Pattern.compile("^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-z" + + static final Pattern urlPattern = Pattern.compile("^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-z" + "A-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~\\!])*$"); @Override diff --git a/framework/src/play/data/validation/Validation.java b/framework/src/play/data/validation/Validation.java index 7042acf39c..74e651047b 100644 --- a/framework/src/play/data/validation/Validation.java +++ b/framework/src/play/data/validation/Validation.java @@ -20,7 +20,7 @@ public class Validation { public static final ThreadLocal current = new ThreadLocal<>(); - List errors = new ArrayList<>(); + final List errors = new ArrayList<>(); boolean keep = false; protected Validation() { @@ -97,13 +97,7 @@ public static void insertError(int index, String field, String message, String.. public static void removeErrors(String field, String message) { Validation validation = current.get(); if (validation != null) { - Iterator it = validation.errors.iterator(); - while (it.hasNext()) { - Error error = it.next(); - if (error.key != null && error.key.equals(field) && error.message.equals(message)) { - it.remove(); - } - } + validation.errors.removeIf(error -> error.key != null && error.key.equals(field) && error.message.equals(message)); } } @@ -114,13 +108,7 @@ public static void removeErrors(String field, String message) { public static void removeErrors(String field) { Validation validation = current.get(); if (validation != null) { - Iterator it = validation.errors.iterator(); - while (it.hasNext()) { - Error error = it.next(); - if (error.key != null && error.key.equals(field)) { - it.remove(); - } - } + validation.errors.removeIf(error -> error.key != null && error.key.equals(field)); } } @@ -274,8 +262,8 @@ static void searchValidator(Class clazz, String name, Map params = new HashMap<>(); + public final Annotation annotation; + public final Map params = new HashMap<>(); public Validator(Annotation annotation) { this.annotation = annotation; diff --git a/framework/src/play/data/validation/ValidationPlugin.java b/framework/src/play/data/validation/ValidationPlugin.java index 165b51696f..d4496de544 100644 --- a/framework/src/play/data/validation/ValidationPlugin.java +++ b/framework/src/play/data/validation/ValidationPlugin.java @@ -141,7 +141,7 @@ public List validateAction(Method actionMethod) throws Exce return validationCycle.violations; } } - static Pattern errorsParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); + static final Pattern errorsParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); static Validation restore() { try { diff --git a/framework/src/play/db/Configuration.java b/framework/src/play/db/Configuration.java index ae14a04639..5adc079fce 100644 --- a/framework/src/play/db/Configuration.java +++ b/framework/src/play/db/Configuration.java @@ -21,7 +21,7 @@ public class Configuration { /** compiled regex as a pattern for reuse to filter all db related settings. */ final java.util.regex.Pattern compiledRegexDbRelatedSettings = java.util.regex.Pattern.compile(regexDbRelatedSettings +".*"); - public String configName; + public final String configName; public boolean isDefault() { return DB.DEFAULT.equals(this.configName); diff --git a/framework/src/play/db/DB.java b/framework/src/play/db/DB.java index c8bd3c05f1..8c2de5eaee 100644 --- a/framework/src/play/db/DB.java +++ b/framework/src/play/db/DB.java @@ -39,12 +39,12 @@ public static class ExtendedDatasource { /** * Connection to the physical data source */ - private DataSource datasource; + private final DataSource datasource; /** * The method used to destroy the data source */ - private String destroyMethod; + private final String destroyMethod; public ExtendedDatasource(DataSource ds, String destroyMethod) { this.datasource = ds; @@ -85,10 +85,8 @@ public DataSource getDataSource() { static final ThreadLocal> localConnection = new ThreadLocal<>(); public static DataSource getDataSource(String name) { - if (datasources.get(name) != null) { - return datasources.get(name).getDataSource(); - } - return null; + ExtendedDatasource datasource = datasources.get(name); + return datasource == null ? null : datasource.getDataSource(); } public static DataSource getDataSource() { @@ -109,8 +107,7 @@ public static Connection getConnection(String name, boolean autocommit) { private static Connection getLocalConnection(String name) { Map map = localConnection.get(); if (map != null) { - Connection connection = map.get(name); - return connection; + return map.get(name); } return null; } @@ -119,9 +116,9 @@ private static void registerLocalConnection(String name, Connection connection) Map map = localConnection.get(); if (map == null) { map = new HashMap<>(); + localConnection.set(map); } map.put(name, connection); - localConnection.set(map); } /** @@ -145,7 +142,7 @@ public static void close() { } /** - * Close an given open connections for the current thread + * Close a given open connections for the current thread * * @param name * Name of the DB @@ -153,10 +150,8 @@ public static void close() { public static void close(String name) { Map map = localConnection.get(); if (map != null) { - Connection connection = map.get(name); + Connection connection = map.remove(name); if (connection != null) { - map.remove(name); - localConnection.set(map); try { connection.close(); } catch (Exception e) { @@ -176,7 +171,7 @@ public static void close(String name) { public static Connection getConnection(String name) { try { if (JPA.isEnabled()) { - return ((SessionImpl) ((org.hibernate.Session) JPA.em(name)).getSession()).connection(); + return JPA.em(name).unwrap(SessionImpl.class).getSession().connection(); } Connection localConnection = getLocalConnection(name); @@ -185,14 +180,13 @@ public static Connection getConnection(String name) { } // We have no connection - Connection connection = getDataSource(name).getConnection(); + DataSource ds = getDataSource(name); + if (ds == null) { + throw new DatabaseException("No database found. Check the configuration of your application."); + } + Connection connection = ds.getConnection(); registerLocalConnection(name, connection); return connection; - } catch (NullPointerException e) { - if (getDataSource(name) == null) { - throw new DatabaseException("No database found. Check the configuration of your application.", e); - } - throw e; } catch (Exception e) { // Exception throw new DatabaseException(e.getMessage()); @@ -313,13 +307,11 @@ public static void destroy(String name) { try { ExtendedDatasource extDatasource = datasources.get(name); if (extDatasource != null && extDatasource.getDestroyMethod() != null) { - Method close = extDatasource.datasource.getClass().getMethod(extDatasource.getDestroyMethod(), new Class[] {}); - if (close != null) { - close.invoke(extDatasource.getDataSource(), new Object[] {}); - datasources.remove(name); - DB.datasource = null; - Logger.trace("Datasource destroyed"); - } + Method close = extDatasource.datasource.getClass().getMethod(extDatasource.getDestroyMethod()); + close.invoke(extDatasource.getDataSource()); + datasources.remove(name); + DB.datasource = null; + Logger.trace("Datasource destroyed"); } } catch (Throwable t) { Logger.error("Couldn't destroy the datasource", t); diff --git a/framework/src/play/db/DBPlugin.java b/framework/src/play/db/DBPlugin.java index ba4b24b9a3..31a73df31c 100644 --- a/framework/src/play/db/DBPlugin.java +++ b/framework/src/play/db/DBPlugin.java @@ -48,9 +48,8 @@ public void onApplicationStart() { } Set dbNames = Configuration.getDbNames(); - Iterator it = dbNames.iterator(); - while (it.hasNext()) { - dbName = it.next(); + for (String name : dbNames) { + dbName = name; Configuration dbConfig = new Configuration(dbName); boolean isJndiDatasource = false; @@ -251,7 +250,7 @@ private boolean changed() { */ public static class ProxyDriver implements Driver { - private Driver driver; + private final Driver driver; ProxyDriver(Driver d) { this.driver = d; @@ -287,16 +286,9 @@ public boolean jdbcCompliant() { return this.driver.jdbcCompliant(); } - // Method not annotated with @Override since getParentLogger() is a new method - // in the CommonDataSource interface starting with JDK7 and this annotation - // would cause compilation errors with JDK6. @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { - try { - return (java.util.logging.Logger) Driver.class.getDeclaredMethod("getParentLogger").invoke(this.driver); - } catch (Throwable e) { - return null; - } + return this.driver.getParentLogger(); } } } diff --git a/framework/src/play/db/Evolutions.java b/framework/src/play/db/Evolutions.java index d4f7d5d7b4..ae36fa32af 100644 --- a/framework/src/play/db/Evolutions.java +++ b/framework/src/play/db/Evolutions.java @@ -39,10 +39,11 @@ */ public class Evolutions extends PlayPlugin { - private static String EVOLUTIONS_TABLE_NAME = "play_evolutions"; - protected static File evolutionsDirectory = Play.getFile("db/evolutions"); + private static final String EVOLUTIONS_TABLE_NAME = "play_evolutions"; + private static final Map modulesWithEvolutions = new LinkedHashMap<>(); + + protected static final File evolutionsDirectory = Play.getFile("db/evolutions"); - private static Map modulesWithEvolutions = new LinkedHashMap<>(); public static void main(String[] args) throws SQLException { /** Start the DB plugin **/ diff --git a/framework/src/play/db/c3p0/PlayConnectionCustomizer.java b/framework/src/play/db/c3p0/PlayConnectionCustomizer.java index 01c80700ed..b6e53cbc4b 100644 --- a/framework/src/play/db/c3p0/PlayConnectionCustomizer.java +++ b/framework/src/play/db/c3p0/PlayConnectionCustomizer.java @@ -7,21 +7,17 @@ import java.sql.Connection; import java.sql.SQLException; -import java.util.HashMap; import java.util.Map; public class PlayConnectionCustomizer implements ConnectionCustomizer { - public static Map isolationLevels; - - static { - isolationLevels = new HashMap<>(); - isolationLevels.put("NONE", Connection.TRANSACTION_NONE); - isolationLevels.put("READ_UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED); - isolationLevels.put("READ_COMMITTED", Connection.TRANSACTION_READ_COMMITTED); - isolationLevels.put("REPEATABLE_READ", Connection.TRANSACTION_REPEATABLE_READ); - isolationLevels.put("SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE); - } + public static final Map isolationLevels = Map.of( + "NONE", Connection.TRANSACTION_NONE, + "READ_UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED, + "READ_COMMITTED", Connection.TRANSACTION_READ_COMMITTED, + "REPEATABLE_READ", Connection.TRANSACTION_REPEATABLE_READ, + "SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE + ); @Override public void onAcquire(Connection c, String parentDataSourceIdentityToken) { diff --git a/framework/src/play/db/evolutions/Evolution.java b/framework/src/play/db/evolutions/Evolution.java index c167c4ff10..3c4c6d348a 100644 --- a/framework/src/play/db/evolutions/Evolution.java +++ b/framework/src/play/db/evolutions/Evolution.java @@ -4,13 +4,13 @@ public class Evolution implements Comparable { - public int revision; - public String sql_up; - public String sql_down; - public String hash; - public boolean applyUp; + public final int revision; + public final String sql_up; + public final String sql_down; + public final String hash; + public final boolean applyUp; - public String moduleKey; + public final String moduleKey; public Evolution(String moduleKey, int revision, String sql_up, String sql_down, boolean applyUp) { this.moduleKey = moduleKey; diff --git a/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java b/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java index 9bc23dadf6..a2faea9308 100644 --- a/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java +++ b/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java @@ -7,11 +7,11 @@ public class InconsistentDatabase extends PlayException { /** * The name of the Database concern by the exception */ - private String dbName; - private String evolutionScript; - private String error; - private int revision; - private String moduleKey; + private final String dbName; + private final String evolutionScript; + private final String error; + private final int revision; + private final String moduleKey; public InconsistentDatabase(String dbName, String evolutionScript, String error, int revision, String moduleKey) { this.dbName = dbName; diff --git a/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java b/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java index a88dcf247a..a952f9115d 100644 --- a/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java +++ b/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java @@ -8,8 +8,8 @@ public class InvalidDatabaseRevision extends PlayException { /** * The name of the Database concern by the exception */ - private String dbName; - private String evolutionScript; + private final String dbName; + private final String evolutionScript; public InvalidDatabaseRevision(String dbName, String evolutionScript) { this.dbName = dbName; diff --git a/framework/src/play/db/helper/JdbcResultFactories.java b/framework/src/play/db/helper/JdbcResultFactories.java index 0dfa4d6dca..6f5cca525a 100644 --- a/framework/src/play/db/helper/JdbcResultFactories.java +++ b/framework/src/play/db/helper/JdbcResultFactories.java @@ -133,7 +133,7 @@ public void init(ResultSet result) throws SQLException { int count = meta.getColumnCount(); for (int i = 1; i <= count; i++) { String label = meta.getColumnLabel(i); - if (label.length()>0) fields.add(label); + if (!label.isEmpty()) fields.add(label); } } } diff --git a/framework/src/play/db/helper/SqlQuery.java b/framework/src/play/db/helper/SqlQuery.java index 97383ead8a..ce6adab219 100644 --- a/framework/src/play/db/helper/SqlQuery.java +++ b/framework/src/play/db/helper/SqlQuery.java @@ -5,10 +5,9 @@ public abstract class SqlQuery { - protected List params; + protected final List params = new ArrayList<>(); protected SqlQuery() { - params = new ArrayList<>(); } public SqlQuery param(Object obj) { params.add(obj); return this; } diff --git a/framework/src/play/db/jpa/Blob.java b/framework/src/play/db/jpa/Blob.java index a9ad9ab8bf..74bd42505f 100644 --- a/framework/src/play/db/jpa/Blob.java +++ b/framework/src/play/db/jpa/Blob.java @@ -8,6 +8,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import java.util.Objects; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -95,17 +96,13 @@ public Class returnedClass() { return Blob.class; } - private static boolean equal(Object a, Object b) { - return a == b || (a != null && a.equals(b)); - } - @Override public boolean equals(Object o, Object o1) throws HibernateException { if(o instanceof Blob && o1 instanceof Blob) { - return equal(((Blob)o).UUID, ((Blob)o1).UUID) && - equal(((Blob)o).type, ((Blob)o1).type); + return Objects.equals(((Blob) o).UUID, ((Blob) o1).UUID) && + Objects.equals(((Blob)o).type, ((Blob)o1).type); } - return equal(o, o1); + return Objects.equals(o, o1); } @Override diff --git a/framework/src/play/db/jpa/JPA.java b/framework/src/play/db/jpa/JPA.java index a733ece071..d925c9ed8f 100644 --- a/framework/src/play/db/jpa/JPA.java +++ b/framework/src/play/db/jpa/JPA.java @@ -23,9 +23,9 @@ */ public class JPA { - protected static Map emfs = new ConcurrentHashMap<>(); + protected static final Map emfs = new ConcurrentHashMap<>(); public static final ThreadLocal> currentEntityManager = ThreadLocal.withInitial(ConcurrentHashMap::new); - public static String DEFAULT = "default"; + public static final String DEFAULT = "default"; public static class JPAContext { public String dbName = JPA.DEFAULT; diff --git a/framework/src/play/db/jpa/JPAModelLoader.java b/framework/src/play/db/jpa/JPAModelLoader.java index 64d60803d9..4040854404 100644 --- a/framework/src/play/db/jpa/JPAModelLoader.java +++ b/framework/src/play/db/jpa/JPAModelLoader.java @@ -36,8 +36,8 @@ public class JPAModelLoader implements Model.Factory { - private String dbName; - private Class clazz; + private final String dbName; + private final Class clazz; private Map properties; public JPAModelLoader(Class clazz) { diff --git a/framework/src/play/db/jpa/JPAPlugin.java b/framework/src/play/db/jpa/JPAPlugin.java index 0ceec845a1..7a476ee7b6 100644 --- a/framework/src/play/db/jpa/JPAPlugin.java +++ b/framework/src/play/db/jpa/JPAPlugin.java @@ -198,7 +198,7 @@ protected EntityManagerFactory newEntityManagerFactory(String dbName, Configurat protected PersistenceUnitInfoImpl persistenceUnitInfo(String dbName, Configuration dbConfig) { final List managedClasses = entityClasses(dbName); final Properties properties = properties(dbName, dbConfig); - properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES,managedClasses); + properties.put(org.hibernate.cfg.AvailableSettings.LOADED_CLASSES,managedClasses); return new PersistenceUnitInfoImpl(dbName, managedClasses, mappingFiles(dbConfig), properties); } @@ -309,7 +309,7 @@ public void afterInvocation() { } } - public class TransactionalFilter extends Filter { + public static class TransactionalFilter extends Filter { public TransactionalFilter(String name) { super(name); } @@ -319,7 +319,7 @@ public Object withinFilter(play.libs.F.Function0 fct) throws Throwable { } } - private TransactionalFilter txFilter = new TransactionalFilter("TransactionalFilter"); + private final TransactionalFilter txFilter = new TransactionalFilter("TransactionalFilter"); @Override public Filter getFilter() { diff --git a/framework/src/play/deps/DependenciesManager.java b/framework/src/play/deps/DependenciesManager.java index 7427a31403..e5c823f68a 100644 --- a/framework/src/play/deps/DependenciesManager.java +++ b/framework/src/play/deps/DependenciesManager.java @@ -76,9 +76,9 @@ public static void main(String[] args) throws Exception { } } - File application; - File framework; - File userHome; + final File application; + final File framework; + final File userHome; HumanReadyLogger logger; final FileFilter dirsToTrim = new FileFilter() { diff --git a/framework/src/play/deps/HumanReadyLogger.java b/framework/src/play/deps/HumanReadyLogger.java index b91c7e9161..088c32988d 100644 --- a/framework/src/play/deps/HumanReadyLogger.java +++ b/framework/src/play/deps/HumanReadyLogger.java @@ -13,18 +13,18 @@ public class HumanReadyLogger implements MessageLogger, TransferListener { - Set notFound = new HashSet<>(); - Set dynamics = new HashSet<>(); - Set evicteds = new HashSet<>(); - Pattern dep = Pattern.compile("found ([^#]+)#([^;]+);([^\\s]+) in (.*)"); - Pattern depNotFound = Pattern.compile("module not found: ([^#]+)#([^;]+);([^\\s]+)"); - Pattern dynamic = Pattern.compile("\\[(.*)\\] ([^#]+)#([^;]+);([^\\s]+)"); - Pattern evicted = Pattern.compile("([^#]+)#([^;]+);([^\\s]+) by \\[([^#]+)#([^;]+);([^\\s]+)\\].*"); + final Set notFound = new HashSet<>(); + final Set dynamics = new HashSet<>(); + final Set evicteds = new HashSet<>(); + final Pattern dep = Pattern.compile("found ([^#]+)#([^;]+);([^\\s]+) in (.*)"); + final Pattern depNotFound = Pattern.compile("module not found: ([^#]+)#([^;]+);([^\\s]+)"); + final Pattern dynamic = Pattern.compile("\\[(.*)\\] ([^#]+)#([^;]+);([^\\s]+)"); + final Pattern evicted = Pattern.compile("([^#]+)#([^;]+);([^\\s]+) by \\[([^#]+)#([^;]+);([^\\s]+)\\].*"); + final String[] progressBar = {". ", ".. ", "...", " "}; String downloading = null; long length = 0; int progress = 0; long lastTime = System.currentTimeMillis(); - String[] progressBar = new String[]{". ", ".. ", "...", " "}; public void niceLog(String msg, int level) { try { diff --git a/framework/src/play/deps/PlayConflictManager.java b/framework/src/play/deps/PlayConflictManager.java index b70fcbc8ff..61b1fd77a2 100644 --- a/framework/src/play/deps/PlayConflictManager.java +++ b/framework/src/play/deps/PlayConflictManager.java @@ -15,7 +15,7 @@ public class PlayConflictManager extends AbstractConflictManager { - public LatestConflictManager delegate = new LatestConflictManager(new LatestRevisionStrategy()); + public final LatestConflictManager delegate = new LatestConflictManager(new LatestRevisionStrategy()); @Override public Collection resolveConflicts(IvyNode in, Collection conflictsUntyped) { diff --git a/framework/src/play/deps/YamlParser.java b/framework/src/play/deps/YamlParser.java index 4031b08a0a..1a5e39b5e7 100644 --- a/framework/src/play/deps/YamlParser.java +++ b/framework/src/play/deps/YamlParser.java @@ -367,7 +367,7 @@ private static String filterModuleName(ModuleRevisionId rev) { } private static class ModuleFilter implements FilenameFilter { - private ModuleRevisionId moduleRevision; + private final ModuleRevisionId moduleRevision; public ModuleFilter(ModuleRevisionId moduleRevision) { this.moduleRevision = moduleRevision; diff --git a/framework/src/play/exceptions/ActionNotFoundException.java b/framework/src/play/exceptions/ActionNotFoundException.java index 353461a1b8..a358c65dbf 100644 --- a/framework/src/play/exceptions/ActionNotFoundException.java +++ b/framework/src/play/exceptions/ActionNotFoundException.java @@ -2,7 +2,7 @@ public class ActionNotFoundException extends PlayException { - private String action; + private final String action; public ActionNotFoundException(String action, Throwable cause) { super(String.format("Action %s not found", action.startsWith("controllers.") ? action.substring(12) : action), cause); diff --git a/framework/src/play/exceptions/CompilationException.java b/framework/src/play/exceptions/CompilationException.java index be74498742..d2fb98be41 100644 --- a/framework/src/play/exceptions/CompilationException.java +++ b/framework/src/play/exceptions/CompilationException.java @@ -9,7 +9,7 @@ */ public class CompilationException extends PlayException implements SourceAttachment { - private String problem; + private final String problem; private VirtualFile source; private Integer line; private Integer start; diff --git a/framework/src/play/exceptions/PlayException.java b/framework/src/play/exceptions/PlayException.java index 65bb7ab638..fe679e5efe 100644 --- a/framework/src/play/exceptions/PlayException.java +++ b/framework/src/play/exceptions/PlayException.java @@ -9,7 +9,7 @@ */ public abstract class PlayException extends RuntimeException { - private static AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis()); + private static final AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis()); private String id; public PlayException() { diff --git a/framework/src/play/exceptions/TemplateException.java b/framework/src/play/exceptions/TemplateException.java index 5c26db5285..7e0aafc7e9 100644 --- a/framework/src/play/exceptions/TemplateException.java +++ b/framework/src/play/exceptions/TemplateException.java @@ -9,8 +9,8 @@ */ public abstract class TemplateException extends PlayException implements SourceAttachment { - private Template template; - private Integer lineNumber; + private final Template template; + private final Integer lineNumber; public TemplateException(Template template, Integer lineNumber, String message) { super(message); diff --git a/framework/src/play/exceptions/TemplateNotFoundException.java b/framework/src/play/exceptions/TemplateNotFoundException.java index 629244044b..5fbaaf2ec0 100644 --- a/framework/src/play/exceptions/TemplateNotFoundException.java +++ b/framework/src/play/exceptions/TemplateNotFoundException.java @@ -8,7 +8,7 @@ public class TemplateNotFoundException extends PlayException implements SourceAttachment { - private String path; + private final String path; private String sourceFile; private List source; private Integer line; diff --git a/framework/src/play/exceptions/YAMLException.java b/framework/src/play/exceptions/YAMLException.java index 7179d8a98f..c294cfb6ff 100644 --- a/framework/src/play/exceptions/YAMLException.java +++ b/framework/src/play/exceptions/YAMLException.java @@ -7,8 +7,8 @@ public class YAMLException extends PlayException implements SourceAttachment { - ScannerException e; - VirtualFile yaml; + final ScannerException e; + final VirtualFile yaml; public YAMLException(ScannerException e, VirtualFile yaml) { super(e.getMessage() + " (in file " + yaml.relativePath() + " line " + (e.getProblemMark().getLine() + 1) + ", column " + (e.getProblemMark().getColumn() + 1) + ")", e); diff --git a/framework/src/play/i18n/Lang.java b/framework/src/play/i18n/Lang.java index 7e02aed994..6c174bd948 100644 --- a/framework/src/play/i18n/Lang.java +++ b/framework/src/play/i18n/Lang.java @@ -16,7 +16,7 @@ public class Lang { static final ThreadLocal current = new ThreadLocal<>(); - private static Map cache = new HashMap<>(); + private static final Map cache = new HashMap<>(); /** * Retrieve the current language or null diff --git a/framework/src/play/i18n/Localized.java b/framework/src/play/i18n/Localized.java index 4ca6f5392f..1186b38070 100644 --- a/framework/src/play/i18n/Localized.java +++ b/framework/src/play/i18n/Localized.java @@ -10,7 +10,7 @@ */ public class Localized { - private Map values = new HashMap<>(); + private final Map values = new HashMap<>(); public void set(T value) { this.values.put(Lang.get(), value); diff --git a/framework/src/play/i18n/Messages.java b/framework/src/play/i18n/Messages.java index 6688deaf29..66d35b9b3d 100644 --- a/framework/src/play/i18n/Messages.java +++ b/framework/src/play/i18n/Messages.java @@ -34,7 +34,7 @@ public class Messages { public static Properties defaults = new Properties(); - public static Map locales = new HashMap<>(); + public static final Map locales = new HashMap<>(); private static final Pattern recursive = Pattern.compile("&\\{(.*?)\\}"); @@ -125,7 +125,7 @@ public static String formatString(Locale locale, String value, Object... args) { String message = String.format(locale, value, coolStuff(value, args)); Matcher matcher = recursive.matcher(message); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); while (matcher.find()) { matcher.appendReplacement(sb, get(matcher.group(1))); } @@ -133,7 +133,7 @@ public static String formatString(Locale locale, String value, Object... args) { return sb.toString(); } - static Pattern formatterPattern = Pattern.compile("%((\\d+)\\$)?([-#+ 0,(]+)?(\\d+)?([.]\\d+)?([bBhHsScCdoxXeEfgGaAtT])"); + static final Pattern formatterPattern = Pattern.compile("%((\\d+)\\$)?([-#+ 0,(]+)?(\\d+)?([.]\\d+)?([bBhHsScCdoxXeEfgGaAtT])"); @SuppressWarnings("unchecked") static Object[] coolStuff(String pattern, Object[] args) { diff --git a/framework/src/play/i18n/MessagesPlugin.java b/framework/src/play/i18n/MessagesPlugin.java index e79ce8f28e..6108190a3f 100644 --- a/framework/src/play/i18n/MessagesPlugin.java +++ b/framework/src/play/i18n/MessagesPlugin.java @@ -23,7 +23,7 @@ public class MessagesPlugin extends PlayPlugin { static Long lastLoading = 0L; - private static List includeMessageFilenames = new ArrayList<>(); + private static final List includeMessageFilenames = new ArrayList<>(); @Override public void onApplicationStart() { diff --git a/framework/src/play/jobs/JobsPlugin.java b/framework/src/play/jobs/JobsPlugin.java index e47f8ca45c..b6da2a55f6 100644 --- a/framework/src/play/jobs/JobsPlugin.java +++ b/framework/src/play/jobs/JobsPlugin.java @@ -25,7 +25,7 @@ public class JobsPlugin extends PlayPlugin { public static ScheduledThreadPoolExecutor executor; - public static List scheduledJobs = new ArrayList<>(); + public static final List scheduledJobs = new ArrayList<>(); private static final ThreadLocal>> afterInvocationActions = new ThreadLocal<>(); @Override @@ -263,7 +263,7 @@ public void beforeInvocation() { @Override public void afterInvocation() { List> currentActions = afterInvocationActions.get(); - afterInvocationActions.set(null); + afterInvocationActions.remove(); for (Callable callable : currentActions) { executor.submit(callable); } diff --git a/framework/src/play/libs/CronExpression.java b/framework/src/play/libs/CronExpression.java index 09d9dcd5a2..46cbc7a623 100644 --- a/framework/src/play/libs/CronExpression.java +++ b/framework/src/play/libs/CronExpression.java @@ -4,7 +4,6 @@ import java.text.ParseException; import java.util.Calendar; import java.util.Date; -import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; @@ -176,31 +175,30 @@ public class CronExpression implements Serializable, Cloneable { protected static final int NO_SPEC_INT = 98; // '?' protected static final Integer ALL_SPEC = ALL_SPEC_INT; protected static final Integer NO_SPEC = NO_SPEC_INT; - protected static Map monthMap = new HashMap<>(20); - protected static Map dayMap = new HashMap<>(60); - - static { - monthMap.put("JAN", 0); - monthMap.put("FEB", 1); - monthMap.put("MAR", 2); - monthMap.put("APR", 3); - monthMap.put("MAY", 4); - monthMap.put("JUN", 5); - monthMap.put("JUL", 6); - monthMap.put("AUG", 7); - monthMap.put("SEP", 8); - monthMap.put("OCT", 9); - monthMap.put("NOV", 10); - monthMap.put("DEC", 11); - - dayMap.put("SUN", 1); - dayMap.put("MON", 2); - dayMap.put("TUE", 3); - dayMap.put("WED", 4); - dayMap.put("THU", 5); - dayMap.put("FRI", 6); - dayMap.put("SAT", 7); - } + protected static final Map monthMap = Map.ofEntries( + Map.entry("JAN", 0), + Map.entry("FEB", 1), + Map.entry("MAR", 2), + Map.entry("APR", 3), + Map.entry("MAY", 4), + Map.entry("JUN", 5), + Map.entry("JUL", 6), + Map.entry("AUG", 7), + Map.entry("SEP", 8), + Map.entry("OCT", 9), + Map.entry("NOV", 10), + Map.entry("DEC", 11) + ); + protected static final Map dayMap = Map.of( + "SUN", 1, + "MON", 2, + "TUE", 3, + "WED", 4, + "THU", 5, + "FRI", 6, + "SAT", 7 + ); + private String cronExpression = null; private TimeZone timeZone = null; protected transient TreeSet seconds; @@ -509,7 +507,7 @@ protected int storeExpressionVals(int pos, String s, int type) throws ParseExcep throw new ParseException("'?' can only be specfied for Day-of-Month or Day-of-Week.", i); } if (type == DAY_OF_WEEK && !lastdayOfMonth) { - int val = daysOfMonth.last().intValue(); + int val = daysOfMonth.last(); if (val == NO_SPEC_INT) { throw new ParseException("'?' can only be specfied for Day-of-Month -OR- Day-of-Week.", i); } @@ -969,23 +967,11 @@ protected int getNumericValue(String s, int i) { } protected int getMonthNumber(String s) { - Integer integer = monthMap.get(s); - - if (integer == null) { - return -1; - } - - return integer.intValue(); + return monthMap.getOrDefault(s, -1); } protected int getDayOfWeekNumber(String s) { - Integer integer = dayMap.get(s); - - if (integer == null) { - return -1; - } - - return integer.intValue(); + return dayMap.getOrDefault(s, -1); } // ////////////////////////////////////////////////////////////////////////// @@ -1126,7 +1112,7 @@ protected Date getTimeAfter(Date afterTime) { } } else if (nearestWeekday) { t = day; - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); java.util.Calendar tcal = java.util.Calendar.getInstance(); tcal.set(Calendar.SECOND, 0); @@ -1156,14 +1142,14 @@ protected Date getTimeAfter(Date afterTime) { tcal.set(Calendar.MONTH, mon - 1); Date nTime = tcal.getTime(); if (nTime.before(afterTime)) { - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); mon++; } - } else if (st != null && st.size() != 0) { + } else if (st.size() != 0) { t = day; - day = st.first().intValue(); + day = st.first(); } else { - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); mon++; } @@ -1182,7 +1168,7 @@ protected Date getTimeAfter(Date afterTime) { // week rule if (lastdayOfWeek) { // are we looking for the last day of the month? - int dow = daysOfWeek.first().intValue(); // desired + int dow = daysOfWeek.first(); // desired // d-o-w int cDow = cl.get(Calendar.DAY_OF_WEEK); // current // d-o-w @@ -1227,7 +1213,7 @@ protected Date getTimeAfter(Date afterTime) { } else if (nthdayOfWeek != 0) { // are we looking for the Nth day in the month? - int dow = daysOfWeek.first().intValue(); // desired + int dow = daysOfWeek.first(); // desired // d-o-w int cDow = cl.get(Calendar.DAY_OF_WEEK); // current // d-o-w diff --git a/framework/src/play/libs/Crypto.java b/framework/src/play/libs/Crypto.java index 10873c0df5..4a0059fce2 100644 --- a/framework/src/play/libs/Crypto.java +++ b/framework/src/play/libs/Crypto.java @@ -24,7 +24,7 @@ public class Crypto { */ public enum HashType { MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), SHA512("SHA-512"); - private String algorithm; + private final String algorithm; HashType(String algorithm) { this.algorithm = algorithm; diff --git a/framework/src/play/libs/Expression.java b/framework/src/play/libs/Expression.java index 5f60e76163..abeff1fa38 100644 --- a/framework/src/play/libs/Expression.java +++ b/framework/src/play/libs/Expression.java @@ -28,7 +28,7 @@ public class Expression { - static Pattern expression = Pattern.compile("^\\$\\{(.*)\\}$"); + static final Pattern expression = Pattern.compile("^\\$\\{(.*)\\}$"); public static Object evaluate(String value, String defaultValue) { Matcher matcher = expression.matcher(value); diff --git a/framework/src/play/libs/I18N.java b/framework/src/play/libs/I18N.java index 79c1fc3f3f..c3db7c7524 100644 --- a/framework/src/play/libs/I18N.java +++ b/framework/src/play/libs/I18N.java @@ -1,6 +1,5 @@ package play.libs; -import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import play.Play; @@ -11,142 +10,121 @@ */ public class I18N { - static final Map symbols = new HashMap<>(); - - static { - symbols.put("ALL", "Lek"); - symbols.put("USD", "$"); - symbols.put("AFN", "؋"); - symbols.put("ARS", "$"); - symbols.put("AWG", "ƒ"); - symbols.put("AUD", "$"); - symbols.put("AZN", "ман"); - symbols.put("BSD", "$"); - symbols.put("BBD", "$"); - symbols.put("BYR", "p."); - symbols.put("EUR", "€"); - symbols.put("BZD", "BZ$"); - symbols.put("BMD", "$"); - symbols.put("BOB", "$b"); - symbols.put("BAM", "KM"); - symbols.put("BWP", "P"); - symbols.put("BGN", "лв"); - symbols.put("BRL", "R$"); - symbols.put("GBP", "£"); - symbols.put("BND", "$"); - symbols.put("KHR", "៛"); - symbols.put("CAD", "$"); - symbols.put("KYD", "$"); - symbols.put("CLP", "$"); - symbols.put("CNY", "¥"); - symbols.put("COP", "$"); - symbols.put("CRC", "₡"); - symbols.put("HRK", "kn"); - symbols.put("CUP", "₱"); - symbols.put("EUR", "€"); - symbols.put("CZK", "Kč"); - symbols.put("DKK", "kr"); - symbols.put("DOP", "RD$"); - symbols.put("XCD", "$"); - symbols.put("EGP", "£"); - symbols.put("SVC", "$"); - symbols.put("GBP", "£"); - symbols.put("EEK", "kr"); - symbols.put("EUR", "€"); - symbols.put("FKP", "£"); - symbols.put("FJD", "$"); - symbols.put("EUR", "€"); - symbols.put("GHC", "¢"); - symbols.put("GIP", "£"); - symbols.put("EUR", "€"); - symbols.put("GTQ", "Q"); - symbols.put("GGP", "£"); - symbols.put("GYD", "$"); - symbols.put("EUR", "€"); - symbols.put("HNL", "L"); - symbols.put("HKD", "$"); - symbols.put("HUF", "Ft"); - symbols.put("ISK", "kr"); - symbols.put("INR", ""); - symbols.put("IDR", "Rp"); - symbols.put("IRR", "﷼"); - symbols.put("EUR", "€"); - symbols.put("IMP", "£"); - symbols.put("ILS", "₪"); - symbols.put("EUR", "€"); - symbols.put("JMD", "J$"); - symbols.put("JPY", "¥"); - symbols.put("JEP", "£"); - symbols.put("KZT", "лв"); - symbols.put("KPW", "₩"); - symbols.put("KRW", "₩"); - symbols.put("KGS", "лв"); - symbols.put("LAK", "₭"); - symbols.put("LVL", "Ls"); - symbols.put("LBP", "£"); - symbols.put("LRD", "$"); - symbols.put("CHF", "CHF"); - symbols.put("LTL", "Lt"); - symbols.put("EUR", "€"); - symbols.put("MKD", "ден"); - symbols.put("MYR", "RM"); - symbols.put("EUR", "€"); - symbols.put("MUR", "₨"); - symbols.put("MXN", "$"); - symbols.put("MNT", "₮"); - symbols.put("MZN", "MT"); - symbols.put("NAD", "$"); - symbols.put("NPR", "₨"); - symbols.put("ANG", "ƒ"); - symbols.put("EUR", "€"); - symbols.put("NZD", "$"); - symbols.put("NIO", "C$"); - symbols.put("NGN", "₦"); - symbols.put("KPW", "₩"); - symbols.put("NOK", "kr"); - symbols.put("OMR", "﷼"); - symbols.put("PKR", "₨"); - symbols.put("PAB", "B/."); - symbols.put("PYG", "Gs"); - symbols.put("PEN", "S/."); - symbols.put("PHP", "Php"); - symbols.put("PLN", "zł"); - symbols.put("QAR", "﷼"); - symbols.put("RON", "lei"); - symbols.put("RUB", "руб."); - symbols.put("SHP", "£"); - symbols.put("SAR", "﷼"); - symbols.put("RSD", "Дин."); - symbols.put("SCR", "₨"); - symbols.put("SGD", "$"); - symbols.put("EUR", "€"); - symbols.put("SBD", "$"); - symbols.put("SOS", "S"); - symbols.put("ZAR", "R"); - symbols.put("KRW", "₩"); - symbols.put("EUR", "€"); - symbols.put("LKR", "₨"); - symbols.put("SEK", "kr"); - symbols.put("CHF", "CHF"); - symbols.put("SRD", "$"); - symbols.put("SYP", "£"); - symbols.put("TWD", "NT$"); - symbols.put("THB", "฿"); - symbols.put("TTD", "TT$"); - symbols.put("TRY", "TL"); - symbols.put("TRL", "₤"); - symbols.put("TVD", "$"); - symbols.put("UAH", "₴"); - symbols.put("GBP", "£"); - symbols.put("USD", "$"); - symbols.put("UYU", "$U"); - symbols.put("UZS", "лв"); - symbols.put("EUR", "€"); - symbols.put("VEF", "Bs"); - symbols.put("VND", "₫"); - symbols.put("YER", "﷼"); - symbols.put("ZWD", "Z$"); - } + static final Map symbols = Map.ofEntries( + Map.entry("ALL", "Lek"), + Map.entry("USD", "$"), + Map.entry("AFN", "؋"), + Map.entry("ARS", "$"), + Map.entry("AWG", "ƒ"), + Map.entry("AUD", "$"), + Map.entry("AZN", "ман"), + Map.entry("BSD", "$"), + Map.entry("BBD", "$"), + Map.entry("BYR", "p."), + Map.entry("EUR", "€"), + Map.entry("BZD", "BZ$"), + Map.entry("BMD", "$"), + Map.entry("BOB", "$b"), + Map.entry("BAM", "KM"), + Map.entry("BWP", "P"), + Map.entry("BGN", "лв"), + Map.entry("BRL", "R$"), + Map.entry("GBP", "£"), + Map.entry("BND", "$"), + Map.entry("KHR", "៛"), + Map.entry("CAD", "$"), + Map.entry("KYD", "$"), + Map.entry("CLP", "$"), + Map.entry("CNY", "¥"), + Map.entry("COP", "$"), + Map.entry("CRC", "₡"), + Map.entry("HRK", "kn"), + Map.entry("CUP", "₱"), + Map.entry("CZK", "Kč"), + Map.entry("DKK", "kr"), + Map.entry("DOP", "RD$"), + Map.entry("XCD", "$"), + Map.entry("EGP", "£"), + Map.entry("SVC", "$"), + Map.entry("EEK", "kr"), + Map.entry("FKP", "£"), + Map.entry("FJD", "$"), + Map.entry("GHC", "¢"), + Map.entry("GIP", "£"), + Map.entry("GTQ", "Q"), + Map.entry("GGP", "£"), + Map.entry("GYD", "$"), + Map.entry("HNL", "L"), + Map.entry("HKD", "$"), + Map.entry("HUF", "Ft"), + Map.entry("ISK", "kr"), + Map.entry("INR", ""), + Map.entry("IDR", "Rp"), + Map.entry("IRR", "﷼"), + Map.entry("IMP", "£"), + Map.entry("ILS", "₪"), + Map.entry("JMD", "J$"), + Map.entry("JPY", "¥"), + Map.entry("JEP", "£"), + Map.entry("KZT", "лв"), + Map.entry("KPW", "₩"), + Map.entry("KGS", "лв"), + Map.entry("LAK", "₭"), + Map.entry("LVL", "Ls"), + Map.entry("LBP", "£"), + Map.entry("LRD", "$"), + Map.entry("CHF", "CHF"), + Map.entry("LTL", "Lt"), + Map.entry("MKD", "ден"), + Map.entry("MYR", "RM"), + Map.entry("MUR", "₨"), + Map.entry("MXN", "$"), + Map.entry("MNT", "₮"), + Map.entry("MZN", "MT"), + Map.entry("NAD", "$"), + Map.entry("NPR", "₨"), + Map.entry("ANG", "ƒ"), + Map.entry("NZD", "$"), + Map.entry("NIO", "C$"), + Map.entry("NGN", "₦"), + Map.entry("NOK", "kr"), + Map.entry("OMR", "﷼"), + Map.entry("PKR", "₨"), + Map.entry("PAB", "B/."), + Map.entry("PYG", "Gs"), + Map.entry("PEN", "S/."), + Map.entry("PHP", "Php"), + Map.entry("PLN", "zł"), + Map.entry("QAR", "﷼"), + Map.entry("RON", "lei"), + Map.entry("RUB", "руб."), + Map.entry("SHP", "£"), + Map.entry("SAR", "﷼"), + Map.entry("RSD", "Дин."), + Map.entry("SCR", "₨"), + Map.entry("SGD", "$"), + Map.entry("SBD", "$"), + Map.entry("SOS", "S"), + Map.entry("ZAR", "R"), + Map.entry("KRW", "₩"), + Map.entry("LKR", "₨"), + Map.entry("SEK", "kr"), + Map.entry("SRD", "$"), + Map.entry("SYP", "£"), + Map.entry("TWD", "NT$"), + Map.entry("THB", "฿"), + Map.entry("TTD", "TT$"), + Map.entry("TRY", "TL"), + Map.entry("TRL", "₤"), + Map.entry("TVD", "$"), + Map.entry("UAH", "₴"), + Map.entry("UYU", "$U"), + Map.entry("UZS", "лв"), + Map.entry("VEF", "Bs"), + Map.entry("VND", "₫"), + Map.entry("YER", "﷼"), + Map.entry("ZWD", "Z$") + ); /** * Retrieve currency symbol for a currency @@ -154,10 +132,7 @@ public class I18N { * @return ($, €, ...) */ public static String getCurrencySymbol(String currency) { - if (symbols.containsKey(currency)) { - return symbols.get(currency); - } - return currency; + return symbols.getOrDefault(currency, currency); } public static String getDateFormat() { diff --git a/framework/src/play/libs/IO.java b/framework/src/play/libs/IO.java index cb09da0ff7..970be89b1b 100644 --- a/framework/src/play/libs/IO.java +++ b/framework/src/play/libs/IO.java @@ -1,17 +1,22 @@ package play.libs; +import static java.nio.charset.Charset.defaultCharset; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static org.apache.commons.io.Charsets.toCharset; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Properties; +import java.util.stream.Stream; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import play.exceptions.UnexpectedException; @@ -77,7 +82,11 @@ public static String readContentAsString(InputStream is, String encoding) { * @return The String content */ public static String readContentAsString(File file) { - return readContentAsString(file, "utf-8"); + try { + return Files.readString(file.toPath(), UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } } /** @@ -91,32 +100,34 @@ public static String readContentAsString(File file) { */ public static String readContentAsString(File file, String encoding) { try { - return FileUtils.readFileToString(file, encoding); + return Files.readString(file.toPath(), toCharset(encoding)); } catch (IOException e) { throw new UnexpectedException(e); } } public static List readLines(InputStream is) { - List lines = null; try { - lines = IOUtils.readLines(is); + return IOUtils.readLines(is, defaultCharset()); } catch (IOException ex) { throw new UnexpectedException(ex); } - return lines; } public static List readLines(File file, String encoding) { try { - return FileUtils.readLines(file, encoding); + return Files.readAllLines(file.toPath(), toCharset(encoding)); } catch (IOException ex) { throw new UnexpectedException(ex); } } public static List readLines(File file) { - return readLines(file, "utf-8"); + try { + return Files.readAllLines(file.toPath(), UTF_8); + } catch (IOException ex) { + throw new UnexpectedException(ex); + } } /** @@ -128,7 +139,7 @@ public static List readLines(File file) { */ public static byte[] readContent(File file) { try { - return FileUtils.readFileToByteArray(file); + return Files.readAllBytes(file.toPath()); } catch (IOException e) { throw new UnexpectedException(e); } @@ -158,7 +169,13 @@ public static byte[] readContent(InputStream is) { * The stream to write */ public static void writeContent(CharSequence content, OutputStream os) { - writeContent(content, os, "utf-8"); + try { + IOUtils.write(content, os, UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } finally { + closeQuietly(os); + } } /** @@ -190,7 +207,11 @@ public static void writeContent(CharSequence content, OutputStream os, String en * The file to write */ public static void writeContent(CharSequence content, File file) { - writeContent(content, file, "utf-8"); + try { + Files.writeString(file.toPath(), content, UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } } /** @@ -205,7 +226,7 @@ public static void writeContent(CharSequence content, File file) { */ public static void writeContent(CharSequence content, File file, String encoding) { try { - FileUtils.write(file, content, encoding); + Files.writeString(file.toPath(), content, toCharset(encoding)); } catch (IOException e) { throw new UnexpectedException(e); } @@ -221,14 +242,14 @@ public static void writeContent(CharSequence content, File file, String encoding */ public static void write(byte[] data, File file) { try { - FileUtils.writeByteArrayToFile(file, data); + Files.write(file.toPath(), data); } catch (IOException e) { throw new UnexpectedException(e); } } /** - * Copy an stream to another one. + * Copy a stream to another one. By the end of the method the input stream {@code is} will be closed. * * @param is * The source stream @@ -237,7 +258,7 @@ public static void write(byte[] data, File file) { */ public static void copy(InputStream is, OutputStream os) { try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); } finally { @@ -246,7 +267,7 @@ public static void copy(InputStream is, OutputStream os) { } /** - * Copy an stream to another one. + * Copy a stream to another one. By the end of the method both of streams {@code is} and {@code os} will be closed. * * @param is * The source stream @@ -255,7 +276,7 @@ public static void copy(InputStream is, OutputStream os) { */ public static void write(InputStream is, OutputStream os) { try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); } finally { @@ -276,7 +297,7 @@ public static void write(InputStream is, File f) { try { OutputStream os = new FileOutputStream(f); try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } finally { closeQuietly(is); closeQuietly(os); @@ -288,19 +309,16 @@ public static void write(InputStream is, File f) { // If targetLocation does not exist, it will be created. public static void copyDirectory(File source, File target) { - if (source.isDirectory()) { - if (!target.exists()) { - target.mkdir(); - } - for (String child : source.list()) { - copyDirectory(new File(source, child), new File(target, child)); - } - } else { - try { - write(new FileInputStream(source), new FileOutputStream(target)); - } catch (IOException e) { - throw new UnexpectedException(e); - } + try (Stream dirs = Files.walk(source.toPath())) { + dirs.forEach(src -> { + try { + Files.copy(source.toPath(), target.toPath(), REPLACE_EXISTING); + } catch (IOException e) { + throw new UnexpectedException(e); + } + }); + } catch (IOException e) { + throw new UnexpectedException(e); } } diff --git a/framework/src/play/libs/Images.java b/framework/src/play/libs/Images.java index fa501f2255..3f7013a098 100644 --- a/framework/src/play/libs/Images.java +++ b/framework/src/play/libs/Images.java @@ -234,11 +234,11 @@ public static Captcha captcha() { */ public static class Captcha extends InputStream { + public final GimpyRenderer gimpy = new RippleGimpyRenderer(); + public final List fonts = new ArrayList<>(2); public String text = null; public BackgroundProducer background = new TransparentBackgroundProducer(); - public GimpyRenderer gimpy = new RippleGimpyRenderer(); public Color textColor = Color.BLACK; - public List fonts = new ArrayList<>(2); public int w, h; public Color noise = null; diff --git a/framework/src/play/libs/Mail.java b/framework/src/play/libs/Mail.java index 146083621e..5eff4b485d 100644 --- a/framework/src/play/libs/Mail.java +++ b/framework/src/play/libs/Mail.java @@ -243,12 +243,12 @@ public Boolean get(long timeout, TimeUnit unit) { } } - static ExecutorService executor = Executors.newCachedThreadPool(); + static final ExecutorService executor = Executors.newCachedThreadPool(); public static class SMTPAuthenticator extends Authenticator { - private String user; - private String password; + private final String user; + private final String password; public SMTPAuthenticator(String user, String password) { this.user = user; diff --git a/framework/src/play/libs/MimeTypes.java b/framework/src/play/libs/MimeTypes.java index 1ebcab8fd9..9e653c1dca 100644 --- a/framework/src/play/libs/MimeTypes.java +++ b/framework/src/play/libs/MimeTypes.java @@ -18,11 +18,7 @@ public class MimeTypes { private static Properties mimetypes = null; - private static Pattern extPattern; - - static { - extPattern = Pattern.compile("^.*\\.([^.]+)$"); - } + private static final Pattern extPattern = Pattern.compile("^.*\\.([^.]+)$"); /** * return the mimetype from a file name diff --git a/framework/src/play/libs/OAuth.java b/framework/src/play/libs/OAuth.java index 59444626f7..e9876b2058 100644 --- a/framework/src/play/libs/OAuth.java +++ b/framework/src/play/libs/OAuth.java @@ -18,8 +18,8 @@ */ public class OAuth { - private ServiceInfo info; - private OAuthProvider provider; + private final ServiceInfo info; + private final OAuthProvider provider; private OAuth(ServiceInfo info) { this.info = info; @@ -139,11 +139,11 @@ public String redirectUrl(TokenPair tokenPair) { * */ public static class ServiceInfo { - public String requestTokenURL; - public String accessTokenURL; - public String authorizationURL; - public String consumerKey; - public String consumerSecret; + public final String requestTokenURL; + public final String accessTokenURL; + public final String authorizationURL; + public final String consumerKey; + public final String consumerSecret; public ServiceInfo(String requestTokenURL, String accessTokenURL, String authorizationURL, String consumerKey, String consumerSecret) { @@ -229,8 +229,8 @@ public String toString() { @Deprecated public static class TokenPair { - public String token; - public String secret; + public final String token; + public final String secret; public TokenPair(String token, String secret) { this.token = token; diff --git a/framework/src/play/libs/OAuth2.java b/framework/src/play/libs/OAuth2.java index 85944c9028..355c9f14b8 100644 --- a/framework/src/play/libs/OAuth2.java +++ b/framework/src/play/libs/OAuth2.java @@ -20,10 +20,10 @@ public class OAuth2 { private static final String CLIENT_ID_NAME = "client_id"; private static final String REDIRECT_URI = "redirect_uri"; - public String authorizationURL; - public String accessTokenURL; - public String clientid; - public String secret; + public final String authorizationURL; + public final String accessTokenURL; + public final String clientid; + public final String secret; public OAuth2(String authorizationURL, String accessTokenURL, String clientid, String secret) { this.accessTokenURL = accessTokenURL; diff --git a/framework/src/play/libs/OpenID.java b/framework/src/play/libs/OpenID.java index 358172aebb..80f5d3b247 100644 --- a/framework/src/play/libs/OpenID.java +++ b/framework/src/play/libs/OpenID.java @@ -33,13 +33,13 @@ private OpenID(String id) { } // ~~~ API - String id; + final List sregRequired = new ArrayList<>(); + final List sregOptional = new ArrayList<>(); + final Map axRequired = new HashMap<>(); + final Map axOptional = new HashMap<>(); + final String id; String returnAction; String realmAction; - List sregRequired = new ArrayList<>(); - List sregOptional = new ArrayList<>(); - Map axRequired = new HashMap<>(); - Map axOptional = new HashMap<>(); public OpenID returnTo(String action) { this.returnAction = action; @@ -359,7 +359,7 @@ public static class UserInfo { /** * Extensions values */ - public Map extensions = new HashMap<>(); + public final Map extensions = new HashMap<>(); @Override public String toString() { diff --git a/framework/src/play/libs/Time.java b/framework/src/play/libs/Time.java index f6ebfc51db..6a21a14846 100644 --- a/framework/src/play/libs/Time.java +++ b/framework/src/play/libs/Time.java @@ -16,9 +16,9 @@ */ public class Time { private static final Pattern p = Pattern.compile("(([0-9]+?)((d|h|mi|min|mn|s)))+?"); - private static final Integer MINUTE = 60; - private static final Integer HOUR = 60 * MINUTE; - private static final Integer DAY = 24 * HOUR; + private static final int MINUTE = 60; + private static final int HOUR = 60 * MINUTE; + private static final int DAY = 24 * HOUR; /** * Parse a duration diff --git a/framework/src/play/libs/WS.java b/framework/src/play/libs/WS.java index d63e4989fa..811ca3bb40 100644 --- a/framework/src/play/libs/WS.java +++ b/framework/src/play/libs/WS.java @@ -667,8 +667,8 @@ protected String createQueryString() { } public static class FileParam { - public File file; - public String paramName; + public final File file; + public final String paramName; public FileParam(File file, String name) { this.file = file; @@ -852,7 +852,7 @@ public Map getQueryString() { public JsonElement getJson() { String json = getString(); try { - return new JsonParser().parse(json); + return JsonParser.parseString(json); } catch (Exception e) { Logger.error("Bad JSON: \n%s", json); throw new RuntimeException("Cannot parse JSON (check logs)", e); diff --git a/framework/src/play/libs/mail/test/LegacyMockMailSystem.java b/framework/src/play/libs/mail/test/LegacyMockMailSystem.java index 77c4c6921a..9a4e28da04 100644 --- a/framework/src/play/libs/mail/test/LegacyMockMailSystem.java +++ b/framework/src/play/libs/mail/test/LegacyMockMailSystem.java @@ -27,7 +27,7 @@ public class LegacyMockMailSystem implements MailSystem { // Has to remain static to preserve the possibility of testing mail sending within Selenium tests - static Map emails = new HashMap<>(); + static final Map emails = new HashMap<>(); @Override public Future sendMessage(Email email) { diff --git a/framework/src/play/libs/ws/WSAsync.java b/framework/src/play/libs/ws/WSAsync.java index c31795c23e..018d216104 100644 --- a/framework/src/play/libs/ws/WSAsync.java +++ b/framework/src/play/libs/ws/WSAsync.java @@ -747,9 +747,9 @@ public WSRequest sign(WSRequest request, String method) return request; } - public class WSRequestAdapter implements HttpRequest { + public static class WSRequestAdapter implements HttpRequest { - private WSRequest request; + private final WSRequest request; private String method; public WSRequestAdapter(WSRequest request) { diff --git a/framework/src/play/libs/ws/WSUrlFetch.java b/framework/src/play/libs/ws/WSUrlFetch.java index 0e40b25a65..d34227b97b 100644 --- a/framework/src/play/libs/ws/WSUrlFetch.java +++ b/framework/src/play/libs/ws/WSUrlFetch.java @@ -49,7 +49,7 @@ public play.libs.WS.WSRequest newRequest(String url, String encoding) { return new WSUrlfetchRequest(url, encoding); } - public class WSUrlfetchRequest extends WSRequest { + public static class WSUrlfetchRequest extends WSRequest { protected WSUrlfetchRequest(String url, String encoding) { super(url, encoding); diff --git a/framework/src/play/mvc/CookieDataCodec.java b/framework/src/play/mvc/CookieDataCodec.java index eb220728e7..e5cdda1fcf 100644 --- a/framework/src/play/mvc/CookieDataCodec.java +++ b/framework/src/play/mvc/CookieDataCodec.java @@ -20,7 +20,7 @@ public class CookieDataCodec { * applications are upgraded to a newer version of Play *

*/ - public static Pattern oldCookieSessionParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); + public static final Pattern oldCookieSessionParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); /** * @param map diff --git a/framework/src/play/mvc/Http.java b/framework/src/play/mvc/Http.java index 9c845935d1..4193d7c1f6 100644 --- a/framework/src/play/mvc/Http.java +++ b/framework/src/play/mvc/Http.java @@ -272,7 +272,7 @@ public static class Request implements Serializable { /** * Free space to store your request specific data */ - public Map args = new HashMap<>(16); + public final Map args = new HashMap<>(16); /** * When the request has been received */ @@ -580,7 +580,7 @@ public List acceptLanguage() { } String acceptLanguage = headers.get("accept-language").value(); List languages = Arrays.asList(acceptLanguage.split(",")); - Collections.sort(languages, (lang1, lang2) -> { + languages.sort((lang1, lang2) -> { double q1 = 1.0; double q2 = 1.0; Matcher m1 = qpattern.matcher(lang1); @@ -625,11 +625,11 @@ public static class Response { /** * Response headers */ - public Map headers = new HashMap<>(16); + public final Map headers = new HashMap<>(16); /** * Response cookies */ - public Map cookies = new HashMap<>(16); + public final Map cookies = new HashMap<>(16); /** * Response body stream */ diff --git a/framework/src/play/mvc/Router.java b/framework/src/play/mvc/Router.java index dea0a61e8c..8c81936faa 100644 --- a/framework/src/play/mvc/Router.java +++ b/framework/src/play/mvc/Router.java @@ -28,12 +28,12 @@ */ public class Router { - static Pattern routePattern = new Pattern( + static final Pattern routePattern = new Pattern( "^({method}GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|WS|\\*)[(]?({headers}[^)]*)(\\))?\\s+({path}.*/[^\\s]*)\\s+({action}[^\\s(]+)({params}.+)?(\\s*)$"); /** * Pattern used to locate a method override instruction in request.querystring */ - static Pattern methodOverride = new Pattern("^.*x-http-method-override=({method}GET|PUT|POST|PATCH|DELETE).*$"); + static final Pattern methodOverride = new Pattern("^.*x-http-method-override=({method}GET|PUT|POST|PATCH|DELETE).*$"); /** * Timestamp the routes file was last loaded at. */ @@ -341,7 +341,7 @@ public static void detectChanges(String prefix) { /** * All the loaded routes. */ - public static List routes = new CopyOnWriteArrayList<>(); + public static final List routes = new CopyOnWriteArrayList<>(); public static void routeOnlyStatic(Http.Request request) { for (Route route : routes) { @@ -714,8 +714,8 @@ private static List findActionRoutes(String action) { } private static final class ActionRoute { + private final Map args = new HashMap<>(2); private Route route; - private Map args = new HashMap<>(2); } public static class ActionDefinition { @@ -828,9 +828,9 @@ public static class Route { Arg hostArg = null; public int routesFileLine; public String routesFile; - static Pattern customRegexPattern = new Pattern("\\{([a-zA-Z_][a-zA-Z_0-9]*)\\}"); - static Pattern argsPattern = new Pattern("\\{<([^>]+)>([a-zA-Z_0-9]+)\\}"); - static Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+):'(.*)'"); + static final Pattern customRegexPattern = new Pattern("\\{([a-zA-Z_][a-zA-Z_0-9]*)\\}"); + static final Pattern argsPattern = new Pattern("\\{<([^>]+)>([a-zA-Z_0-9]+)\\}"); + static final Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+):'(.*)'"); public void compute() { this.host = ""; diff --git a/framework/src/play/mvc/Scope.java b/framework/src/play/mvc/Scope.java index 939b1f74e5..11eb7e266c 100644 --- a/framework/src/play/mvc/Scope.java +++ b/framework/src/play/mvc/Scope.java @@ -34,7 +34,7 @@ public class Scope { .getProperty("application.session.sendOnlyIfChanged", "false").toLowerCase().equals("true"); public static final String COOKIE_SAME_SITE = COOKIE_SECURE ? "None" : "Lax"; - public static SessionStore sessionStore = createSessionStore(); + public static final SessionStore sessionStore = createSessionStore(); private static SessionStore createSessionStore() { String sessionStoreClass = Play.configuration.getProperty("application.session.storeClass"); @@ -56,8 +56,8 @@ private static SessionStore createSessionStore() { */ public static class Flash { - Map data = new HashMap<>(); - Map out = new HashMap<>(); + final Map data = new HashMap<>(); + final Map out = new HashMap<>(); public static Flash restore() { try { @@ -180,7 +180,7 @@ public static Session restore() { return sessionStore.restore(); } - Map data = new HashMap<>(); // ThreadLocal access + final Map data = new HashMap<>(); // ThreadLocal access boolean changed = false; public static final ThreadLocal current = new ThreadLocal<>(); @@ -293,7 +293,7 @@ public static Params current() { } boolean requestIsParsed; - public Map data = new LinkedHashMap<>(); + public final Map data = new LinkedHashMap<>(); boolean rootParamsNodeIsGenerated = false; private RootParamNode rootParamNode = null; @@ -357,13 +357,7 @@ public void remove(String key) { public void removeStartWith(String prefix) { checkAndParse(); - Iterator> iterator = data.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - if (entry.getKey().startsWith(prefix)) { - iterator.remove(); - } - } + data.entrySet().removeIf(entry -> entry.getKey().startsWith(prefix)); // make sure rootsParamsNode is regenerated if needed rootParamsNodeIsGenerated = false; } @@ -520,7 +514,7 @@ public String toString() { */ public static class RenderArgs { - public Map data = new HashMap<>(); // ThreadLocal access + public final Map data = new HashMap<>(); // ThreadLocal access public static final ThreadLocal current = new ThreadLocal<>(); public static RenderArgs current() { @@ -551,7 +545,7 @@ public String toString() { */ public static class RouteArgs { - public Map data = new HashMap<>(); // ThreadLocal access + public final Map data = new HashMap<>(); // ThreadLocal access public static final ThreadLocal current = new ThreadLocal<>(); public static RouteArgs current() { diff --git a/framework/src/play/mvc/results/RenderBinary.java b/framework/src/play/mvc/results/RenderBinary.java index 559c3e504d..91d78b0e97 100644 --- a/framework/src/play/mvc/results/RenderBinary.java +++ b/framework/src/play/mvc/results/RenderBinary.java @@ -9,6 +9,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import java.nio.charset.StandardCharsets; import org.apache.commons.codec.net.URLCodec; import org.apache.commons.io.IOUtils; @@ -211,7 +212,7 @@ private static void copyInputStreamAndClose(InputStream is, OutputStream out) th } private boolean canAsciiEncode(String string) { - CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder(); + CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder(); return asciiEncoder.canEncode(string); } diff --git a/framework/src/play/mvc/results/RenderJson.java b/framework/src/play/mvc/results/RenderJson.java index 57f8f4fccd..a0a92889fc 100644 --- a/framework/src/play/mvc/results/RenderJson.java +++ b/framework/src/play/mvc/results/RenderJson.java @@ -5,6 +5,7 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.Objects; import play.exceptions.UnexpectedException; import play.mvc.Http.Request; @@ -47,11 +48,7 @@ public RenderJson(String jsonString) { public RenderJson(Object response, Gson gson) { this.response = response; - if (gson != null) { - json = gson.toJson(response); - } else { - json = GSON.toJson(response); - } + json = Objects.requireNonNullElse(gson, GSON).toJson(response); } @Override diff --git a/framework/src/play/plugins/PluginCollection.java b/framework/src/play/plugins/PluginCollection.java index 2abc0d1f19..13c4d781f8 100644 --- a/framework/src/play/plugins/PluginCollection.java +++ b/framework/src/play/plugins/PluginCollection.java @@ -56,7 +56,7 @@ public class PluginCollection { /** * List that holds all loaded plugins, enabled or disabled */ - protected List allPlugins = new ArrayList<>(); + protected final List allPlugins = new ArrayList<>(); /** * Readonly copy of allPlugins - updated each time allPlugins is updated. Using this cached copy so we don't have to @@ -67,7 +67,7 @@ public class PluginCollection { /** * List of all enabled plugins */ - protected List enabledPlugins = new ArrayList<>(); + protected final List enabledPlugins = new ArrayList<>(); /** * Readonly copy of enabledPlugins - updated each time enabledPlugins is updated. Using this cached copy so we don't @@ -78,7 +78,7 @@ public class PluginCollection { /** * List of all enabled plugins with filters */ - protected List enabledPluginsWithFilters = new ArrayList<>(); + protected final List enabledPluginsWithFilters = new ArrayList<>(); /** * Readonly copy of enabledPluginsWithFilters - updated each time enabledPluginsWithFilters is updated. Using this @@ -94,7 +94,7 @@ public class PluginCollection { * @return Read only list of plugins */ protected List createReadonlyCopy(List list) { - return Collections.unmodifiableList(new ArrayList<>(list)); + return List.copyOf(list); } private static class LoadingPluginInfo implements Comparable { @@ -202,7 +202,7 @@ List loadPlayPluginDescriptors() { String playPluginsDescriptors = Play.configuration.getProperty("play.plugins.descriptor"); if (playPluginsDescriptors != null) { return Stream.of(playPluginsDescriptors.split(",")) - .map(playPluginsDescriptor -> fileToUrl(playPluginsDescriptor)) + .map(this::fileToUrl) .collect(toList()); } return Collections.list(Play.classloader.getResources(play_plugins_resourceName)); diff --git a/framework/src/play/server/FileService.java b/framework/src/play/server/FileService.java index 1213e9ebb1..9b94575527 100644 --- a/framework/src/play/server/FileService.java +++ b/framework/src/play/server/FileService.java @@ -273,9 +273,9 @@ private static String makeRangeBodyHeader(String separator, String contentType, } private class ByteRange { - public long start; - public long end; - public byte[] header; + public final long start; + public final long end; + public final byte[] header; public long length() { return end - start + 1; diff --git a/framework/src/play/server/HttpServerPipelineFactory.java b/framework/src/play/server/HttpServerPipelineFactory.java index 6ddc376bdd..fef7498580 100644 --- a/framework/src/play/server/HttpServerPipelineFactory.java +++ b/framework/src/play/server/HttpServerPipelineFactory.java @@ -5,6 +5,8 @@ import org.jboss.netty.channel.ChannelHandler; import play.Play; import play.Logger; +import play.exceptions.UnexpectedException; + import java.util.Map; import java.util.HashMap; @@ -12,9 +14,9 @@ public class HttpServerPipelineFactory implements ChannelPipelineFactory { - private String pipelineConfig = Play.configuration.getProperty("play.netty.pipeline", "play.server.FlashPolicyHandler,play.server.PlayHttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.PlayHandler"); + protected static final Map classes = new HashMap<>(); - protected static Map classes = new HashMap<>(); + private String pipelineConfig = Play.configuration.getProperty("play.netty.pipeline", "play.server.FlashPolicyHandler,play.server.PlayHttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.PlayHandler"); @Override public ChannelPipeline getPipeline() throws Exception { @@ -51,11 +53,9 @@ public ChannelPipeline getPipeline() throws Exception { } } - if (playHandler != null) { - pipeline.addLast("handler", playHandler); - playHandler.pipelines.put("handler", playHandler); - } - + pipeline.addLast("handler", playHandler); + playHandler.pipelines.put("handler", playHandler); + return pipeline; } @@ -68,11 +68,13 @@ protected String getName(String name) { protected ChannelHandler getInstance(String name) throws Exception { - Class clazz = classes.get(name); - if (clazz == null) { - clazz = Class.forName(name); - classes.put(name, clazz); - } + Class clazz = classes.computeIfAbsent(name, className -> { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + throw new UnexpectedException(e); + } + }); if (ChannelHandler.class.isAssignableFrom(clazz)) return (ChannelHandler)clazz.newInstance(); return null; diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 8ef658ca12..79df27c0be 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -104,10 +104,7 @@ import java.io.*; import java.net.InetSocketAddress; import java.net.URLEncoder; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -133,14 +130,10 @@ public class PlayHandler extends SimpleChannelUpstreamHandler { private static final String signature = "Play! Framework;" + Play.version + ";" + Play.mode.name().toLowerCase(); private static final boolean exposePlayServer; - private static final String ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - private static final Charset ASCII = Charset.forName("ASCII"); - private static final MessageDigest SHA_1; - /** * The Pipeline is given for a PlayHandler */ - public Map pipelines = new HashMap<>(); + public final Map pipelines = new HashMap<>(); private WebSocketServerHandshaker handshaker; @@ -151,14 +144,6 @@ public class PlayHandler extends SimpleChannelUpstreamHandler { */ private static final Set allowedHttpMethodOverride; - static { - try { - SHA_1 = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-1 not supported on this platform", e); - } - } - static { exposePlayServer = !"false".equals(Play.configuration.getProperty("http.exposePlayServer")); allowedHttpMethodOverride = Stream.of(Play.configuration.getProperty("http.allowed.method.override", "").split(",")).collect(Collectors.toSet()); @@ -261,10 +246,10 @@ public boolean init() { Response.current.set(response); Scope.Params.current.set(request.params); - Scope.RenderArgs.current.set(null); - Scope.RouteArgs.current.set(null); - Scope.Session.current.set(null); - Scope.Flash.current.set(null); + Scope.RenderArgs.current.remove(); + Scope.RouteArgs.current.remove(); + Scope.Session.current.remove(); + Scope.Flash.current.remove(); CachedBoundActionMethodArgs.init(); try { @@ -717,10 +702,7 @@ protected static Map getHeaders(HttpRequest nettyRequest) { for (String key : nettyRequest.headers().names()) { Http.Header hd = new Http.Header(); hd.name = key.toLowerCase(); - hd.values = new ArrayList<>(); - for (String next : nettyRequest.headers().getAll(key)) { - hd.values.add(next); - } + hd.values = new ArrayList<>(nettyRequest.headers().getAll(key)); headers.put(hd.name, hd); } @@ -1043,8 +1025,8 @@ public static void setContentLength(HttpMessage message, long contentLength) { static class LazyChunkedInput implements org.jboss.netty.handler.stream.ChunkedInput { + private final ConcurrentLinkedQueue nextChunks = new ConcurrentLinkedQueue<>(); private boolean closed = false; - private ConcurrentLinkedQueue nextChunks = new ConcurrentLinkedQueue<>(); @Override public boolean hasNextChunk() throws Exception { diff --git a/framework/src/play/server/ServletWrapper.java b/framework/src/play/server/ServletWrapper.java index 9a95315481..83bc9028f8 100644 --- a/framework/src/play/server/ServletWrapper.java +++ b/framework/src/play/server/ServletWrapper.java @@ -510,10 +510,10 @@ private void copyStream(HttpServletResponse servletResponse, InputStream is) thr public class ServletInvocation extends Invoker.DirectInvocation { - private Request request; - private Response response; - private HttpServletRequest httpServletRequest; - private HttpServletResponse httpServletResponse; + private final Request request; + private final Response response; + private final HttpServletRequest httpServletRequest; + private final HttpServletResponse httpServletResponse; public ServletInvocation(Request request, Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { this.httpServletRequest = httpServletRequest; diff --git a/framework/src/play/server/ssl/SslHttpServerContextFactory.java b/framework/src/play/server/ssl/SslHttpServerContextFactory.java index b4da404886..9146bd26c7 100644 --- a/framework/src/play/server/ssl/SslHttpServerContextFactory.java +++ b/framework/src/play/server/ssl/SslHttpServerContextFactory.java @@ -80,7 +80,7 @@ public static SSLContext getServerContext() { public static class PEMKeyManager extends X509ExtendedKeyManager { - static PEMKeyManager instance = new PEMKeyManager(); + static final PEMKeyManager instance = new PEMKeyManager(); PrivateKey key; X509Certificate[] chain; diff --git a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java index 295d6643e0..f622a9295c 100644 --- a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java +++ b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java @@ -14,7 +14,7 @@ public class SslHttpServerPipelineFactory extends HttpServerPipelineFactory { - private String pipelineConfig = Play.configuration.getProperty("play.ssl.netty.pipeline", + private final String pipelineConfig = Play.configuration.getProperty("play.ssl.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.ssl.SslPlayHandler"); @Override diff --git a/framework/src/play/templates/BaseTemplate.java b/framework/src/play/templates/BaseTemplate.java index dae9a543c0..7b3e4fd0e0 100644 --- a/framework/src/play/templates/BaseTemplate.java +++ b/framework/src/play/templates/BaseTemplate.java @@ -18,12 +18,12 @@ public abstract class BaseTemplate extends Template { + public final Long timestamp = System.currentTimeMillis(); public String compiledSource; public Map linesMatrix = new HashMap<>(); public Set doBodyLines = new HashSet<>(); public Class compiledTemplate; public String compiledTemplateName; - public Long timestamp = System.currentTimeMillis(); public BaseTemplate(String name, String source) { this.name = name; @@ -97,7 +97,7 @@ void throwException(Throwable e) { public static final class RawData { - public String data; + public final String data; public RawData(Object val) { if (val == null) { diff --git a/framework/src/play/templates/FastTags.java b/framework/src/play/templates/FastTags.java index ebc5448302..70ae069da2 100644 --- a/framework/src/play/templates/FastTags.java +++ b/framework/src/play/templates/FastTags.java @@ -414,8 +414,7 @@ public static void _include(Map args, Closure body, PrintWriter out, Execu name = ct + name.substring(1); } BaseTemplate t = (BaseTemplate) TemplateLoader.load(name); - Map newArgs = new HashMap<>(); - newArgs.putAll(template.getBinding().getVariables()); + Map newArgs = new HashMap<>(template.getBinding().getVariables()); newArgs.put("_isInclude", true); t.internalRender(newArgs); } catch (TemplateNotFoundException e) { @@ -441,8 +440,7 @@ public static void _render(Map args, Closure body, PrintWriter out, Execut } args.remove("arg"); BaseTemplate t = (BaseTemplate) TemplateLoader.load(name); - Map newArgs = new HashMap<>(); - newArgs.putAll((Map) args); + Map newArgs = new HashMap<>((Map) args); newArgs.put("_isInclude", true); newArgs.put("out", out); t.internalRender(newArgs); diff --git a/framework/src/play/templates/GroovyTemplate.java b/framework/src/play/templates/GroovyTemplate.java index 66670f38e7..f0a649ac33 100644 --- a/framework/src/play/templates/GroovyTemplate.java +++ b/framework/src/play/templates/GroovyTemplate.java @@ -3,11 +3,13 @@ import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -16,9 +18,11 @@ import org.codehaus.groovy.control.CompilationUnit.IGroovyClassOperation; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.MultipleCompilationErrorsException; +import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.Message; +import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.syntax.SyntaxException; @@ -142,34 +146,18 @@ public void compile() { compilationUnit.addSource( new SourceUnit(name, compiledSource, compilerConfiguration, tClassLoader, compilationUnit.getErrorCollector())); - // The following approach to adding the phase operation replaces the original - // reflection based approach commented out lower down. This appears to be the - // canonical approach and possibly has only been made available in the v3.x - // stream but it differs in two ways from the reflection based approach and it's - // not clear if and what the impact is: - // 1. It does NOT guarantee an empty list of OUTPUT phases operations to begin with. - // 2. The new phase operation is added to the start and not the end. - // See https://github.com/apache/groovy/blob/GROOVY_3_0_6/src/main/java/org/codehaus/groovy/control/CompilationUnit.java#L349 - compilationUnit.addPhaseOperation(new IGroovyClassOperation() { - @Override - public void call(GroovyClass gclass) { - groovyClassesForThisTemplate.add(gclass); - } - }); - - // TOOD: Remove once the above replacement logic has been confirmed. -// Field phasesF = compilationUnit.getClass().getDeclaredField("phaseOperations"); -// phasesF.setAccessible(true); -// Collection[] phases = (Collection[]) phasesF.get(compilationUnit); -// LinkedList output = new LinkedList<>(); -// phases[Phases.OUTPUT] = output; -// output.add(new IGroovyClassOperation() { -// @Override -// public void call(GroovyClass gclass) { -// groovyClassesForThisTemplate.add(gclass); -// } -// }); - + // Play needs to handle writing the generated Groovy class to the file system but the Groovy + // compilation unit by default adds it's own output phase operation to do this that cannot + // be replaced using the available public methods. Until Groovy provides this capability + // it's necessary to access the compilation unit directly using reflection to replace the + // default output operation with the Play Groovy class handler. + Field phasesF = compilationUnit.getClass().getDeclaredField("phaseOperations"); + phasesF.setAccessible(true); + Collection[] phases = (Collection[]) phasesF.get(compilationUnit); + LinkedList output = new LinkedList<>(); + phases[Phases.OUTPUT] = output; + output.add(groovyClassesForThisTemplate::add); + compilationUnit.compile(); // ouf @@ -223,12 +211,15 @@ public void call(GroovyClass gclass) { message = message.substring(0, message.lastIndexOf('@')); } throw new TemplateCompilationException(this, line, message); - } else { - ExceptionMessage errorMessage = (ExceptionMessage) e.getErrorCollector().getLastError(); + } else if (errorMsg instanceof ExceptionMessage) { + ExceptionMessage errorMessage = ExceptionMessage.class.cast(errorMsg); Exception exception = errorMessage.getCause(); Integer line = 0; String message = exception.getMessage(); throw new TemplateCompilationException(this, line, message); + } else if (errorMsg instanceof SimpleMessage) { + SimpleMessage errorMessage = SimpleMessage.class.cast(errorMsg); + throw new TemplateCompilationException(this, null, errorMessage.getMessage()); } } throw new UnexpectedException(e); @@ -281,7 +272,7 @@ protected String internalRender(Map args) { // We have to set up the PrintWriter that this (and all sub-templates) are going // to write the output to.. applyLayouts = true; - layout.set(null); + layout.remove(); writer = new StringWriter(); binding.setProperty("out", new PrintWriter(writer)); currentTemplate.set(this); diff --git a/framework/src/play/templates/GroovyTemplateCompiler.java b/framework/src/play/templates/GroovyTemplateCompiler.java index 41e9234beb..78bfdb9d17 100644 --- a/framework/src/play/templates/GroovyTemplateCompiler.java +++ b/framework/src/play/templates/GroovyTemplateCompiler.java @@ -17,7 +17,7 @@ public class GroovyTemplateCompiler extends TemplateCompiler { - protected List extensionsClassnames = new ArrayList<>(); + protected final List extensionsClassnames = new ArrayList<>(); // [#714] The groovy-compiler complaints if a line is more than 65535 unicode units long.. // Have to split it if it is really that big @@ -79,7 +79,7 @@ protected String checkScalaCompatibility(String source) { originalNames.put(name, clazz.getName()); } } - Collections.sort(names, (o1, o2) -> o2.length() - o1.length()); + names.sort((o1, o2) -> o2.length() - o1.length()); // We're about to do many many String.replaceAll() so we do some // checking first diff --git a/framework/src/play/templates/TagContext.java b/framework/src/play/templates/TagContext.java index 4b2177aaf4..7793b6ab00 100644 --- a/framework/src/play/templates/TagContext.java +++ b/framework/src/play/templates/TagContext.java @@ -11,8 +11,8 @@ public class TagContext { private static final ThreadLocal> currentStack = new ThreadLocal<>(); - public String tagName; - public Map data = new HashMap<>(); + public final String tagName; + public final Map data = new HashMap<>(); public TagContext(String tagName) { this.tagName = tagName; diff --git a/framework/src/play/templates/TemplateCompiler.java b/framework/src/play/templates/TemplateCompiler.java index c8e6d7d2cd..be77c23ed7 100644 --- a/framework/src/play/templates/TemplateCompiler.java +++ b/framework/src/play/templates/TemplateCompiler.java @@ -28,12 +28,12 @@ public BaseTemplate compile(VirtualFile file) { return compile(new GroovyTemplate(file.relativePath(), file.contentAsString())); } - protected StringBuilder compiledSource = new StringBuilder(); + protected final StringBuilder compiledSource = new StringBuilder(); + protected final Stack tagsStack = new Stack<>(); protected BaseTemplate template; protected TemplateParser parser; protected boolean doNextScan = true; protected TemplateParser.Token state; - protected Stack tagsStack = new Stack<>(); protected int tagIndex; protected boolean skipLineBreak; protected int currentLine = 1; diff --git a/framework/src/play/templates/TemplateLoader.java b/framework/src/play/templates/TemplateLoader.java index 0982b25ad2..8a3c6b4582 100644 --- a/framework/src/play/templates/TemplateLoader.java +++ b/framework/src/play/templates/TemplateLoader.java @@ -17,12 +17,12 @@ public class TemplateLoader { - protected static Map templates = new HashMap<>(); + protected static final Map templates = new HashMap<>(); /** * See getUniqueNumberForTemplateFile() for more info */ - private static AtomicLong nextUniqueNumber = new AtomicLong(1000);// we start on 1000 - private static Map templateFile2UniqueNumber = Collections.synchronizedMap(new HashMap()); + private static final AtomicLong nextUniqueNumber = new AtomicLong(1000);// we start on 1000 + private static final Map templateFile2UniqueNumber = Collections.synchronizedMap(new HashMap()); /** * All loaded templates is cached in the templates-list using a key. This key is included as part of the classname diff --git a/framework/src/play/templates/TemplateParser.java b/framework/src/play/templates/TemplateParser.java index f5cf13298f..682dedb66b 100644 --- a/framework/src/play/templates/TemplateParser.java +++ b/framework/src/play/templates/TemplateParser.java @@ -5,7 +5,7 @@ */ public class TemplateParser { - private String pageSource; + private final String pageSource; private int nestedBracesCounter; // counts nested braces in current expression/tag public TemplateParser(String pageSource) { diff --git a/framework/src/play/test/Fixtures.java b/framework/src/play/test/Fixtures.java index e115c4b9b2..ceff21da2f 100644 --- a/framework/src/play/test/Fixtures.java +++ b/framework/src/play/test/Fixtures.java @@ -60,9 +60,9 @@ public class Fixtures { */ public static final String PROFILE_NAME = "Fixtures"; - static Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)"); + static final Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)"); // Allows people to clear the cache, so Fixture is not stateful - public static Map idCache = new HashMap<>(); + public static final Map idCache = new HashMap<>(); public static void executeSQL(String sqlScript) { for (CharSequence sql : new SQLSplitter(sqlScript)) { @@ -138,7 +138,7 @@ public static void deleteAll() { deleteDatabase(); } - static String[] dontDeleteTheseTables = new String[] { "play_evolutions" }; + static final String[] dontDeleteTheseTables = { "play_evolutions" }; /** * Flush the entire JDBC database @@ -540,8 +540,7 @@ static Map resolveDependencies(Class type, Map fields = new HashSet<>(); - Map resolvedYml = new HashMap<>(); - resolvedYml.putAll(yml); + Map resolvedYml = new HashMap<>(yml); // Look up the super classes Class clazz = type; diff --git a/framework/src/play/test/FunctionalTest.java b/framework/src/play/test/FunctionalTest.java index 330d5ff08e..53e3825f36 100644 --- a/framework/src/play/test/FunctionalTest.java +++ b/framework/src/play/test/FunctionalTest.java @@ -53,7 +53,7 @@ public abstract class FunctionalTest extends BaseTest { private static Map savedCookies; // cookies stored // between calls - private static Map renderArgs = new HashMap<>(); + private static final Map renderArgs = new HashMap<>(); @Before public void clearCookies() { @@ -626,7 +626,7 @@ protected static URL reverse() { public static class URL { - ActionDefinition actionDefinition; + final ActionDefinition actionDefinition; URL(ActionDefinition actionDefinition) { this.actionDefinition = actionDefinition; diff --git a/framework/src/play/test/Helpers.java b/framework/src/play/test/Helpers.java index 08361646c8..a1b6a5fee2 100644 --- a/framework/src/play/test/Helpers.java +++ b/framework/src/play/test/Helpers.java @@ -5,7 +5,7 @@ public class Helpers { - static Pattern pattern = Pattern.compile("^(\\w+)\\(\\s*(?:('(?:\\\\'|[^'])*'|[^.]+?)\\s*(?:,\\s*('(?:\\\\'|[^'])*'|[^.]+?)\\s*)?)?\\)$"); + static final Pattern pattern = Pattern.compile("^(\\w+)\\(\\s*(?:('(?:\\\\'|[^'])*'|[^.]+?)\\s*(?:,\\s*('(?:\\\\'|[^'])*'|[^.]+?)\\s*)?)?\\)$"); public static String[] seleniumCommand(String command) { Matcher matcher = pattern.matcher(command.trim()); diff --git a/framework/src/play/test/TestEngine.java b/framework/src/play/test/TestEngine.java index 37dbea0f72..17c3dea76b 100644 --- a/framework/src/play/test/TestEngine.java +++ b/framework/src/play/test/TestEngine.java @@ -39,7 +39,7 @@ public int compare(Class aClass, Class bClass) { private static final ClassNameComparator classNameComparator = new ClassNameComparator(); - public static ExecutorService functionalTestsExecutor = Executors.newSingleThreadExecutor(); + public static final ExecutorService functionalTestsExecutor = Executors.newSingleThreadExecutor(); public static List allUnitTests() { List classes = new ArrayList<>(); @@ -59,7 +59,7 @@ public static List allUnitTests() { } } } - Collections.sort(classes, classNameComparator); + classes.sort(classNameComparator); return classes; } @@ -68,17 +68,9 @@ public static List allFunctionalTests() { classes.addAll(Play.classloader.getAssignableClasses(FunctionalTest.class)); classes.addAll(Play.pluginCollection.getFunctionalTests()); - for (ListIterator it = classes.listIterator(); it.hasNext();) { - Class c = it.next(); - if (!Play.pluginCollection.shouldRunTest(c)) { - it.remove(); - } else { - if (Modifier.isAbstract(c.getModifiers())) { - it.remove(); - } - } - } - Collections.sort(classes, classNameComparator); + classes.removeIf(aClass -> Modifier.isAbstract(aClass.getModifiers())); + classes.removeIf(aClass ->!Play.pluginCollection.shouldRunTest(aClass)); + classes.sort(classNameComparator); return classes; } @@ -206,9 +198,9 @@ public static TestResults run(String name) { // ~~~~~~ Run listener static class Listener extends RunListener { - TestResults results; + final TestResults results; + final String className; TestResult current; - String className; public Listener(String className, TestResults results) { this.results = results; diff --git a/framework/src/play/utils/Default.java b/framework/src/play/utils/Default.java index 74bab120f5..0942879f91 100644 --- a/framework/src/play/utils/Default.java +++ b/framework/src/play/utils/Default.java @@ -2,7 +2,7 @@ public class Default { - Object o; + final Object o; public Default(Object o) { this.o = o; diff --git a/framework/src/play/utils/HTML.java b/framework/src/play/utils/HTML.java index 68bd2ac380..9099c737d4 100644 --- a/framework/src/play/utils/HTML.java +++ b/framework/src/play/utils/HTML.java @@ -110,7 +110,7 @@ public HtmlCharacterEntityReferences() { int index = (referredChar < 1000 ? referredChar : referredChar - 7000); String reference = entityReferences.getProperty(key); this.characterToEntityReferenceMap[index] = REFERENCE_START + reference + REFERENCE_END; - this.entityReferenceToCharacterMap.put(reference, new Character((char) referredChar)); + this.entityReferenceToCharacterMap.put(reference, (char) referredChar); } } diff --git a/framework/src/play/utils/Java.java b/framework/src/play/utils/Java.java index d718777d34..5fc7111f0e 100644 --- a/framework/src/play/utils/Java.java +++ b/framework/src/play/utils/Java.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.FutureTask; @@ -316,7 +317,7 @@ public static void findAllFields(Class clazz, Set found) { } /** cache */ - private static Map wrappers = new HashMap<>(); + private static final Map wrappers = new HashMap<>(); public static FieldWrapper getFieldWrapper(Field field) { if (wrappers.get(field) == null) { @@ -473,12 +474,7 @@ public boolean equals(Object o) { ClassAndAnnotation that = (ClassAndAnnotation) o; - if (annotation != null ? !annotation.equals(that.annotation) : that.annotation != null) - return false; - if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null) - return false; - - return true; + return Objects.equals(annotation, that.annotation) && Objects.equals(clazz, that.clazz); } @Override @@ -543,7 +539,7 @@ public List findAllAnnotatedMethods(Class clazz, Class methods, final Class annotationType) { try { final Method priority = annotationType.getMethod("priority"); - sort(methods, (m1, m2) -> { + methods.sort((m1, m2) -> { try { Integer priority1 = (Integer) priority.invoke(m1.getAnnotation(annotationType)); Integer priority2 = (Integer) priority.invoke(m2.getAnnotation(annotationType)); diff --git a/framework/src/play/utils/SmartFuture.java b/framework/src/play/utils/SmartFuture.java index bed603982a..a6e86246ba 100644 --- a/framework/src/play/utils/SmartFuture.java +++ b/framework/src/play/utils/SmartFuture.java @@ -42,7 +42,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution // Callbacks - private List> callbacks = new ArrayList<>(); + private final List> callbacks = new ArrayList<>(); private boolean invoked = false; private V result = null; diff --git a/framework/src/play/utils/Utils.java b/framework/src/play/utils/Utils.java index fd2aefffb6..a5b0f7ba84 100644 --- a/framework/src/play/utils/Utils.java +++ b/framework/src/play/utils/Utils.java @@ -175,11 +175,10 @@ public static void kill(String pid) throws Exception { public static class AlternativeDateFormat { - Locale locale; - List formats = new ArrayList<>(); + final List formats = new ArrayList<>(); + final Locale locale; public AlternativeDateFormat(Locale locale, String... alternativeFormats) { - super(); this.locale = locale; setFormats(alternativeFormats); } diff --git a/framework/src/play/vfs/VirtualFile.java b/framework/src/play/vfs/VirtualFile.java index 8cb4096287..95d55084e6 100644 --- a/framework/src/play/vfs/VirtualFile.java +++ b/framework/src/play/vfs/VirtualFile.java @@ -30,7 +30,7 @@ */ public class VirtualFile { - File realFile; + final File realFile; VirtualFile(File file) { this.realFile = file; diff --git a/framework/test-src/play/db/SQLSplitterTest.java b/framework/test-src/play/db/SQLSplitterTest.java index c1f2851cd9..ff6f226dde 100644 --- a/framework/test-src/play/db/SQLSplitterTest.java +++ b/framework/test-src/play/db/SQLSplitterTest.java @@ -2,6 +2,7 @@ import org.junit.*; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.File; @@ -110,11 +111,11 @@ public void verifyTestSplitting() throws Exception { CharSequence[] srcArr = new CharSequence[(int) srcArrList.size()]; srcArr = srcArrList.toArray(srcArr); - assertEquals(readFile("/play/db/test.out.sql").split("==="), srcArr); + assertArrayEquals(readFile("/play/db/test.out.sql").split("==="), srcArr); srcArrList = SQLSplitter.splitSQL(readFile("/play/db/test2.sql")); srcArr = new CharSequence[(int) srcArrList.size()]; srcArr = srcArrList.toArray(srcArr); - assertEquals(readFile("/play/db/test2.out.sql").split("==="), srcArr); + assertArrayEquals(readFile("/play/db/test2.out.sql").split("==="), srcArr); } } diff --git a/modules/crud/app/controllers/CRUD.java b/modules/crud/app/controllers/CRUD.java index f0294073e3..0b7b1a65c0 100644 --- a/modules/crud/app/controllers/CRUD.java +++ b/modules/crud/app/controllers/CRUD.java @@ -79,7 +79,7 @@ public static void attachment(String id, String field) throws Exception { Object att = object.getClass().getField(field).get(object); if(att instanceof Model.BinaryField) { Model.BinaryField attachment = (Model.BinaryField)att; - if (attachment == null || !attachment.exists()) { + if (!attachment.exists()) { notFound(); } response.contentType = attachment.type(); @@ -88,7 +88,7 @@ public static void attachment(String id, String field) throws Exception { // DEPRECATED if(att instanceof play.db.jpa.FileAttachment) { play.db.jpa.FileAttachment attachment = (play.db.jpa.FileAttachment)att; - if (attachment == null || !attachment.exists()) { + if (!attachment.exists()) { notFound(); } renderBinary(attachment.get(), attachment.filename); @@ -274,13 +274,13 @@ public Object getBlankAction() { public Long count(String search, String searchFields, String where) { - return factory.count(searchFields == null ? new ArrayList() : Arrays.asList(searchFields.split("[ ]")), search, where); + return factory.count(searchFields == null ? new ArrayList() : Arrays.asList(searchFields.split(" ")), search, where); } @SuppressWarnings("unchecked") public List findPage(int page, String search, String searchFields, String orderBy, String order, String where) { int offset = (page - 1) * getPageSize(); - List properties = searchFields == null ? new ArrayList(0) : Arrays.asList(searchFields.split("[ ]")); + List properties = searchFields == null ? new ArrayList(0) : Arrays.asList(searchFields.split(" ")); return Model.Manager.factoryFor(entityClass).fetch(offset, getPageSize(), orderBy, order, properties, search, where); } diff --git a/modules/docviewer/app/helpers/CheatSheetHelper.java b/modules/docviewer/app/helpers/CheatSheetHelper.java index 82df469eb5..f2675112b0 100644 --- a/modules/docviewer/app/helpers/CheatSheetHelper.java +++ b/modules/docviewer/app/helpers/CheatSheetHelper.java @@ -21,27 +21,18 @@ public static File[] getSheets(String category, String docLang) { } if (cheatSheetDir.exists() && cheatSheetDir.isDirectory()) { - File[] sheetFiles = cheatSheetDir.listFiles(new FileFilter() { - - public boolean accept(File pathname) { - return pathname.isFile() && pathname.getName().endsWith(".textile"); - } - }); + File[] sheetFiles = cheatSheetDir.listFiles(pathname -> pathname.isFile() && pathname.getName().endsWith(".textile")); // first letters of file name before "-" serves as sort index - Arrays.sort(sheetFiles, new Comparator() { - - public int compare(File f1, File f2) { - - String o1 = f1.getName(); - String o2 = f2.getName(); - - if (o1.contains("-") && o2.contains("-")) { - return o1.substring(0, o1.indexOf("-")) - .compareTo(o2.substring(0, o1.indexOf("-"))); - } else { - return o1.compareTo(o2); - } + Arrays.sort(sheetFiles, (f1, f2) -> { + String o1 = f1.getName(); + String o2 = f2.getName(); + + if (o1.contains("-") && o2.contains("-")) { + return o1.substring(0, o1.indexOf("-")) + .compareTo(o2.substring(0, o1.indexOf("-"))); + } else { + return o1.compareTo(o2); } }); @@ -73,18 +64,10 @@ public static String getCategoryTitle(String category) { public static Map listCategoriesAndTitles(String docLang) { String docLangDir = (docLang != null && (!"en".equalsIgnoreCase(docLang) && !docLang.matches("en-.*"))) ? "_" + docLang : ""; - File[] categories = new File(cheatSheetBaseDir + docLangDir).listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + File[] categories = new File(cheatSheetBaseDir + docLangDir).listFiles(File::isDirectory); if(categories==null || categories.length<=0){ - categories = cheatSheetBaseDir.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + categories = cheatSheetBaseDir.listFiles(File::isDirectory); } Arrays.sort(categories); diff --git a/modules/docviewer/app/helpers/LangMenuHelper.java b/modules/docviewer/app/helpers/LangMenuHelper.java index 20871145bc..3a7527ac76 100644 --- a/modules/docviewer/app/helpers/LangMenuHelper.java +++ b/modules/docviewer/app/helpers/LangMenuHelper.java @@ -20,12 +20,7 @@ public static List getMenuList() { defaultLangMenu.key = "en"; defaultLangMenu.value = "English"; langMenuList.add(defaultLangMenu); - File[] dirs = baseDir.listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return file.isDirectory() && ptn.matcher(file.getName()).find(); - } - }); + File[] dirs = baseDir.listFiles(file -> file.isDirectory() && ptn.matcher(file.getName()).find()); for (final File dir : dirs) { Matcher m = ptn.matcher(dir.getName()); String langCd = ""; diff --git a/modules/testrunner/src/play/modules/testrunner/FirePhoque.java b/modules/testrunner/src/play/modules/testrunner/FirePhoque.java index a2e2268b94..7713d4e0ef 100644 --- a/modules/testrunner/src/play/modules/testrunner/FirePhoque.java +++ b/modules/testrunner/src/play/modules/testrunner/FirePhoque.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -51,18 +52,18 @@ public static void main(String[] args) throws Exception { if(runUnitTests != null || runFunctionalTests != null || runSeleniumTests != null){ urlStringBuilder.append("?"); - urlStringBuilder.append("runUnitTests=").append(runUnitTests != null ? true : false); - System.out.println("~ Run unit tests:" + (runUnitTests != null ? true : false)); + urlStringBuilder.append("runUnitTests=").append(runUnitTests != null); + System.out.println("~ Run unit tests:" + (runUnitTests != null)); - urlStringBuilder.append("&runFunctionalTests=").append(runFunctionalTests != null ? true : false); - System.out.println("~ Run functional tests:" + (runFunctionalTests != null ? true : false)); + urlStringBuilder.append("&runFunctionalTests=").append(runFunctionalTests != null); + System.out.println("~ Run functional tests:" + (runFunctionalTests != null)); - urlStringBuilder.append("&runSeleniumTests=").append(runSeleniumTests != null ? true : false); - System.out.println("~ Run selenium tests:" + (runSeleniumTests != null ? true : false)); + urlStringBuilder.append("&runSeleniumTests=").append(runSeleniumTests != null); + System.out.println("~ Run selenium tests:" + (runSeleniumTests != null)); } try { - in = new BufferedReader(new InputStreamReader(new URL(urlStringBuilder.toString()).openStream(), "utf-8")); + in = new BufferedReader(new InputStreamReader(new URL(urlStringBuilder.toString()).openStream(), StandardCharsets.UTF_8)); String marker = in.readLine(); if (!marker.equals("---")) { throw new RuntimeException("Oops"); diff --git a/resources/module-skel/commands.py b/resources/module-skel/commands.py index 4e52a37288..8635fb2c2f 100644 --- a/resources/module-skel/commands.py +++ b/resources/module-skel/commands.py @@ -13,7 +13,7 @@ def execute(**kargs): env = kargs.get("env") if command == "%MODULE%:hello": - print "~ Hello" + print("~ Hello") # This will be executed before any command (new, run...)