diff --git a/.github/workflows/submit.yml b/.github/workflows/submit.yml index 99041df6e3b79cc23067a48ca0586ce98e73f2e0..acf46c615ce6e9f392bc929f8a4260a3eefcee8e 100644 --- a/.github/workflows/submit.yml +++ b/.github/workflows/submit.yml @@ -341,6 +341,7 @@ jobs: run: > if ! grep --include=test-summary.txt -lqr build/*/test-results -e "TEST SUCCESS" ; then cat build/*/test-results/*/text/newfailures.txt ; + cat build/*/test-results/*/text/other_errors.txt ; exit 1 ; fi @@ -807,6 +808,7 @@ jobs: run: > if ! grep --include=test-summary.txt -lqr build/*/test-results -e "TEST SUCCESS" ; then cat build/*/test-results/*/text/newfailures.txt ; + cat build/*/test-results/*/text/other_errors.txt ; exit 1 ; fi @@ -884,7 +886,7 @@ jobs: run: | New-Item -Force -ItemType directory -Path "$HOME\cygwin" & curl -L "https://www.cygwin.com/setup-x86_64.exe" -o "$HOME/cygwin/setup-x86_64.exe" - Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow + Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages cygwin=3.2.0-1,autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow - name: Checkout the source uses: actions/checkout@v2 @@ -973,7 +975,7 @@ jobs: run: | New-Item -Force -ItemType directory -Path "$HOME\cygwin" & curl -L "https://www.cygwin.com/setup-x86_64.exe" -o "$HOME/cygwin/setup-x86_64.exe" - Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow + Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages cygwin=3.2.0-1,autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow - name: Checkout the source uses: actions/checkout@v2 @@ -1145,7 +1147,7 @@ jobs: run: | New-Item -Force -ItemType directory -Path "$HOME\cygwin" & curl -L "https://www.cygwin.com/setup-x86_64.exe" -o "$HOME/cygwin/setup-x86_64.exe" - Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow + Start-Process -FilePath "$HOME\cygwin\setup-x86_64.exe" -ArgumentList "--quiet-mode --packages cygwin=3.2.0-1,autoconf,make,zip,unzip --root $HOME\cygwin\cygwin64 --local-package-dir $HOME\cygwin\packages --site http://mirrors.kernel.org/sourceware/cygwin --no-desktop --no-shortcuts --no-startmenu --no-admin" -Wait -NoNewWindow - name: Restore jtreg artifact id: jtreg_restore @@ -1218,6 +1220,7 @@ jobs: run: > if ((Get-ChildItem -Path build\*\test-results\test-summary.txt -Recurse | Select-String -Pattern "TEST SUCCESS" ).Count -eq 0) { Get-Content -Path build\*\test-results\*\*\newfailures.txt ; + Get-Content -Path build\*\test-results\*\*\other_errors.txt ; exit 1 } @@ -1611,6 +1614,7 @@ jobs: run: > if ! grep --include=test-summary.txt -lqr build/*/test-results -e "TEST SUCCESS" ; then cat build/*/test-results/*/text/newfailures.txt ; + cat build/*/test-results/*/text/other_errors.txt ; exit 1 ; fi diff --git a/.hgtags b/.hgtags deleted file mode 100644 index ef4ec35e2f27ed951ce5306b393547235e25a97f..0000000000000000000000000000000000000000 --- a/.hgtags +++ /dev/null @@ -1,664 +0,0 @@ -3cc80be736f24704e505ad8ddaa598dec3fa2ed3 jdk-9+181 -e2b70be325bd10dae4c06f74c46d70d480854916 jdk-9+179 -5b16a1c3ccffff2a82c88bb7ea894c4ff1c9ebde jdk-9+180 -43bf6f30fcba031ecf0cc7e511efe3a8179d0f77 jdk-9+176 -d9f6bc6ba599d0487dc18b2fbdb6c34eedf6f958 jdk-9+177 -bc9df7dd63ec76f50fafeb4acc44465044662f0a jdk-9+178 -994036e74ab805bcc09afa0646be17a725bec42f jdk-9+175 -94680c6d60ecd9ed3ffd1847706efde7eb947afc jdk-9+174 -6dd7fda42bab7ecf648cafb0a4e9b4ca11b3094f jdk-9+173 -dad6746278facbbea57dd462cb56fb743dc0a5f0 jdk-9+172 -643b5f18c2656fe91b69fea85b07b98d5fad394d jdk-9+171 -898cbe31fbdae2d25d141384fac746cc244a730c jdk-9+170 -c7efde2b60fc1ec04630be769d9ad60efb39c39c jdk-9+169 -8fd0a4569191f33c98ee90c2709174a342fefb0d jdk-9+167 -fcabc74bd44e56c7419d111d59b95669ecb33c55 jdk-9+168 -d3e973f1809606c67412361041ad197e50fe8cec jdk-9+166 -3965b747cfe1e6cbd66b8739da5a1ea6ec6985e9 jdk-9+165 -d16aebbb56d37f12e0c0b0a4fb427db65e1fb1a8 jdk-9+162 -18c41483a082e097ac2f5f983c1226ed94aa4215 jdk-9+163 -32db52c675e7d5bc413605d2e89b68b608b19be0 jdk-9+164 -fd1497902bbe3aa24b21f270ecdcb8de5f7aa9ac jdk-9+159 -6aa8be0c4e054fe8b3ab016ae00d16d680f92145 jdk-9+160 -f6883b1a5a6478437cd4181c4bd45328ab24feaf jdk-9+161 -fa3e76b477829afc4476f0b725cfaa440a6fd917 jdk-9+157 -b5015f742ba648184bb7fc547197bd33ebfde30d jdk-9+158 -1cc8dd79fd1cd13d36b385196271a29632c67c3b jdk7-b24 -bf2517e15f0c0f950e5b3143c4ca11e2df73dcc1 jdk7-b25 -5ae7db536e3fcf6be78e45b240a9058095e0ed38 jdk7-b26 -67052ac87fc927d048e62ec54ff42adb230d3f7c jdk7-b27 -18dc4ba4739a537fd146f77da51db16efce28da2 jdk7-b28 -bfe4572fd301a6fcd120373cdb2eff5d2da0c72c jdk7-b29 -bee4731164a06ddece1297ae58db24aca6a1c626 jdk7-b30 -cd8b8f500face60d1566d850857a7fccadbd383a jdk7-b31 -a9f1805e3ba9ca520cad199d522c84af5433e85a jdk7-b32 -6838c1a3296aaa3572364d2ce7d70826cee96286 jdk7-b33 -90cf935adb353bb0af4b46fb0677e841fd24c000 jdk7-b34 -6d909d5803e3a22850e6c4e5a75b888742ee7e20 jdk7-b35 -d718a441936196b93d8bc9f084933af9a4c2a350 jdk7-b36 -c2036bf76829c03b99108fffab52e20910a9be4f jdk7-b37 -a2879b2837f5a4c87e9542efe69ef138194af8ff jdk7-b38 -126f365cec6c3c2c72de934fa1c64b5f082b55b5 jdk7-b39 -3c53424bbe3bb77e01b468b4b0140deec33e11fc jdk7-b40 -3cb2a607c347934f8e7e86f840a094c28b08d9ea jdk7-b41 -caf58ffa084568990cbb3441f9ae188e36b31770 jdk7-b42 -41bd0a702bc8ec6feebd725a63e7c3227f82ab11 jdk7-b43 -5843778bda89b1d5ac8e1aa05e26930ac90b3145 jdk7-b44 -54dffad0bf066791a2793305875250c395011d5f jdk7-b45 -04b2620edc72de93671646e4720c5992c74ac8b5 jdk7-b46 -0c4657194eec95c08ba478aee9cfc3c295e41657 jdk7-b47 -1bf51a4c2627c2f0e0cbcc2cf0421bdb37f1f2b2 jdk7-b48 -6b84b04a80afe23262377c60913eebfc898f14c4 jdk7-b49 -5da0e6b9f4f18ef483c977337214b12ee0e1fc8f jdk7-b50 -a25c5ec5e40e07733d1ff9898a0abe36159288ff jdk7-b51 -7a90e89e36d103038f8667f6a7daae34ecfa1ad8 jdk7-b52 -d52186ee770dac57950536cd00ccbfdef360b04c jdk7-b53 -15096652c4d48dfb9fc0b2cb135304db94c65ba0 jdk7-b54 -c8b275d62d6b0a980c510e839b70292245863e85 jdk7-b55 -a8134c4ee2cf451cf9b5e1609f39d83ecd53acc5 jdk7-b56 -b44f05654c26fcd1f995e712992f9b07ffd7c0c6 jdk7-b57 -d60a9ce3c3eabf28f5d50ae839d18be04a551bc2 jdk7-b58 -c33e7d38c9210741dbc285507403a4b20bd802a0 jdk7-b59 -5a10e4d0b14d7beac53a7b2213ae6864afe1fd3e jdk7-b60 -dbb955b1ee59b876dd1f133952b557b48b1d7732 jdk7-b61 -6107cbff3130c747d243c25a7874cd59db5744a8 jdk7-b62 -dfd8506f74c3731bb169ce93c72612d78ee0413b jdk7-b63 -d22867c5f1b295a0a2b3b4bc8999a2676f6e20c3 jdk7-b64 -7d3bf00f3cc4f8125de1842521e7567f37dc84b8 jdk7-b65 -62109d1b9e7310f29ab51ca6f1d71b899c0ce6b0 jdk7-b66 -eb24af1404aec8aa140c4cd4d13d2839b150dd41 jdk7-b67 -bca2225b66d78c4bf4d9801f54cac7715a598650 jdk7-b68 -1b662b1ed14eb4ae31d5138a36c433b13d941dc5 jdk7-b69 -207f694795c448c17753eff1a2f50363106960c2 jdk7-b70 -c5d39b6be65cba0effb5f466ea48fe43764d0e0c jdk7-b71 -df4bcd06e1d0ab306efa5a44f24a409dc0c0c742 jdk7-b72 -ce74bd35ce948d629a356e168797f44b593b1578 jdk7-b73 -4e7661eaa211e186674f6cbefec4aef1144ac2a0 jdk7-b74 -946518568340c4e511549318f19f47f06b7f5f9b jdk7-b75 -09e0b33177af2b98a03c9ca19eedf61440bd1cf6 jdk7-b76 -1d0121b741f029dc4b828e4b36ba6fda92907dd7 jdk7-b77 -4061c66ba1af1a2e27c2c839ba887407dd3ce050 jdk7-b78 -e9c98378f6b9256c0595ef2985ca5899f0c0e274 jdk7-b79 -e6abd38682d237306d6c147c17538ec9e7f8e3a7 jdk7-b80 -dcc938ac40cc45f1ef454d76020b5db5d943001c jdk7-b81 -a30062be6d9ca1d48579826f870f85974300004e jdk7-b82 -34c8199936a1682aa8587857f44cfaf37c2b6381 jdk7-b83 -b1e55627a6980b9508854ed0c0f21d4f981b4494 jdk7-b84 -b6f633a93ae0ec4555ff4bf756f5e2150c9bdede jdk7-b85 -c94d9cc81f495d97817eba9d71b84fc45f7661a5 jdk7-b86 -b7456c473862048fa70ed8092313a4ef0a55d403 jdk7-b87 -7077b95d42f6b3942a8751bba033801ff50e5889 jdk7-b88 -44158f6d3b94c0fa020e33632532473d92d1ea96 jdk7-b89 -1d1927f9ec097b62c913921e2dfa5dbaf5dc325b jdk7-b90 -308ad8f68b8dd68e22d73dd490e110059b732422 jdk7-b91 -ff9031a745d9cc52318f2148e43ca3b07ee08098 jdk7-b92 -b5dab6a313fdff4c043250e4d9c8f66fd624d27e jdk7-b93 -8bb281f0f91582104d65d032be22522bfd2d8110 jdk7-b94 -654298d26561b76dfe3cfcffbbd7078080837300 jdk7-b95 -d260f892491e040ae385a8e6df59557a7d721abf jdk7-b96 -7e406ebed9a5968b584f3c3e6b60893b5d6d9741 jdk7-b97 -db6e660120446c407e2d908d52ec046592b21726 jdk7-b98 -c4c8a5bc54f66abc68cd185d9294042121922154 jdk7-b99 -2d6ba7a221915bdf0311acc5641c7f3875cb793e jdk7-b100 -2548ac036b8fca3326d058d758e6df8355a42469 jdk7-b101 -88db80c8e49cea352c2900f689600dc410761c1f jdk7-b102 -64770970865839b0443066370e7d476ef47e90cd jdk7-b103 -10bc903a228d3a8efdf46fb8c3fcf82a59b88bc5 jdk7-b104 -1ce7938efb03224ccc8b3cdd7803eb39e889539c jdk7-b105 -6bdae472f77205046703b685eff2ac4f7a0ecf4e jdk7-b106 -439de530aac531a360beedba6e2fe51e17292cc0 jdk7-b107 -044d31b99ef5609389fc771c422e722e5e224228 jdk7-b108 -e02b4d709e177d08d56130a4bc68061e4bbacc7d jdk7-b109 -a6442d6bc38a44152e0662688213ce4d2701f42a jdk7-b110 -69f3edf083477955b5bd2f754252c7504167d8e1 jdk7-b111 -f960f117f1623629f64203e2b09a92a8f6f14ff5 jdk7-b112 -1fee41c7ed2b3388970a756a85aa693c0de8407a jdk7-b113 -750c1ccb2f2d1ddfa95ab6c7f897fdab2f87f7e9 jdk7-b114 -9cb24917216bc68997154f6e9566c3de62acb2f4 jdk7-b115 -a4e6aa1f45ad23a6f083ed98d970b5006ea4d292 jdk7-b116 -228e73f288c543a8c34e2a54227103ae5649e6af jdk7-b117 -2e876e59938a853934aa738c811b26c452bd9fe8 jdk7-b118 -4951967a61b4dbbf514828879f57bd1a0d4b420b jdk7-b119 -8c840d3ab24f8d0f422b991638acb44b6ab1d98c jdk7-b120 -0ce0a2c3a6926677dc507839a820ab6625541e5a jdk7-b121 -6f09ea1c034f087916d2a8cf0d22be768400118f jdk7-b122 -142129d8599d1f56b29387e7f9a5fad53b6d61df jdk7-b123 -aa894c225b1a517b665ac2a58295217ea2245134 jdk7-b124 -f658ec2730fa29323c36d23c27e54c7219ef5e16 jdk7-b125 -f1df068076986679ea1105532a65529d63a89060 jdk7-b126 -f83cd8bd35c678f94e526990e03dc838d0ec2717 jdk7-b127 -7da3f5f30855dec6bf3a86529e87dee883b90c72 jdk7-b128 -6823ea7eb8eb6fab405d7edb7a5c2f690887a2fa jdk7-b129 -a36beda9b9de91231d92a2c529f21cc218fcf8d5 jdk7-b130 -d8af56da89bc0fc02a6b6ad78f51157a46d665ab jdk7-b131 -d61280d36755d1941fb487f554e8b7a6d0bca6a1 jdk7-b132 -fd444c61e7ed3d92b2a730da7c737b02191b682f jdk7-b133 -def8e16dd237a47fc067d66d4c616d7baaec6001 jdk7-b134 -f75a1efb141210901aabe00a834e0fc32bb8b337 jdk7-b135 -46acf76a533954cfd594bb88fdea79938abfbe20 jdk7-b136 -d1cf7d4ee16c341f5b8c7e7f1d68a8c412b6c693 jdk7-b137 -62b8e328f8c8c66c14b0713222116f2add473f3f jdk7-b138 -955488f34ca418f6cdab843d61c20d2c615637d9 jdk7-b139 -f4298bc3f4b6baa315643be06966f09684290068 jdk7-b140 -5d86d0c7692e8f4a58d430d68c03594e2d3403b3 jdk7-b141 -92bf0655022d4187e9b49c1400f98fb3392a4630 jdk7-b142 -4a05062d8c4dfa3edec3faf1052af28baba5adff jdk7-b143 -07a8728ad49ef6dfa469c3a8bf5ab1e9c80bed5c jdk7-b144 -8294c99e685a1f6d1d37c45cd97854cf74be771e jdk7-b145 -dca1e8a87e8f756f95b99bac8fe795750d42e1b0 jdk7-b146 -a2a589fc29543ed32919c78a1810ad93a6fcf5bc jdk7-b147 -de9223c94f9c710b3eebb599cd3586f36c8b94a9 jdk8-b01 -1b9d19620eb4606a25b1e28f86d66c8bfa867e06 jdk8-b02 -6815e85bf96d6d3875954f9777660372cd70d065 jdk8-b03 -31f5c34d78081572ad9a2401c0bb0c6b9711dd65 jdk8-b04 -c4f9ea1ecb55ff44e0dd21d2888ead308c86a3aa jdk8-b05 -429da7734bf491bccde2a752fae97e9f225896dc jdk8-b06 -bc5710332b294676661103bb20d47d2ea3ba8def jdk8-b07 -24ee504f80412770c6874836cd9e55b536427b1d jdk8-b08 -fbf3cabc9e3bb1fcf710941d777cb0400505fbe6 jdk8-b09 -f651ce87127980c58e3599daba964eba2f3b4026 jdk8-b10 -cc1f5ce8e504d350e0b0c28c5f84333f8d540132 jdk8-b11 -86db042b3385c338e17f7664447fdc7d406dd19e jdk8-b12 -4cc0ef72c812943743ef4765f1100e2fbe2b1a08 jdk8-b13 -9ffaa48dbfb0f5936c2b789867d0785faec7071d jdk8-b14 -b5060eae3b32fd9f884a09774338cd8186d7fafa jdk8-b15 -736a63b854f321c7824b7e47890135f80aee05e3 jdk8-b16 -f0eccb2946986fb9626efde7d8ed9c8192623f5c jdk8-b17 -885050364691ac1ac978305c63f3368a197fb04d jdk8-b18 -0ff7113a0882ec82d642cb9f0297b4e497807ced jdk8-b19 -6561530ea757c3f3a6fb171c9cc7b3885cdeca85 jdk8-b20 -b3a426170188f52981cf4573a2f14d487fddab0d jdk8-b21 -e8f03541af27e38aafb619b96863e17f65ffe53b jdk8-b22 -498124337041ad53cbaa7eb110f3d7acd6d4eac4 jdk8-b23 -7d3720d8c595d1519c31e9ff7366203fc2c61350 jdk8-b24 -0071a6d64113a35ba345bb1580c256de5ce17d3e jdk8-b25 -6c805d8ed4e5449ea5e4d158c7bdbd7b0b70efd1 jdk8-b26 -c51754cddc037b9609e202b9ed38363d8683e7a8 jdk8-b27 -16ba58282d117247f480aae7a79b88141ade52a3 jdk8-b28 -e070119aa56ee4dc5506c19d2c4d2eecab8ad429 jdk8-b29 -23da7804aca0c9c4e6e86532a1453125a76d95ee jdk8-b30 -bac81e9f7d57b75fba5ab31b571f3fe0dc08af69 jdk8-b31 -2c5208ccb863db936eab523f49450b3fcd230348 jdk8-b32 -a6e6d42203e6d35f9e8b31eac25b0021b4dd58ad jdk8-b33 -0ae89825c75c9492e44efb3aca3d9ee3d8a209df jdk8-b34 -f151d5833912a82cd4f203944da0305c3be83ecc jdk8-b35 -98ce9816ae089c959ba1e70fba98423a31c4e9fa jdk8-b36 -b3a91113026c99b0da010d41055719ab0d8938f0 jdk8-b37 -4cc5610a6dd6227da766ebf9742eb11ff5ded6c0 jdk8-b38 -35a5397278779a2f8f3013f81586dc8f30cb149d jdk8-b39 -6e4e654931b976304bf6e7b4d0d6db8f75bac5d9 jdk8-b40 -c029c972396cea042a0dc67c0f7ccf2fe68007d4 jdk8-b41 -5c5a64ec0839df5affe9394b99ff338c363acbca jdk8-b42 -69d8a827cdf9236be9694a46d75c710d71dac7d7 jdk8-b43 -7e981cb0ad6a194f1fa859f9ad47586db461f269 jdk8-b44 -9b19b2302c28f4da6d4078f66234abecfed5688a jdk8-b45 -600c9a1feb01633cbcf2341a43d1d21e6497ecd0 jdk8-b46 -b820143a6f1ce993c6e6f31db4d64de990f42654 jdk8-b47 -086271e35b0a419b38e8bda9bebd70693811df0a jdk8-b48 -cecd7026f30cbd83b0601925a7a5e059aec98138 jdk8-b49 -38fe5ab028908cf64dd73a43336ba3211577bfc3 jdk8-b50 -382651d28f2502d371eca751962232c0e535e57a jdk8-b51 -b67041a6cb508da18d2f5c7687e6a31e08bea4fc jdk8-b52 -c7aa5cca1c01689a7b1a92411daf83684af05a33 jdk8-b53 -7c6aa31ff1b2ae48c1c686ebe1aadf0c3da5be15 jdk8-b54 -319f583f66db47395fa86127dd3ddb729eb7c64f jdk8-b55 -ffe6bce5a521be40146af2ac03c509b7bac30595 jdk8-b56 -2c21c080b11b93efb3851e39e1363e45da805943 jdk8-b57 -479d3302a26d7607ba271d66973e59ebf58825b6 jdk8-b58 -3bd874584fc01aae92fbc8827e2bd04d8b6ace04 jdk8-b59 -5e3adc681779037a2d33b7be6f75680619085492 jdk8-b60 -cdaa6122185f9bf512dcd6600f56bfccc4824e8c jdk8-b61 -8d9d430b4244b95f5cf1ebe719f834a1ac5d6cd5 jdk8-b62 -21ee1dd7b809639284900a128b9b656a592ebc7a jdk8-b63 -70fa4b11f26522e69b51fd652215f60ce350bac3 jdk8-b64 -a2cf4d4a484378caea2e827ed604b2bbae58bdba jdk8-b65 -17820b958ae84f7c1cc6719319c8e2232f7a4f1d jdk8-b66 -76cc9bd3ece407d3a15d3bea537b57927973c5e7 jdk8-b67 -cb33628d4e8f11e879c371959e5948b66a53376f jdk8-b68 -adb5171c554e14cd86f618b5584f6e3d693d5889 jdk8-b69 -0d625373c69e2ad6f546fd88ab50c6c9aad01271 jdk8-b70 -a41ada2ed4ef735449531c6ebe6cec593d890a1c jdk8-b71 -6725b3961f987cf40f446d1c11cd324a3bec545f jdk8-b72 -fe94b40ffd9390f6cffcdf51c0389b0e6dde0c13 jdk8-b73 -f627eff819628822a0777af8062244352f2a29cf jdk8-b74 -f1478a6d25fddd311a84dcbfac50824cc1858bdd jdk8-b75 -f407160c280d1c5b00d314c535441ac26f195fee jdk8-b76 -d17eb2e13e362085e866d46235314c50cc4661cc jdk8-b77 -6d3dcd34b5b962ea1ef9eed0dafdee9e812401bc jdk8-b78 -a1313a8d90d17d363a3b2a645dc4030ec204b168 jdk8-b79 -3fa21fbf9be7e6b482af43aacb6a09acfa30bdb6 jdk8-b80 -e41d716405b209d3eddef8bd4240cec2bd34dcca jdk8-b81 -5e8c55025644730385a6f8fa029ecdb2d2c98a07 jdk8-b82 -bcebd3fdefc91abb9d7fa0c5af6211b3f8720da6 jdk8-b83 -d7ad0dfaa41151bd3a9ae46725b0aec3730a9cd0 jdk8-b84 -1872c12529090e1c1dbf567f02ad7ae6231b8f0c jdk8-b85 -da9a4c9312816451884aa6db6f18be51a07bff13 jdk8-b86 -5ebf6c63714de2c9dcf831074086d31daec819df jdk8-b87 -e517701a4d0e25ae9c7945bca6e1762a8c5d8aa6 jdk8-b88 -4dec41b3c5e3bb616f0c6f15830d940905aa5d16 jdk8-b89 -f09ab0c416185e3cba371e81bcb6a16060c90f44 jdk8-b90 -80b6c3172dc2cfceb022411292d290a967f9c728 jdk8-b91 -2fd6acba737b01e705e1f7c33588c922a3787f13 jdk8-b92 -b72ae39e1329fefae50d4690db4fde43f3841a95 jdk8-b93 -0d804e3b955dce406af6a79ac1cc35c696aff7fb jdk8-b94 -49fe9c8049132647ad38837a877dd473e6c9b0e5 jdk8-b95 -ea73f01b9053e7165e7ba80f242bafecbc6af712 jdk8-b96 -0a85476a0b9cb876d5666d45097dac68bef3fce1 jdk8-b97 -711eb4aa87de68de78250e0549980936bab53d54 jdk8-b98 -2d3875b0d18b3ad1c2bebf385a697e309e4005a4 jdk8-b99 -3d34036aae4ea90b2ca59712d5a69db3221f0875 jdk8-b100 -edb01c460d4cab21ff0ff13512df7b746efaa0e7 jdk8-b101 -bbe43d712fe08e650808d774861b256ccb34e500 jdk8-b102 -30a1d677a20c6a95f98043d8f20ce570304e3818 jdk8-b103 -b5ed503c26ad38869c247c5e32debec217fd056b jdk8-b104 -589f4fdc584e373a47cde0162e9eceec9165c381 jdk8-b105 -514b0b69fb9683ef52062fd962a3e0644431f64d jdk8-b106 -892889f445755790ae90e61775bfb59ddc6182b5 jdk8-b107 -74049f7a28b48c14910106a75d9f2504169c352e jdk8-b108 -af9a674e12a16da1a4bd53e4990ddb1121a21ef1 jdk8-b109 -b5d2bf482a3ea1cca08c994512804ffbc73de0a1 jdk8-b110 -b9a0f6c693f347a6f4b9bb994957f4eaa05bdedd jdk8-b111 -ad67c34f79c28a8e755f4a49f313868619d6702c jdk8-b112 -4a4dbcf7cb7d3e1a81beaa3b11cd909f69ebc79a jdk8-b113 -dfa34ab293faad9b543a24646dbb381bc3ab5586 jdk8-b114 -3dd9732b17034f45d111996d1d50287b05a3998c jdk8-b115 -aaf663f591aba43ec942263b15ba62759ce26a1e jdk8-b116 -31b0e03fcad73d7886b306b4c2e57ad270780d0d jdk8-b117 -f5b521ade7a35cea18df78ee86322207729f5611 jdk8-b118 -87b743b2263cc53955266411b7797b365a0fb050 jdk8-b119 -a1ee9743f4ee165eae59389a020f2552f895dac8 jdk8-b120 -13b877757b0b1c0d5813298df85364f41d7ba6fe jdk9-b00 -f130ca87de6637acae7d99fcd7a8573eea1cbaed jdk9-b01 -b32e2219736e42baaf45daf0ad67ed34f6033799 jdk9-b02 -7f655f31f9bcee618cf832f08176ad8c1ed3fdd3 jdk9-b03 -099891b1d86f3719e116ac717ffdafc90d037fb7 jdk9-b04 -dd311791ad6895a3989020dd6c6c46db87972ab8 jdk9-b05 -85dbdc227c5e11429b4fc4a8ba763f50107edd6e jdk9-b06 -c826d05f1fb0773f6a28caa763307dd30d90d36e jdk9-b07 -b47e021195757f8f45582124ea7cad48ccf5f872 jdk9-b08 -efe7dbc6088691757404e0c8745f894e3ca9c022 jdk9-b09 -8c0bdeecd7c0f9ce3f3762a51991f755cb3a972c jdk9-b10 -0809c9a4d36e6291f1c4384604c4bbf29e975722 jdk9-b11 -0d1f816217dce5e72187f167cc1816080cbeb453 jdk9-b12 -1a30593dcb9802faec3b6edb24d86ca088594e4e jdk9-b13 -97932f6ad950ae5a73a9da5c96e6e58503ff646b jdk9-b14 -74eb0778e4f2dbff6628e718378449fba27c4265 jdk9-b15 -4a09f5d30be844ac6f714bdb0f63d8c3c08b9a98 jdk9-b16 -410bccbded9e9cce80f1e13ad221e37ae97a3986 jdk9-b17 -c5495e25c7258ab5f96a1ae14610887d76d2be63 jdk9-b18 -2dcf544eb7ed5ac6a3f7813a32e33acea7442405 jdk9-b19 -89731ae72a761afdf4262e8b9513f302f6563f89 jdk9-b20 -28dd0c7beb3cad9cf95f17b4b5ad87eb447a4084 jdk9-b21 -9678e0db8ff6ed845d4c2ee4a3baf7f386a777e5 jdk9-b22 -39cfdc2dcaf3f195c55398e4e677ab053b07e3d2 jdk9-b23 -d9ce05f36ffec3e5e8af62a92455c1c66a63c320 jdk9-b24 -13a5c76976fe48e55c9727c25fae2d2ce7c05da0 jdk9-b25 -cd6f4557e7fea5799ff3762ed7a80a743e75d5fd jdk9-b26 -d06a6d3c66c08293b2a9650f3cc01fd55c620e65 jdk9-b27 -f4269e8f454eb77763ecee228a88ae102a9aef6e jdk9-b28 -c36c0092693707a8255561433647e8c3cd724ccd jdk9-b29 -b2287cac7813c70ed7f679d9a46fe774bd4005f8 jdk9-b30 -9d0e6639a4d71b63507dd94b1a028e963b27e798 jdk9-b31 -1b1ec4291abc0ba6da7bf79b754f08dd759a4a0c jdk9-b32 -f0c5e4b732da823bdaa4184133675f384e7cd68d jdk9-b33 -9618201c5df28a460631577fad1f61e96f775c34 jdk9-b34 -a137992d750c72f6f944f341aa19b0d0d96afe0c jdk9-b35 -41df50e7303daf73c0d661ef601c4fe250915de5 jdk9-b36 -b409bc51bc23cfd51f2bd04ea919ec83535af9d0 jdk9-b37 -948cceef81ba4cb34bc233e7cc5952951ff04e88 jdk9-b38 -4e7c4d692e934cb9023af8201e7c2b510e9c4ee1 jdk9-b39 -82f4cb44b2d7af2352f48568a64b7b6a5ae960cd jdk9-b40 -9fffb959eb4197ff806e4ac12244761815b4deee jdk9-b41 -3107be2ba9c6e208a0b86bc7100a141abbc5b5fb jdk9-b42 -6494b13f88a867026ee316b444d9a4fa589dd6bd jdk9-b43 -abbfccd659b91a7bb815d5e36fed635dcdd40f31 jdk9-b44 -bfc24ae2b900187585079bb11e66e459d1e525fe jdk9-b45 -722378bc599e38d9a1dd484de30f10dfd7b21438 jdk9-b46 -8327024a99559982b848e9c2191da9c0bf8838fd jdk9-b47 -b2f9702efbe95527ea3a991474fda23987ff1c5c jdk9-b48 -5b8db585a33c3cc48e70e688ceee57dd9271dc5d jdk9-b49 -1550b2f6b63d1411fa84dc7bbc6f04809aedb43f jdk9-b50 -6efe265424e3f1ea596408a1f71baf2de316c772 jdk9-b51 -d6224d6021459ac8b3832e822f5acc849fa944af jdk9-b52 -874d76e4699dfcd61ae1826c9fe0ddc1610ad598 jdk9-b53 -82cd31c5d6ca8d4c1653f4eb1c09eb2d9a3b2813 jdk9-b54 -c97e2d1bad9708d379793ba2a4c848eda14c741e jdk9-b55 -47544495db2d3d2edf0f85862d8715592fdb919f jdk9-b56 -ddb95d8f169b09544cc17e72a6baaff2400092f5 jdk9-b57 -f40752db7773ca0c737f2ad88371e35c57fdfed7 jdk9-b58 -da950f343762a856d69751570a4c07cfa68a415b jdk9-b59 -38f98cb6b33562a926ec3b79c7b34128be37647d jdk9-b60 -ac3f5a39d4ff14d70c365e12cf5ec8f2abd52a04 jdk9-b61 -e7dbbef69d12b6a74dfad331b7188e7f893e8d29 jdk9-b62 -989253a902c34dcb7564695161c9200a5fbb7412 jdk9-b63 -8ffdeabc7c2b9a8280bf46cae026ac46b4d31c26 jdk9-b64 -4915246064b2f89d5f00c96e758686b7fdad36a6 jdk9-b65 -ff3fc75f3214ad7e03595be1b0d0f38d887b6f0e jdk9-b66 -56166ce66037952fa21e9f680b31bf8eb47312c0 jdk9-b67 -5b500c93ce4822d47061cd518ff3f72d9d8cb5b5 jdk9-b68 -d69c968463f0ae5d0b45de3fc14fe65171b23948 jdk9-b69 -43d0179ee9de3bfffae3417f09e07eb6d8efc963 jdk9-b70 -f66c185284727f6e6ffd27e9c45ed2dd9da0a691 jdk9-b71 -61d2d0629b6dbf4c091dc86151ade1b3ef34fffe jdk9-b72 -9b3a9d72f07b40c648de79961679f42283af1bb5 jdk9-b73 -7c577fda1855d03c04546694d514678f596508c9 jdk9-b74 -f55df5cfe11c97e4b58998b76f5bd00a73cde12d jdk9-b75 -eeea9adfd1e3d075ef82148c00a4847a1aab4d26 jdk9-b76 -c25e882cee9622ec75c4e9d60633539a2f0a8809 jdk9-b77 -c8753d0be1778944dc512ec86a459941ea1ad2c3 jdk9-b78 -3966bd3b8167419aa05c6718a4af1cf54b1e3c58 jdk9-b79 -3c9f5bd909ae7187f24622ee4b69f8a5756a9271 jdk9-b80 -2050b3a0aadcb0e024bf798197421d58e54ec8bf jdk9-b81 -6521875cb63e1d0121b30af56ebbc36db078c4c6 jdk9-b82 -f61a63b7d1e52e307abc0bfc751203155d362ec4 jdk9-b83 -51b2db2fa04c16d767b66113dbf08c5349ce382a jdk9-b84 -8392405ab038b22e69a3728e17dbdd9e3d3a22ed jdk9-b85 -7db0663a5e968059fa7c772172187ebd60b6492d jdk9-b86 -1a52a30674cd28c24d4d388150336121f2e9ddf9 jdk9-b87 -16b4968f9bb8f34371b42c0ba483d76e91ba84d8 jdk9-b88 -4a0312f2894bcbe1fd20266c8fda8d983bd2fcf6 jdk9-b89 -d131f4b8433a79408f935eff9bf92a0664229b60 jdk9-b90 -8077fd2f055d31e50b46fcf62d9c035bc385a215 jdk9-b91 -f242d4332f563648426a1b0fa02d8741beba19ef jdk9-b92 -09206c6513b300e1ac8541f3be012e1a49312104 jdk9-b93 -25a2cab05cfbe6034b71d9e72d64c65b0572ce63 jdk9-b94 -5ac6287ec71aafe021cc839d8bc828108d23aaba jdk-9+95 -139f19d70350238e15e107945cea75082b6380b3 jdk-9+96 -4edcff1b9a8875eb6380a2165dfec599e8e3f7c0 jdk-9+97 -d00ad2d9049ac60815f70bff445e95df85648bd2 jdk-9+98 -f9bcdce2df26678c3fe468130b535c0342c69b89 jdk-9+99 -4379223f8806626852c46c52d4e7a27a584b406e jdk-9+100 -80f67512daa15cf37b4825c1c62a675d524d7c49 jdk-9+101 -2dc4c11fe48831854916d53c3913bdb7d49023ea jdk-9+102 -4a652e4ca9523422149958673033e0ac740d5e1e jdk-9+103 -086c682bd8c5f195c324f61e2c61fbcd0226d63b jdk-9+104 -db483b34fa7148d257a429acddbde9c13687dcae jdk-9+105 -6c644cca3f3fc2763e2ff7d669849a75d34543ba jdk-9+106 -1c076468bf7dad5b8f2ee5dcf66e2279caa3e208 jdk-9+107 -257b579d813201682931d6b42f0445ffe5b4210d jdk-9+108 -c870cb782aca71093d2584376f27f0cfbfec0e3a jdk-9+109 -4a95f4b1bd8bfce85dc02a593896749feab96c34 jdk-9+110 -a6614ff7bf09da74be1d0ef3d9755090d244697a jdk-9+111 -7359994942f8d8e723b584d66a3a92c2e9e95e5c jdk-9+112 -6072af7a98be3922f26bdce71b53bb3646cb2ac9 jdk-9+113 -c84d0cce090e161d736de69e941830adf8c2f87a jdk-9+114 -8d78fb40648dd221ce4ef19f9d5aa41ee1a3a884 jdk-9+115 -84aba7335005a3a47751dcf1f37935f97df9f99a jdk-9+116 -82b8d12a553f5617737c238cec060281d52e351c jdk-9+117 -7c04fcb12bd4a31570a238e663fa846dfa5ec3b8 jdk-9+118 -caf97b37ebec84288c112d21d3a60cb628cba1e8 jdk-9+119 -9330543436402b8f3bd070524846a464d8143557 jdk-9+120 -18e5cdecb37a2f03ba74f6c8f022858bcbaacf56 jdk-9+121 -7693aa00e131493ceb42b93305e2f014c9922a3b jdk-9+122 -d53037a90c441cb528dc41c30827985de0e67c62 jdk-9+123 -2a5697a98620c4f40e4a1a71478464399b8878de jdk-9+124 -3aa52182b3ad7c5b3a61cf05a59dd07e4c5884e5 jdk-9+125 -03e7b2c5ae345be3caf981d76ceb3efe5ff447f8 jdk-9+126 -8e45018bde9de4ad15b972ae62874bba52dba2d5 jdk-9+127 -5bf88dce615f6804f9e101a96ffa7c9dfb4fbbbe jdk-9+128 -e8373543a3f0f60589b7d72b1f9b172721124caf jdk-9+129 -e613affb88d178dc7c589f1679db113d589bddb4 jdk-9+130 -4d2a15091124488080d65848b704e25599b2aaeb jdk-9+131 -2e83d21d78cd9c1d52e6cd2599e9c8aa36ea1f52 jdk-9+132 -e17429a7e843c4a4ed3651458d0f950970edcbcc jdk-9+133 -a71210c0d9800eb6925b61ecd6198abd554f90ee jdk-9+134 -e384420383a5b79fa0012ebcb25d8f83cff7f777 jdk-9+135 -1b4b5d01aa11edf24b6fadbe3d2f3e411e3b02cd jdk-9+136 -9cb87c88ed851c0575b8ead753ea238ed5b544e9 jdk-9+137 -d273dfe9a126d3bffe92072547fef2cd1361b0eb jdk-9+138 -65477538bec32963dc41153d89c4417eb46c45fc jdk-9+139 -0875007901f7d364a08220b052f0c81003e9c8c5 jdk-9+140 -9aadd2163b568d76f8969ad2fb404a63733da359 jdk-9+141 -df0e03e3ca0ed1307793017dfc1a054c8726131c jdk-9+142 -d62173b931bf5b6bffc6e80a9060bb2e8b8efc75 jdk-9+143 -31f5023200d42185b70c4c00ba5672391e4642d0 jdk-9+144 -3ee4e7827413fa5c5c4fca58597b0ad89e921bfb jdk-9+145 -581331db696a62dd411926ba7fd437252252a71d jdk-9+146 -f4e854a77aa38749bd90f722b06974a56e7233d5 jdk-9+147 -5c71ea43933b6c7e8a85eb1a4eb2213011b95d82 jdk-9+148 -cf139f925da04c8bd7efd33270a0315d72b338d3 jdk-9+149 -17469f16fbb406ec9f0dd262ce776ab6efbc38f1 jdk-9+150 -37b95df0042ae0687324e1f7dc4a2519e230e704 jdk-9+151 -ab2c8b03c3284fcbdd157551a66f807e3a182d9b jdk-9+152 -d7034ff7f8e257e81c9f95c7785dd4eaaa3c2afc jdk-9+153 -8c70d170e62c0c58b5bc3ba666bd140399b98c9c jdk-10+0 -45b751afd11e6c05991cf4913c5a0ac3304fcc4e jdk-9+154 -f4aff695ffe05cfdb69d8af25a4ddc6a029754ea jdk-9+155 -06bce0388880b5ff8e040e4a9d72a3ea11dac321 jdk-9+156 -74116beae88a8f17a80301aa6c83865c82f10ece jdk-10+1 -4a79ad46e578112fce68f1af9dd931025cc235cb jdk-10+2 -d1cab6c7e608479be4ebfad48a25b0ed48600f62 jdk-10+3 -02253db2ace1422f576f58502fc7831ead77424b jdk-10+4 -f113ce12fe24fbd24acf02711372d9f1e1c12426 jdk-10+5 -1407b19a2ddf6baae162f5a1a5b96af473f4d7d1 jdk-10+6 -30e75693ae99fd8e47fd2f5116527aff1b59aff9 jdk-10+7 -c42dc7b58b4d4301ea676a76326fd9bbd403d595 jdk-10+8 -aa5b01f5e5620438fd39efdb2e2f6365a2c7d898 jdk-10+9 -b0f2b8ff25a2209b2c807785d75f20e5086bbfc2 jdk-10+10 -036dbf8b381798e5d31065109714d04d97bf98a4 jdk-10+11 -e6d70017f5b9adbb2ec82d826973d0251800a3c3 jdk-10+12 -9927a9f16738e240ab7014f0118f41e314ef8f99 jdk-10+13 -9ef5029b247b4d940080417a287440bbdbab995b jdk-10+14 -878e216039322cb3f0ecbd0944642a2b4e2593f3 jdk-10+15 -4bbea012e5676e8025ade2bcfab4d6581e6e9f4b jdk-10+16 -7db699468b4f84abbcc01647e5a964409737411a jdk-10+17 -3739654290616e533fc6f51bf9ad69ed47a6abba jdk-10+18 -14df107500cc3b8ab238c3e4ad2c74e12bfe6067 jdk-10+19 -4586bc5d28d13d3147b993e6237eaf29a7073bbb jdk-10+20 -a85884d55ce32799f5c7382b7ea4839052b362a2 jdk-10+21 -e5357aa85dadacc6562175ff74714fecfb4470cf jdk-10+22 -22850b3a55240253841b9a425ad60a7fcdb22d47 jdk-10+23 -3b201865d5c1f244f555cad58da599c9261286d8 jdk-10+24 -8eb5e3ccee560c28ac9b1df2670adac2b3d36fad jdk-10+25 -1129253d3bc728a2963ba411ab9dd1adf358fb6b jdk-10+26 -b87d7b5d5dedc1185e5929470f945b7378cdb3ad jdk-10+27 -92f08900cb3c0d694e5c529a676c1c9e5909193f jdk-10+28 -a6e591e12f122768f675428e1e5a838fd0e9c7ec jdk-10+29 -8fee80b92e65149f7414250fd5e34b6f35d417b4 jdk-10+30 -e6278add9ff28fab70fe1cc4c1d65f7363dc9445 jdk-10+31 -a2008587c13fa05fa2dbfcb09fe987576fbedfd1 jdk-10+32 -bbd692ad4fa300ecca7939ffbe3b1d5e52a28cc6 jdk-10+33 -89deac44e51517841491ba86ff44aa82a5ca96b3 jdk-10+34 -d8c634b016c628622c9abbdc6bf50509e5dedbec jdk-10+35 -0ee20aad71c4f33c426372b4c8bcc1235ce2ec08 jdk-11+0 -959f2f7cbaa6d2ee45d50029744efb219721576c jdk-10+36 -4f830b447edf04fb4a52151a5ad44d9bb60723cd jdk-10+37 -e569e83139fdfbecfeb3cd9014d560917787f158 jdk-10+38 -5b834ec962366e00d4445352a999a3ac14e26f64 jdk-10+39 -860326263d1f6a83996d7da0f4c66806ae4aa1eb jdk-10+40 -3eae36c6baa5f916a3024cf1513e22357e00185d jdk-10+41 -4b62b815b4f49970b91a952929cf50115c263cb3 jdk-10+42 -107413b070b92c88bde6230ceb4a19b579781068 jdk-10+43 -dfa46cfe56346884a61efdc30dc50f7505d66761 jdk-11+1 -03ae177c26b016353e5ea1cab6ffd051dfa086ca jdk-11+2 -663f20fc51091bd7f95d18448850ba091207b7bd jdk-10+44 -4f96cf952e71cb8a127334494faf28880c26181b jdk-10+45 -1fd4d6068f54561cfc67d54fc9ca84af7212c4f8 jdk-11+3 -e59941f7247d451fa7df9eaef3fce0f492f8420c jdk-11+4 -d5c43e9f08fb9a7c74aae0d48daf17f2ad2afaef jdk-11+5 -3acb379b86725c47e7f33358cb22efa8752ae532 jdk-11+6 -f7363de371c9a1f668bd0a01b7df3d1ddb9cc58b jdk-11+7 -755e1b55a4dff510f9639cdb5c5e82549a7e09b3 jdk-11+8 -0c3e252cea44f06aef570ef464950ab97c669970 jdk-11+9 -6fa770f9f8ab296e1ce255ec17ccf6d4e1051886 jdk-10+46 -69d7398038c54774d9395b6810e0cca335edc02c jdk-11+10 -e1e60f75cd39312a7f59d2a4f91d624e5aecc95e jdk-11+11 -3ab6ba9f94a9045a526d645af26c933235371d6f jdk-11+12 -758deedaae8406ae60147486107a54e9864aa7b0 jdk-11+13 -3595bd343b65f8c37818ebe6a4c343ddeb1a5f88 jdk-11+14 -a11c1cb542bbd1671d25b85efe7d09b983c48525 jdk-11+15 -02934b0d661b82b7fe1052a04998d2091352e08d jdk-11+16 -64e4b1686141e57a681936a8283983341484676e jdk-11+17 -e1b3def126240d5433902f3cb0e91a4c27f6db50 jdk-11+18 -36ca515343e00b021dcfc902e986d26ec994a2e5 jdk-11+19 -95aad0c785e497f1bade3955c4e4a677b629fa9d jdk-12+0 -9816d7cc655e53ba081f938b656e31971b8f097a jdk-11+20 -14708e1acdc3974f4539027cbbcfa6d69f83cf51 jdk-11+21 -00b16d0457e43d23f6ca5ade6b243edce62750a0 jdk-12+1 -9937ef7499dcd7673714517fd5e450410c14ba4e jdk-11+22 -69b438908512d3dfef5852c6a843a5778333a309 jdk-12+2 -1edcf36fe15f79d6228d1a63eb680878e2386480 jdk-11+23 -990db216e7199b2ba9989d8fa20b657e0ca7d969 jdk-12+3 -ea900a7dc7d77dee30865c60eabd87fc24b1037c jdk-11+24 -499b873761d8e8a1cc4aa649daf04cbe98cbce77 jdk-12+4 -331888ea4a788df801b1edf8836646cd25fc758b jdk-11+25 -f8696e0ab9b795030429fc3374ec03e378fd9ed7 jdk-12+5 -945ba9278a272a5477ffb1b3ea1b04174fed8036 jdk-11+26 -7939b3c4e4088bf4f70ec5bbd8030393b653372f jdk-12+6 -9d7d74c6f2cbe522e39fa22dc557fdd3f79b32ad jdk-11+27 -ef57958c7c511162da8d9a75f0b977f0f7ac464e jdk-12+7 -76072a077ee1d815152d45d1692c4b36c53c5c49 jdk-11+28 -492b366f8e5784cc4927c2c98f9b8a3f16c067eb jdk-12+8 -31b159f30fb281016c5f0c103552809aeda84063 jdk-12+9 -8f594f75e0547d4ca16649cb3501659e3155e81b jdk-12+10 -f0f5d23449d31f1b3580c8a73313918cafeaefd7 jdk-12+11 -15094d12a632f452a2064318a4e416d0c7a9ce0c jdk-12+12 -511a9946f83e3e3c7b9dbe1840367063fb39b4e1 jdk-12+13 -8897e41b327c0a5601c6ba2bba5d07f15a3ffc91 jdk-12+14 -8897e41b327c0a5601c6ba2bba5d07f15a3ffc91 jdk-12+14 -6f04692c7d5137ee34a6bd94c0c8a6c9219cb127 jdk-12+14 -f8626bcc169813a4b2a15880386b952719d1d6d1 jdk-12+15 -199658d1ef860cdc17055b4fd3e94b057f292fe9 jdk-12+16 -eefa65e142af305923d2adcd596fab9c639723a1 jdk-12+17 -e38473506688e0995e701fc7f77d5a91b438ef93 jdk-12+18 -dc1f9dec2018a37fedba47d8a2aedef99faaec64 jdk-12+19 -40098289d5804c3b5e7074bc75501a81e70d9b0d jdk-12+20 -f8fb0c86f2b3d24294d39c5685a628e1beb14ba7 jdk-12+21 -732bec44c89e8b93a38296bf690f97b7230c5b6d jdk-12+22 -eef755718cb24813031a842bbfc716a6cea18e9a jdk-12+23 -cc4098b3bc10d1c390384289025fea7b0d4b9e93 jdk-13+0 -7d4397b43fa305806160785a4c7210600d59581a jdk-12+24 -11033c4ada542f9c9a873314b6ecf60af19e8256 jdk-13+1 -7496df94b3b79f3da53925d2d137317715f11d97 jdk-12+25 -50677f43ac3df9a8684222b8893543c60f3aa0bd jdk-13+2 -de9fd809bb475401aad188eab2264226788aad81 jdk-12+26 -642346a11059b9f283110dc301a24ed43b76a94e jdk-13+3 -f15d443f97318e9b40e6f451e327ff69ed4ec361 jdk-12+27 -a47b8125b7cc9ef59619745c163975fe935b57ed jdk-13+4 -659b004b6a1bd8c31e766cbdf328d8f8473fd4d7 jdk-12+28 -e3ed960609927b5fdfd0a797159835cd83a81a31 jdk-13+5 -44f41693631f9b5ac78ff4d2bfabd6734fe46df2 jdk-12+29 -b5f05fe4a6f8b3996a000c20078b356d991ca8ec jdk-13+6 -6c377af36a5c4203f16aed8a5e4c2ecc08fcd8bd jdk-12+30 -021917019cda1c0c5853255322274f37693a2431 jdk-13+7 -b5f7bb57de2f797be34f6c75d45c3245ad37ab97 jdk-12+31 -a535ba736cabc6886acdff36de3a096c46e5ddc5 jdk-13+8 -4ce47bc1fb92cf94c6e3d1f49d582f02dcb851ab jdk-12+32 -c081f3ea6b9300265a4a34e38f970b1e3ddaae9f jdk-13+9 -b67884871b5fff79c5ef3eb8ac74dd48d71ea9b1 jdk-12+33 -8e069f7b4fabfe05d9f500783e6d56cb0196d25c jdk-13+10 -21ea4076a275a0f498afa517e9ee1b94a9cf0255 jdk-13+11 -1d7aec80147a6d92b101a76aef92f3ddc88bedf4 jdk-13+12 -b67884871b5fff79c5ef3eb8ac74dd48d71ea9b1 jdk-12-ga -83cace4142c8563b6a921787db02388e1bc48d01 jdk-13+13 -46cf212cdccaf4fb064d913b12004007d3322b67 jdk-13+14 -f855ec13aa2501ae184c8b3e0626a8cec9966116 jdk-13+15 -9d0ae9508d5337b0dc7cc4684be42888c4023755 jdk-13+16 -93b702d2a0cb9e32160208f6700aede1f8492773 jdk-13+17 -bebb82ef3434a25f8142edafec20165f07ac562d jdk-13+18 -a43d6467317d8f1e160f67aadec37919c9d64443 jdk-13+19 -6ccc7cd7931e34129f6b7e04988fc9a63958dde0 jdk-13+20 -f2f11d7f7f4e7128f8aba6ffa576cfa76fbf7d1a jdk-13+21 -181986c5476468bc2dd4532af49599003ee8af37 jdk-13+22 -b034d2dee5fc93d42a81b65e58ce3f91e42586ff jdk-13+23 -7e2238451585029680f126ccbb46d01f2ff5607f jdk-13+24 -22b3b7983adab54e318f75aeb94471f7a4429c1e jdk-14+0 -22b3b7983adab54e318f75aeb94471f7a4429c1e jdk-13+25 -2f4e214781a1d597ed36bf5a36f20928c6c82996 jdk-14+1 -0692b67f54621991ba7afbf23e55b788f3555e69 jdk-13+26 -43627549a488b7d0b4df8fad436e36233df89877 jdk-14+2 -b7f68ddec66f996ae3aad03291d129ca9f02482d jdk-13+27 -e64383344f144217c36196c3c8a2df8f588a2af3 jdk-14+3 -1e95931e7d8fa7e3899340a9c7cb28dbea50c10c jdk-13+28 -19d0b382f0869f72d4381b54fa129f1c74b6e766 jdk-14+4 -3081f39a3d30d63b112098386ac2bb027c2b7223 jdk-13+29 -0f1e29c77e50c7da11d83df410026392c4d1a28c jdk-14+5 -2e63fb0a885fa908a97bbb0da8d7c3de11536aca jdk-13+30 -443f7359b34d60e7821216ffc60f88b6ffe0ccdd jdk-14+6 -6a159c6c23ccd0029140ab91653442e412305ce5 jdk-13+31 -28ab01c067551ef158abaef08e154e1051ca0893 jdk-14+7 -929f37a9c35d530d4e866f6e832001aeb4cfb371 jdk-13+32 -c0023e364b6f130cb1e93747b796d8718d544db1 jdk-14+8 -9c250a7600e12bdb1e611835250af3204d4aa152 jdk-13+33 -18f189e69b29f8215a3500b875127ed4fb2d977a jdk-14+9 -ececb6dae777e622abda42c705fd984a42f46b5a jdk-14+10 -bf4c808a4488025a415f867e54c8b088417e08a0 jdk-14+11 -8570f22b9b6ac6bec673899b582150865696e425 jdk-14+12 -fbbe6672ae15deaf350a9e935290a36f57ba9c25 jdk-14+13 -cddef3bde924f3ff4f17f3d369280cf69d0450e5 jdk-14+14 -9c250a7600e12bdb1e611835250af3204d4aa152 jdk-13-ga -778fc2dcbdaa8981e07e929a2cacef979c72261e jdk-14+15 -d29f0181ba424a95d881aba5eabf2e393abcc70f jdk-14+16 -5c83830390baafb76a1fbe33443c57620bd45fb9 jdk-14+17 -e84d8379815ba0d3e50fb096d28c25894cb50b8c jdk-14+18 -9b67dd88a9313e982ec5f710a7747161bc8f0c23 jdk-14+19 -54ffb15c48399dd59922ee22bb592d815307e77c jdk-14+20 -c16ac7a2eba4e73cb4f7ee9294dd647860eebff0 jdk-14+21 -83810b7d12e7ff761ad3dd91f323a22dad96f108 jdk-14+22 -15936b142f86731afa4b1a2c0fe4a01e806c4944 jdk-14+23 -438337c846fb071900ddb6922bddf8b3e895a514 jdk-14+24 -17d242844fc9e7d18b3eac97426490a9c246119e jdk-14+25 -288777cf0702914e5266bc1e5d380eed9032ca41 jdk-14+26 -2c724dba4c3cf9516b2152e151c9aea66b21b30b jdk-15+0 -91a3f092682fc715d991a87eb6ec6f28886d2035 jdk-14+27 -63e17cf29bed191ea21020b4648c9cdf893f80f5 jdk-15+1 -2069b4bfd23b56b6fc659fba8b75aaaa23debbe0 jdk-14+28 -f33197adda9ad82fdef46ac0f7dc0126204f35b2 jdk-15+2 -563fa900fa17c290ae516c7a3a69e8c069dde304 jdk-14+29 -d05fcdf25717d85e80a3a39a6b719458b22be5fe jdk-15+3 -d54ce919da90dab361995bb4d87be9851f00537a jdk-14+30 -bb0a7975b31ded63d594ee8dbfc4d4ead587f79b jdk-15+4 -decd3d2953b640f1043ee76953ff89238bff92e8 jdk-14+31 -b97c1773ccafae4a8c16cc6aedb10b2a4f9a07ed jdk-15+5 -2776da28515e087cc8849acf1e131a65ea7e77b6 jdk-14+32 -ef7d53b4fccd4a0501b17d974e84f37aa99fa813 jdk-15+6 -f728b6c7f4910d6bd6070cb4dde8393f4ba95113 jdk-14+33 -e2bc57500c1b785837982f7ce8af6751387ed73b jdk-15+7 -a96bc204e3b31ddbf909b20088964112f052927e jdk-14+34 -c7d4f2849dbfb755fc5860b362a4044ea0c9e082 jdk-15+8 -4a87bb7ebfd7f6a25ec59a5982fe3607242777f8 jdk-14+35 -62b5bfef8d618e08e6f3a56cf1fb0e67e89e9cc2 jdk-15+9 -bc54620a3848c26cff9766e5e2a6e5ddab98ed18 jdk-14+36 -1bee69801aeea1a34261c93f35bc9de072a98704 jdk-15+10 -b2dd4028a6de4e40dda8b76109e4b5c6b294f980 jdk-15+11 -2ec0ff3042630ddbd3587e340fe0dd40391cb6c4 jdk-15+12 -1c06a8ee8acad4d93c782626a233693a73de0add jdk-15+13 -1d6ceb13e142665ea833fca01c8c8598e0ddd211 jdk-15+14 -bc54620a3848c26cff9766e5e2a6e5ddab98ed18 jdk-14-ga -82b7c62cf4cc56828a8fb724f57087967232a2a7 jdk-15+15 -5c7ec21f5d13f6eb5cd32288c69b8be2f9cac256 jdk-15+16 -dd5198db2e5b1ebcafe065d987c03ba9fcb50fc3 jdk-15+17 -44aef192b488a48cce12422394691a6b1d16b98e jdk-15+18 -7cc27caabe6e342151e8baf549beb07a9c755ec2 jdk-15+19 -46bca5e5e6fb26efd07245d26fe96a9c3260f51e jdk-15+20 -12b55fad80f30d24b1f8fdb3b947ea6465ef9518 jdk-15+21 -7223c6d610343fd8323af9d07d501e01fa1a7696 jdk-15+22 -f143729ca00ec14a98ea5c7f73acba88da97746e jdk-15+23 -497fd9f9129c4928fd5a876dd55e0daf6298b511 jdk-15+24 -90b266a84c06f1b3dc0ed8767856793e8c1c357e jdk-15+25 -0a32396f7a690015d22ca3328ac441a358295d90 jdk-15+26 -93813843680bbe1b7efbca56c03fd137f20a2c31 jdk-16+0 -93813843680bbe1b7efbca56c03fd137f20a2c31 jdk-15+27 -4a485c89d5a08b495961835f5308a96038678aeb jdk-16+1 -06c9f89459daba98395fad726100feb44f89ba71 jdk-15+28 -bcbe7b8a77b8971bc221c0be1bd2abb6fb68c2d0 jdk-16+2 -b58fc60580550a4a587cab729d8fd87223ad6932 jdk-15+29 -76810b3a88c8c641ae3850a8dfd7c40c984aea9d jdk-16+3 -6909e4a1f25bfe9a2727026f5845fc1fc44a36aa jdk-15+30 -e2622818f0bd30e736252eba101fe7d2c27f400b jdk-16+4 -a32f58c6b8be81877411767de7ba9c4cf087c1b5 jdk-15+31 -143e258f64af490010eb7e0bacc1cfaeceff0993 jdk-16+5 -2dad000726b8d5db9f3df647fb4949d88f269dd4 jdk-15+32 -4a8fd81d64bafa523cddb45f82805536edace106 jdk-16+6 -6b65f4e7a975628df51ef755b02642075390041d jdk-15+33 -c3a4a7ea7c304cabdacdc31741eb94c51351668d jdk-16+7 -b0817631d2f4395508cb10e81c3858a94d9ae4de jdk-15+34 -0a73d6f3aab48ff6d7e61e47f0bc2d87a054f217 jdk-16+8 -fd60c3146a024037cdd9be34c645bb793995a7cc jdk-15+35 -c075a286cc7df767cce28e8057d6ec5051786490 jdk-16+9 -b01985b4f88f554f97901e53e1ba314681dd9c19 jdk-16+10 -e3f940bd3c8fcdf4ca704c6eb1ac745d155859d5 jdk-15+36 -5c18d696c7ce724ca36df13933aa53f50e12b9e0 jdk-16+11 -fc8e62b399bd93d06e8d13dc3b384c450e853dcd jdk-16+12 -fd07cdb26fc70243ef23d688b545514f4ddf1c2b jdk-16+13 -36b29df125dc88f11657ce93b4998aa9ff5f5d41 jdk-16+14 diff --git a/.jcheck/conf b/.jcheck/conf index 42c3716369ea45aef1693b447d60146073e3b9bc..58d09d2b614a8f24f7802cdd4369ac85556380a9 100644 --- a/.jcheck/conf +++ b/.jcheck/conf @@ -1,6 +1,7 @@ [general] project=jdk jbs=JDK +version=19 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists diff --git a/doc/building.html b/doc/building.html index 8d43c95bee59c91a71dece0d095299ed8cdb9540..97c9b2a4bb693d81a2a523047d65fbca18088497 100644 --- a/doc/building.html +++ b/doc/building.html @@ -96,6 +96,7 @@
  • Specific Build Issues
  • Getting Help
  • +
  • Reproducible Builds
  • Hints and Suggestions for Advanced Users * * @since 1.1 + * @see #getConstructors() * @jls 8.8 Constructor Declarations */ @CallerSensitive @@ -2704,7 +2740,7 @@ public final class Class implements java.io.Serializable, /** * Returns a {@code Constructor} object that reflects the specified - * constructor of the class or interface represented by this + * constructor of the class represented by this * {@code Class} object. The {@code parameterTypes} parameter is * an array of {@code Class} objects that identify the constructor's * formal parameter types, in declared order. @@ -2716,7 +2752,9 @@ public final class Class implements java.io.Serializable, * @param parameterTypes the parameter array * @return The {@code Constructor} object for the constructor with the * specified parameter list - * @throws NoSuchMethodException if a matching method is not found. + * @throws NoSuchMethodException if a matching constructor is not found, + * including when this {@code Class} object represents + * an interface, a primitive type, an array class, or void. * @throws SecurityException * If a security manager, s, is present and any of the * following conditions is met: @@ -2738,6 +2776,7 @@ public final class Class implements java.io.Serializable, * * * + * @see #getConstructor(Class[]) * @since 1.1 */ @CallerSensitive @@ -3788,12 +3827,13 @@ public final class Class implements java.io.Serializable, // Fetches the factory for reflective objects @SuppressWarnings("removal") private static ReflectionFactory getReflectionFactory() { - if (reflectionFactory == null) { - reflectionFactory = - java.security.AccessController.doPrivileged - (new ReflectionFactory.GetReflectionFactoryAction()); + var factory = reflectionFactory; + if (factory != null) { + return factory; } - return reflectionFactory; + return reflectionFactory = + java.security.AccessController.doPrivileged + (new ReflectionFactory.GetReflectionFactoryAction()); } private static ReflectionFactory reflectionFactory; diff --git a/src/java.base/share/classes/java/lang/ClassLoader.java b/src/java.base/share/classes/java/lang/ClassLoader.java index e1ad30f5b115c32a6c17422c320ac02d1c12275b..dffd56948f3b8c6a5df5d260509987c1a6511909 100644 --- a/src/java.base/share/classes/java/lang/ClassLoader.java +++ b/src/java.base/share/classes/java/lang/ClassLoader.java @@ -64,6 +64,7 @@ import jdk.internal.perf.PerfCounter; import jdk.internal.misc.Unsafe; import jdk.internal.misc.VM; import jdk.internal.reflect.CallerSensitive; +import jdk.internal.reflect.CallerSensitiveAdapter; import jdk.internal.reflect.Reflection; import jdk.internal.util.StaticProperty; import sun.reflect.misc.ReflectUtil; @@ -1615,9 +1616,13 @@ public abstract class ClassLoader { */ @CallerSensitive protected static boolean registerAsParallelCapable() { - Class callerClass = - Reflection.getCallerClass().asSubclass(ClassLoader.class); - return ParallelLoaders.register(callerClass); + return registerAsParallelCapable(Reflection.getCallerClass()); + } + + // Caller-sensitive adapter method for reflective invocation + @CallerSensitiveAdapter + private static boolean registerAsParallelCapable(Class caller) { + return ParallelLoaders.register(caller.asSubclass(ClassLoader.class)); } /** diff --git a/src/java.base/share/classes/java/lang/ClassValue.java b/src/java.base/share/classes/java/lang/ClassValue.java index beb07bb2782e46b2de48249178d22a13b8d5bf9d..18f0775cc848f803c43aebc742fef35cfda184c4 100644 --- a/src/java.base/share/classes/java/lang/ClassValue.java +++ b/src/java.base/share/classes/java/lang/ClassValue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -685,7 +685,7 @@ public abstract class ClassValue { if (haveReplacement >= 0) { if (cache[(replacementPos+1) & mask] != null) { // Be conservative, to avoid breaking up a non-null run. - cache[replacementPos & mask] = (Entry) Entry.DEAD_ENTRY; + cache[replacementPos & mask] = Entry.DEAD_ENTRY; } else { cache[replacementPos & mask] = null; cacheLoad -= 1; diff --git a/src/java.base/share/classes/java/lang/Enum.java b/src/java.base/share/classes/java/lang/Enum.java index 54a1f09c9ebd75ed0139ab9a486d7dc10c7734b0..886461c3a91321fd4dbba1dbdf41a217da6a1380 100644 --- a/src/java.base/share/classes/java/lang/Enum.java +++ b/src/java.base/share/classes/java/lang/Enum.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -193,7 +193,7 @@ public abstract class Enum> * method is the order in which the constants are declared. */ public final int compareTo(E o) { - Enum other = (Enum)o; + Enum other = o; Enum self = this; if (self.getClass() != other.getClass() && // optimization self.getDeclaringClass() != other.getDeclaringClass()) @@ -275,8 +275,13 @@ public abstract class Enum> /** * enum classes cannot have finalize methods. + * + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @SuppressWarnings("deprecation") + @Deprecated(since="18", forRemoval=true) + @SuppressWarnings("removal") protected final void finalize() { } /** diff --git a/src/java.base/share/classes/java/lang/Math.java b/src/java.base/share/classes/java/lang/Math.java index 8eb030482a0a021ca2b786c0e2df36d1aee6a3ed..7341aa56a6ac870f6d05dfbac3adca52675f58c5 100644 --- a/src/java.base/share/classes/java/lang/Math.java +++ b/src/java.base/share/classes/java/lang/Math.java @@ -1390,6 +1390,7 @@ public final class Math { * @see #multiplyHigh * @since 18 */ + @IntrinsicCandidate public static long unsignedMultiplyHigh(long x, long y) { // Compute via multiplyHigh() to leverage the intrinsic long result = Math.multiplyHigh(x, y); diff --git a/src/java.base/share/classes/java/lang/Module.java b/src/java.base/share/classes/java/lang/Module.java index ab7d21038507d1c0dc02aacf8f5c87d43311657a..e822c951420669d2cc8c0b2e343b6a385dfd1ca3 100644 --- a/src/java.base/share/classes/java/lang/Module.java +++ b/src/java.base/share/classes/java/lang/Module.java @@ -68,6 +68,7 @@ import jdk.internal.org.objectweb.asm.ModuleVisitor; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; +import jdk.internal.vm.annotation.Stable; import sun.security.util.SecurityConstants; /** @@ -110,7 +111,8 @@ public final class Module implements AnnotatedElement { private final ModuleDescriptor descriptor; // true, if this module allows restricted native access - private volatile boolean enableNativeAccess; + @Stable + private boolean enableNativeAccess; /** * Creates a new named Module. The resulting Module will be defined to the diff --git a/src/java.base/share/classes/java/lang/Object.java b/src/java.base/share/classes/java/lang/Object.java index d0ad7d43cd9e3d078750f7c17c456b4437014a49..52028ba99a7c42f53659e9ee45a6b5d4b31357a4 100644 --- a/src/java.base/share/classes/java/lang/Object.java +++ b/src/java.base/share/classes/java/lang/Object.java @@ -278,7 +278,7 @@ public class Object { *
  • By executing the body of a {@code synchronized} statement * that synchronizes on the object. *
  • For objects of type {@code Class,} by executing a - * synchronized static method of that class. + * static synchronized method of that class. * *

    * Only one thread at a time can own an object's monitor. @@ -478,6 +478,12 @@ public class Object { * A subclass overrides the {@code finalize} method to dispose of * system resources or to perform other cleanup. *

    + * When running in a Java virtual machine in which finalization has been + * disabled or removed, the garbage collector will never call + * {@code finalize()}. In a Java virtual machine in which finalization is + * enabled, the garbage collector might call {@code finalize} only after an + * indefinite delay. + *

    * The general contract of {@code finalize} is that it is invoked * if and when the Java virtual * machine has determined that there is no longer any @@ -543,27 +549,29 @@ public class Object { * } * } * - * @deprecated The finalization mechanism is inherently problematic. - * Finalization can lead to performance issues, deadlocks, and hangs. - * Errors in finalizers can lead to resource leaks; there is no way to cancel - * finalization if it is no longer necessary; and no ordering is specified - * among calls to {@code finalize} methods of different objects. - * Furthermore, there are no guarantees regarding the timing of finalization. - * The {@code finalize} method might be called on a finalizable object - * only after an indefinite delay, if at all. - * - * Classes whose instances hold non-heap resources should provide a method - * to enable explicit release of those resources, and they should also - * implement {@link AutoCloseable} if appropriate. - * The {@link java.lang.ref.Cleaner} and {@link java.lang.ref.PhantomReference} - * provide more flexible and efficient ways to release resources when an object - * becomes unreachable. + * @deprecated Finalization is deprecated and subject to removal in a future + * release. The use of finalization can lead to problems with security, + * performance, and reliability. + * See JEP 421 for + * discussion and alternatives. + *

    + * Subclasses that override {@code finalize} to perform cleanup should use + * alternative cleanup mechanisms and remove the {@code finalize} method. + * Use {@link java.lang.ref.Cleaner} and + * {@link java.lang.ref.PhantomReference} as safer ways to release resources + * when an object becomes unreachable. Alternatively, add a {@code close} + * method to explicitly release resources, and implement + * {@code AutoCloseable} to enable use of the {@code try}-with-resources + * statement. + *

    + * This method will remain in place until finalizers have been removed from + * most existing code. * * @throws Throwable the {@code Exception} raised by this method * @see java.lang.ref.WeakReference * @see java.lang.ref.PhantomReference * @jls 12.6 Finalization of Class Instances */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) protected void finalize() throws Throwable { } } diff --git a/src/java.base/share/classes/java/lang/Process.java b/src/java.base/share/classes/java/lang/Process.java index 5fad1b889d55916dd0a19e3224570a19c932ff55..88e3e473e768fcdb5a21eb47cc2a55d61f9567de 100644 --- a/src/java.base/share/classes/java/lang/Process.java +++ b/src/java.base/share/classes/java/lang/Process.java @@ -845,7 +845,7 @@ public abstract class Process { * A nested class to delay looking up the Charset for the native encoding. */ private static class CharsetHolder { - private final static Charset nativeCharset; + private static final Charset nativeCharset; static { Charset cs; try { diff --git a/src/java.base/share/classes/java/lang/Runtime.java b/src/java.base/share/classes/java/lang/Runtime.java index 7948ebffb63727190030f30b573f9d52899be34d..c674880c636170f221a1b0f4c35706fa910e066d 100644 --- a/src/java.base/share/classes/java/lang/Runtime.java +++ b/src/java.base/share/classes/java/lang/Runtime.java @@ -290,6 +290,12 @@ public class Runtime { * behaves in exactly the same way as the invocation * {@link #exec(String, String[], File) exec}{@code (command, null, null)}. * + * @deprecated This method is error-prone and should not be used, the corresponding method + * {@link #exec(String[])} or {@link ProcessBuilder} should be used instead. + * The command string is broken into tokens using only whitespace characters. + * For an argument with an embedded space, such as a filename, this can cause problems + * as the token does not include the full filename. + * * @param command a specified system command. * * @return A new {@link Process} object for managing the subprocess @@ -311,6 +317,7 @@ public class Runtime { * @see #exec(String[], String[], File) * @see ProcessBuilder */ + @Deprecated(since="18") public Process exec(String command) throws IOException { return exec(command, null, null); } @@ -324,6 +331,12 @@ public class Runtime { * behaves in exactly the same way as the invocation * {@link #exec(String, String[], File) exec}{@code (command, envp, null)}. * + * @deprecated This method is error-prone and should not be used, the corresponding method + * {@link #exec(String[], String[])} or {@link ProcessBuilder} should be used instead. + * The command string is broken into tokens using only whitespace characters. + * For an argument with an embedded space, such as a filename, this can cause problems + * as the token does not include the full filename. + * * @param command a specified system command. * * @param envp array of strings, each element of which @@ -352,6 +365,7 @@ public class Runtime { * @see #exec(String[], String[], File) * @see ProcessBuilder */ + @Deprecated(since="18") public Process exec(String command, String[] envp) throws IOException { return exec(command, envp, null); } @@ -374,6 +388,12 @@ public class Runtime { * produced by the tokenizer are then placed in the new string * array {@code cmdarray}, in the same order. * + * @deprecated This method is error-prone and should not be used, the corresponding method + * {@link #exec(String[], String[], File)} or {@link ProcessBuilder} should be used instead. + * The command string is broken into tokens using only whitespace characters. + * For an argument with an embedded space, such as a filename, this can cause problems + * as the token does not include the full filename. + * * @param command a specified system command. * * @param envp array of strings, each element of which @@ -406,6 +426,7 @@ public class Runtime { * @see ProcessBuilder * @since 1.3 */ + @Deprecated(since="18") public Process exec(String command, String[] envp, File dir) throws IOException { if (command.isEmpty()) @@ -686,8 +707,17 @@ public class Runtime { * The method {@link System#runFinalization()} is the conventional * and convenient means of invoking this method. * + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. + *

    + * When running in a JVM in which finalization has been disabled or removed, + * no objects will be pending finalization, so this method does nothing. + * * @see java.lang.Object#finalize() + * @jls 12.6 Finalization of Class Instances */ + @Deprecated(since="18", forRemoval=true) public void runFinalization() { SharedSecrets.getJavaLangRefAccess().runFinalization(); } diff --git a/src/java.base/share/classes/java/lang/RuntimePermission.java b/src/java.base/share/classes/java/lang/RuntimePermission.java index db985101f7c8d236dd87d872775a492ec26f45d1..7df4c5fac5ba00d668267fa71286bf1a3b85f46e 100644 --- a/src/java.base/share/classes/java/lang/RuntimePermission.java +++ b/src/java.base/share/classes/java/lang/RuntimePermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -378,6 +378,16 @@ import java.lang.module.ModuleFinder; * {@linkplain ModuleFinder#ofSystem system modules} in the runtime image. * * + * + * inetAddressResolverProvider + * This {@code RuntimePermission} is required to be granted to + * classes which subclass and implement {@code java.net.spi.InetAddressResolverProvider}. + * The permission is checked during invocation of the abstract base class constructor. + * This permission ensures trust in classes which provide resolvers used by + * {@link java.net.InetAddress} hostname and address resolution methods. + * See {@link java.net.spi.InetAddressResolverProvider} for more information. + * + * * * * diff --git a/src/java.base/share/classes/java/lang/SecurityManager.java b/src/java.base/share/classes/java/lang/SecurityManager.java index 2facf5ff9e6a1efc76566cd3816836fef718c3c4..7414e1c4a969f3ab64a21784abafab89c640d1f2 100644 --- a/src/java.base/share/classes/java/lang/SecurityManager.java +++ b/src/java.base/share/classes/java/lang/SecurityManager.java @@ -28,7 +28,6 @@ package java.lang; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Exports; import java.lang.module.ModuleDescriptor.Opens; -import java.lang.reflect.Member; import java.io.FileDescriptor; import java.io.File; import java.io.FilePermission; @@ -48,7 +47,6 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import jdk.internal.module.ModuleLoaderMap; -import jdk.internal.reflect.CallerSensitive; import sun.security.util.SecurityConstants; /** @@ -77,7 +75,7 @@ import sun.security.util.SecurityConstants; * manager routine simply returns if the operation is permitted, but * throws a {@code SecurityException} if the operation is not * permitted. - *

    + *

    Setting a Security Manager

    * Environments using a security manager will typically set the security * manager at startup. In the JDK implementation, this is done by setting the * system property {@systemProperty java.security.manager} on the command line @@ -96,13 +94,13 @@ import sun.security.util.SecurityConstants; * {@link System#setSecurityManager(SecurityManager) setSecurityManager} method. * In the JDK implementation, if the Java virtual machine is started with * the {@code java.security.manager} system property set to the special token - * "{@code disallow}" then a security manager will not be set at startup and - * cannot be set dynamically (the + * "{@code allow}", then a security manager will not be set at startup but can + * be set dynamically. If the Java virtual machine is started with the + * {@code java.security.manager} system property not set or set to the special + * token "{@code disallow}", then a security manager will not be set at startup + * and cannot be set dynamically (the * {@link System#setSecurityManager(SecurityManager) setSecurityManager} - * method will throw an {@code UnsupportedOperationException}). If the - * {@code java.security.manager} system property is not set or is set to the - * special token "{@code allow}", then a security manager will not be set at - * startup but can be set dynamically. Finally, if the + * method will throw an {@code UnsupportedOperationException}). Finally, if the * {@code java.security.manager} system property is set to the class name of * the security manager, or to the empty String ("") or the special token * "{@code default}", then a security manager is set at startup (as described @@ -127,8 +125,7 @@ import sun.security.util.SecurityConstants; * * null * None - * Success or throws {@code SecurityException} if not permitted by - * the currently installed security manager + * Throws {@code UnsupportedOperationException} * * * @@ -148,7 +145,7 @@ import sun.security.util.SecurityConstants; * * "disallow" * None - * Always throws {@code UnsupportedOperationException} + * Throws {@code UnsupportedOperationException} * * * @@ -167,12 +164,10 @@ import sun.security.util.SecurityConstants; * * * - *

    A future release of the JDK may change the default value of the - * {@code java.security.manager} system property to "{@code disallow}". *

    * The current security manager is returned by the * {@link System#getSecurityManager() getSecurityManager} method. - *

    + *

    Checking Permissions

    * The special method * {@link SecurityManager#checkPermission(java.security.Permission)} * determines whether an access request indicated by a specified diff --git a/src/java.base/share/classes/java/lang/StackStreamFactory.java b/src/java.base/share/classes/java/lang/StackStreamFactory.java index 328154dc04ebf21c99a13621c0408393c368c683..22cbb2e170a9fb2daa0e9a505eaec4bafa4f787b 100644 --- a/src/java.base/share/classes/java/lang/StackStreamFactory.java +++ b/src/java.base/share/classes/java/lang/StackStreamFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -118,7 +118,7 @@ final class StackStreamFactory { * For example, StackFrameInfo for StackWalker::walk or * Class for StackWalker::getCallerClass */ - static abstract class AbstractStackWalker { + abstract static class AbstractStackWalker { protected final StackWalker walker; protected final Thread thread; protected final int maxDepth; @@ -783,7 +783,7 @@ final class StackStreamFactory { * * Each specialized AbstractStackWalker subclass may subclass the FrameBuffer. */ - static abstract class FrameBuffer { + abstract static class FrameBuffer { static final int START_POS = 2; // 0th and 1st elements are reserved // buffers for VM to fill stack frame info diff --git a/src/java.base/share/classes/java/lang/StackTraceElement.java b/src/java.base/share/classes/java/lang/StackTraceElement.java index 259f9255986cc3e485de5f404d72b62e6eecfda7..9a39bbc1aec208d175e847fa13ede10a947430e4 100644 --- a/src/java.base/share/classes/java/lang/StackTraceElement.java +++ b/src/java.base/share/classes/java/lang/StackTraceElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -443,7 +443,7 @@ public final class StackTraceElement implements java.io.Serializable { */ private synchronized void computeFormat() { try { - Class cls = (Class) declaringClassObject; + Class cls = declaringClassObject; ClassLoader loader = cls.getClassLoader0(); Module m = cls.getModule(); byte bits = 0; diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index 59a2181ae0ef116d620a674849a77cc3e1a11c22..abb35ebaeb16cc81bca8404eecfb0c9dd9ac571e 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -261,6 +261,7 @@ public final class String this.value = original.value; this.coder = original.coder; this.hash = original.hash; + this.hashIsZero = original.hashIsZero; } /** @@ -366,9 +367,8 @@ public final class String * * @deprecated This method does not properly convert bytes into characters. * As of JDK 1.1, the preferred way to do this is via the - * {@code String} constructors that take a {@link - * java.nio.charset.Charset}, charset name, or that use the platform's - * default charset. + * {@code String} constructors that take a {@link Charset}, charset name, + * or that use the {@link Charset#defaultCharset() default charset}. * * @param ascii * The bytes to be converted to characters @@ -428,9 +428,8 @@ public final class String * * @deprecated This method does not properly convert bytes into * characters. As of JDK 1.1, the preferred way to do this is via the - * {@code String} constructors that take a {@link - * java.nio.charset.Charset}, charset name, or that use the platform's - * default charset. + * {@code String} constructors that take a {@link Charset}, charset name, + * or that use the {@link Charset#defaultCharset() default charset}. * * @param ascii * The bytes to be converted to characters @@ -1385,9 +1384,9 @@ public final class String /** * Constructs a new {@code String} by decoding the specified subarray of - * bytes using the platform's default charset. The length of the new - * {@code String} is a function of the charset, and hence may not be equal - * to the length of the subarray. + * bytes using the {@link Charset#defaultCharset() default charset}. + * The length of the new {@code String} is a function of the charset, + * and hence may not be equal to the length of the subarray. * *

    The behavior of this constructor when the given bytes are not valid * in the default charset is unspecified. The {@link @@ -1415,9 +1414,9 @@ public final class String /** * Constructs a new {@code String} by decoding the specified array of bytes - * using the platform's default charset. The length of the new {@code - * String} is a function of the charset, and hence may not be equal to the - * length of the byte array. + * using the {@link Charset#defaultCharset() default charset}. The length + * of the new {@code String} is a function of the charset, and hence may not + * be equal to the length of the byte array. * *

    The behavior of this constructor when the given bytes are not valid * in the default charset is unspecified. The {@link @@ -1693,7 +1692,8 @@ public final class String * * @deprecated This method does not properly convert characters into * bytes. As of JDK 1.1, the preferred way to do this is via the - * {@link #getBytes()} method, which uses the platform's default charset. + * {@link #getBytes()} method, which uses the {@link Charset#defaultCharset() + * default charset}. * * @param srcBegin * Index of the first character in the string to copy @@ -1780,7 +1780,8 @@ public final class String /** * Encodes this {@code String} into a sequence of bytes using the - * platform's default charset, storing the result into a new byte array. + * {@link Charset#defaultCharset() default charset}, storing the result + * into a new byte array. * *

    The behavior of this method when this string cannot be encoded in * the default charset is unspecified. The {@link @@ -3329,10 +3330,10 @@ public final class String * Converts all of the characters in this {@code String} to lower * case using the rules of the given {@code Locale}. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} - * class. Since case mappings are not always 1:1 char mappings, the resulting - * {@code String} may be a different length than the original {@code String}. + * class. Since case mappings are not always 1:1 char mappings, the resulting {@code String} + * and this {@code String} may differ in length. *

    - * Examples of lowercase mappings are in the following table: + * Examples of lowercase mappings are in the following table: * * * @@ -3386,7 +3387,7 @@ public final class String /** * Converts all of the characters in this {@code String} to lower - * case using the rules of the default locale. This is equivalent to calling + * case using the rules of the default locale. This method is equivalent to * {@code toLowerCase(Locale.getDefault())}. *

    * Note: This method is locale sensitive, and may produce unexpected @@ -3411,11 +3412,10 @@ public final class String * Converts all of the characters in this {@code String} to upper * case using the rules of the given {@code Locale}. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} - * class. Since case mappings are not always 1:1 char mappings, the resulting - * {@code String} may be a different length than the original {@code String}. + * class. Since case mappings are not always 1:1 char mappings, the resulting {@code String} + * and this {@code String} may differ in length. *

    - * Examples of locale-sensitive and 1:M case mappings are in the following table. - * + * Examples of locale-sensitive and 1:M case mappings are in the following table: *

    Lowercase mapping examples showing language code of locale, upper case, lower case, and description
    * * diff --git a/src/java.base/share/classes/java/lang/System.java b/src/java.base/share/classes/java/lang/System.java index c843858712f7b8d942ee7e5cb09a2417801f49d9..47b436847cb4ee742d782237d394efc975487a19 100644 --- a/src/java.base/share/classes/java/lang/System.java +++ b/src/java.base/share/classes/java/lang/System.java @@ -33,7 +33,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; -import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; @@ -45,9 +44,9 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URL; -import java.nio.charset.CharacterCodingException; import java.nio.channels.Channel; import java.nio.channels.spi.SelectorProvider; +import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.security.AccessControlContext; import java.security.AccessController; @@ -84,6 +83,7 @@ import jdk.internal.vm.annotation.Stable; import sun.nio.fs.DefaultFileSystemProvider; import sun.reflect.annotation.AnnotationType; import sun.nio.ch.Interruptible; +import sun.nio.cs.UTF_8; import sun.security.util.SecurityConstants; /** @@ -188,6 +188,11 @@ public final class System { @SuppressWarnings("removal") private static volatile SecurityManager security; // read by VM + // `sun.jnu.encoding` if it is not supported. Otherwise null. + // It is initialized in `initPhase1()` before any charset providers + // are initialized. + private static String notSupportedJnuEncoding; + // return true if a security manager is allowed private static boolean allowSecurityManager() { return (allowSecurityManager != NEVER); @@ -331,7 +336,7 @@ public final class System { private static class CallersHolder { // Remember callers of setSecurityManager() here so that warning // is only printed once for each different caller - final static Map, Boolean> callers + static final Map, Boolean> callers = Collections.synchronizedMap(new WeakHashMap<>()); } @@ -361,9 +366,11 @@ public final class System { * the method simply returns. * * @implNote In the JDK implementation, if the Java virtual machine is - * started with the system property {@code java.security.manager} set to + * started with the system property {@code java.security.manager} not set or set to * the special token "{@code disallow}" then the {@code setSecurityManager} - * method cannot be used to set a security manager. + * method cannot be used to set a security manager. See the following + * section of the + * {@code SecurityManager} class specification for more details. * * @param sm the security manager or {@code null} * @throws SecurityException @@ -1593,7 +1600,7 @@ public final class System { * * @since 9 */ - public static abstract class LoggerFinder { + public abstract static class LoggerFinder { /** * The {@code RuntimePermission("loggerFinder")} is * necessary to subclass and instantiate the {@code LoggerFinder} class, @@ -1915,8 +1922,18 @@ public final class System { * Runtime.getRuntime().runFinalization() * * + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. + *

    + * When running in a JVM in which finalization has been disabled or removed, + * no objects will be pending finalization, so this method does nothing. + * * @see java.lang.Runtime#runFinalization() + * @jls 12.6 Finalization of Class Instances */ + @Deprecated(since="18", forRemoval=true) + @SuppressWarnings("removal") public static void runFinalization() { Runtime.getRuntime().runFinalization(); } @@ -2015,10 +2032,9 @@ public final class System { * Create PrintStream for stdout/err based on encoding. */ private static PrintStream newPrintStream(FileOutputStream fos, String enc) { - if (enc != null) { - try { - return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); - } catch (UnsupportedEncodingException uee) {} + if (enc != null) { + return new PrintStream(new BufferedOutputStream(fos, 128), true, + Charset.forName(enc, UTF_8.INSTANCE)); } return new PrintStream(new BufferedOutputStream(fos, 128), true); } @@ -2111,6 +2127,13 @@ public final class System { VM.saveProperties(tempProps); props = createProperties(tempProps); + // Check if sun.jnu.encoding is supported. If not, replace it with UTF-8. + var jnuEncoding = props.getProperty("sun.jnu.encoding"); + if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) { + notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding; + props.setProperty("sun.jnu.encoding", "UTF-8"); + } + StaticProperty.javaHome(); // Load StaticProperty to cache the property values lineSeparator = props.getProperty("line.separator"); @@ -2139,7 +2162,6 @@ public final class System { Thread current = Thread.currentThread(); current.getThreadGroup().add(current); - // Subsystems that are invoked during initialization can invoke // VM.isBooted() in order to avoid doing things that should // wait until the VM is fully initialized. The initialization level @@ -2237,7 +2259,7 @@ public final class System { allowSecurityManager = MAYBE; } } else { - allowSecurityManager = MAYBE; + allowSecurityManager = NEVER; } if (needWarning) { @@ -2246,6 +2268,14 @@ public final class System { WARNING: The Security Manager is deprecated and will be removed in a future release"""); } + // Emit a warning if `sun.jnu.encoding` is not supported. + if (notSupportedJnuEncoding != null) { + System.err.println( + "WARNING: The encoding of the underlying platform's" + + " file system is not supported: " + + notSupportedJnuEncoding); + } + initialErrStream = System.err; // initializing the system class loader @@ -2301,7 +2331,7 @@ public final class System { public Thread newThreadWithAcc(Runnable target, @SuppressWarnings("removal") AccessControlContext acc) { return new Thread(target, acc); } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void invokeFinalize(Object o) throws Throwable { o.finalize(); } diff --git a/src/java.base/share/classes/java/lang/Thread.java b/src/java.base/share/classes/java/lang/Thread.java index 17580d2aa8441c08efae7574c6fee301627c439e..797a7f9f82ec26aa1e1ae87e852d223304ca5e30 100644 --- a/src/java.base/share/classes/java/lang/Thread.java +++ b/src/java.base/share/classes/java/lang/Thread.java @@ -922,7 +922,7 @@ public class Thread implements Runnable { * Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?. */ - @Deprecated(since="1.2") + @Deprecated(since="1.2", forRemoval=true) public final void stop() { @SuppressWarnings("removal") SecurityManager security = System.getSecurityManager(); diff --git a/src/java.base/share/classes/java/lang/ThreadGroup.java b/src/java.base/share/classes/java/lang/ThreadGroup.java index c6e532a74448925cf4892b9631cfe81b072c7de7..bd55ca1595e5b202fd414e9c84a490f89a126b9f 100644 --- a/src/java.base/share/classes/java/lang/ThreadGroup.java +++ b/src/java.base/share/classes/java/lang/ThreadGroup.java @@ -628,6 +628,7 @@ public class ThreadGroup implements Thread.UncaughtExceptionHandler { * {@link Thread#stop} for details. */ @Deprecated(since="1.2", forRemoval=true) + @SuppressWarnings("removal") public final void stop() { if (stopOrSuspend(false)) Thread.currentThread().stop(); diff --git a/src/java.base/share/classes/java/lang/WeakPairMap.java b/src/java.base/share/classes/java/lang/WeakPairMap.java index 0e521dc901ad03243cf60acdf6f66ea8a6fe490a..f274461a5dbac59caaac64871b6ce63ba22dc0b4 100644 --- a/src/java.base/share/classes/java/lang/WeakPairMap.java +++ b/src/java.base/share/classes/java/lang/WeakPairMap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -340,7 +340,7 @@ final class WeakPairMap { /** * Common abstract supertype of a pair of WeakReference peers. */ - private static abstract class WeakRefPeer extends WeakReference { + private abstract static class WeakRefPeer extends WeakReference { WeakRefPeer(K k, ReferenceQueue queue) { super(Objects.requireNonNull(k), queue); diff --git a/src/java.base/share/classes/java/lang/invoke/AbstractConstantGroup.java b/src/java.base/share/classes/java/lang/invoke/AbstractConstantGroup.java index b61875762a4fa0d27caa553247d6f5792e1d843b..5c0f2ec7944ed665902dd18e8880ac9aaad61eaf 100644 --- a/src/java.base/share/classes/java/lang/invoke/AbstractConstantGroup.java +++ b/src/java.base/share/classes/java/lang/invoke/AbstractConstantGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -244,7 +244,7 @@ abstract class AbstractConstantGroup implements ConstantGroup { } } - static abstract + abstract static class WithCache extends AbstractConstantGroup { @Stable final Object[] cache; diff --git a/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java b/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java index b1282970ccf66f76f971373d19984aba717ea857..a9bfff152e6491614b03bc446490568339f976f3 100644 --- a/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java +++ b/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java @@ -26,6 +26,8 @@ package java.lang.invoke; import sun.invoke.util.Wrapper; +import java.lang.reflect.Modifier; + import static java.lang.invoke.MethodHandleInfo.*; import static sun.invoke.util.Wrapper.forPrimitiveType; import static sun.invoke.util.Wrapper.forWrapperType; @@ -157,7 +159,7 @@ import static sun.invoke.util.Wrapper.isWrapperType; // Classes compiled prior to dynamic nestmate support invoke a private instance // method with REF_invokeSpecial. Newer classes use REF_invokeVirtual or // REF_invokeInterface, and we can use that instruction in the lambda class. - if (targetClass == implClass) { + if (targetClass == implClass && Modifier.isPrivate(implInfo.getModifiers())) { this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual; } else { this.implKind = REF_invokeSpecial; diff --git a/src/java.base/share/classes/java/lang/invoke/CallSite.java b/src/java.base/share/classes/java/lang/invoke/CallSite.java index d6011851d9d58a4937204b3e6d8385b286351366..e159e235f30a30830bd263952566974d8bc61c91 100644 --- a/src/java.base/share/classes/java/lang/invoke/CallSite.java +++ b/src/java.base/share/classes/java/lang/invoke/CallSite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,8 +84,8 @@ private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String nam * @author John Rose, JSR 292 EG * @since 1.7 */ -abstract -public class CallSite { +public +abstract class CallSite { // The actual payload of this call site. // Can be modified using {@link MethodHandleNatives#setCallSiteTargetNormal} or {@link MethodHandleNatives#setCallSiteTargetVolatile}. diff --git a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 6b50cf2a2aa324ada6fcb5d9301e2b328e1db11b..30014e1799a79c4906476b33927221ef306392d5 100644 --- a/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -26,7 +26,6 @@ package java.lang.invoke; import jdk.internal.misc.CDS; -import jdk.internal.misc.VM; import jdk.internal.org.objectweb.asm.*; import sun.invoke.util.BytecodeDescriptor; import sun.invoke.util.VerifyAccess; @@ -37,7 +36,6 @@ import java.io.FilePermission; import java.io.Serializable; import java.lang.constant.ConstantDescs; import java.lang.invoke.MethodHandles.Lookup; -import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; @@ -46,8 +44,10 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.PropertyPermission; import java.util.Set; +import static java.lang.invoke.MethodHandleStatics.CLASSFILE_VERSION; import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE; import static java.lang.invoke.MethodHandles.Lookup.ClassOption.STRONG; +import static java.lang.invoke.MethodType.methodType; import static jdk.internal.org.objectweb.asm.Opcodes.*; /** @@ -57,7 +57,6 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; * @see LambdaMetafactory */ /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory { - private static final int CLASSFILE_VERSION = VM.classFileVersion(); private static final String METHOD_DESCRIPTOR_VOID = Type.getMethodDescriptor(Type.VOID_TYPE); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; private static final String NAME_CTOR = ""; @@ -106,7 +105,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; disableEagerInitialization = GetBooleanAction.privilegedGetProperty(disableEagerInitializationKey); // condy to load implMethod from class data - MethodType classDataMType = MethodType.methodType(Object.class, MethodHandles.Lookup.class, String.class, Class.class); + MethodType classDataMType = methodType(Object.class, MethodHandles.Lookup.class, String.class, Class.class); Handle classDataBsm = new Handle(H_INVOKESTATIC, Type.getInternalName(MethodHandles.class), "classData", classDataMType.descriptorString(), false); implMethodCondy = new ConstantDynamic(ConstantDescs.DEFAULT_NAME, MethodHandle.class.descriptorString(), classDataBsm); @@ -227,50 +226,28 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; @Override CallSite buildCallSite() throws LambdaConversionException { final Class innerClass = spinInnerClass(); - if (factoryType.parameterCount() == 0) { - // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance, - // unless we've suppressed eager initialization - if (disableEagerInitialization) { - try { - return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD, - factoryType.returnType())); - } catch (ReflectiveOperationException e) { - throw new LambdaConversionException( - "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e); - } - } else { - @SuppressWarnings("removal") - final Constructor[] ctrs = AccessController.doPrivileged( - new PrivilegedAction<>() { - @Override - public Constructor[] run() { - Constructor[] ctrs = innerClass.getDeclaredConstructors(); - if (ctrs.length == 1) { - // The lambda implementing inner class constructor is private, set - // it accessible (by us) before creating the constant sole instance - ctrs[0].setAccessible(true); - } - return ctrs; - } - }); - if (ctrs.length != 1) { - throw new LambdaConversionException("Expected one lambda constructor for " - + innerClass.getCanonicalName() + ", got " + ctrs.length); - } - - try { - Object inst = ctrs[0].newInstance(); - return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst)); - } catch (ReflectiveOperationException e) { - throw new LambdaConversionException("Exception instantiating lambda object", e); - } + if (factoryType.parameterCount() == 0 && disableEagerInitialization) { + try { + return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD, + factoryType.returnType())); + } catch (ReflectiveOperationException e) { + throw new LambdaConversionException( + "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e); } } else { try { MethodHandle mh = caller.findConstructor(innerClass, constructorType); - return new ConstantCallSite(mh.asType(factoryType)); + if (factoryType.parameterCount() == 0) { + // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance + Object inst = mh.asType(methodType(Object.class)).invokeExact(); + return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst)); + } else { + return new ConstantCallSite(mh.asType(factoryType)); + } } catch (ReflectiveOperationException e) { throw new LambdaConversionException("Exception finding constructor", e); + } catch (Throwable e) { + throw new LambdaConversionException("Exception instantiating lambda object", e); } } } diff --git a/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java b/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java index 243571593ddaff383986fca1340291ba8b5e627a..c687916dde4926ce50b2c70939fd7e0c7a6e056e 100644 --- a/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java +++ b/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java @@ -44,6 +44,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; +import java.util.Set; import java.util.stream.Stream; import static java.lang.invoke.LambdaForm.BasicType; @@ -316,7 +317,7 @@ class InvokerBytecodeGenerator { * Extract the MemberName of a newly-defined method. */ private MemberName loadMethod(byte[] classFile) { - Class invokerClass = LOOKUP.makeHiddenClassDefiner(className, classFile) + Class invokerClass = LOOKUP.makeHiddenClassDefiner(className, classFile, Set.of()) .defineClass(true, classDataValues()); return resolveInvokerMember(invokerClass, invokerName, invokerType); } @@ -376,7 +377,7 @@ class InvokerBytecodeGenerator { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC, "", "()V", null, null); mv.visitCode(); mv.visitLdcInsn(Type.getType("L" + className + ";")); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandleNatives", + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "classData", "(Ljava/lang/Class;)Ljava/lang/Object;", false); // we should optimize one single element case that does not need to create a List mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/List"); diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java b/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java index 70aee0a2778d28a88932342e2e18bc9969f99904..404782c047e2ae418d95bc2128022bc1b2748e1a 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java @@ -42,6 +42,8 @@ import sun.invoke.util.Wrapper; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.nio.ByteOrder; import java.util.Arrays; import java.util.Collections; @@ -50,6 +52,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Stream; @@ -57,6 +60,7 @@ import java.util.stream.Stream; import static java.lang.invoke.LambdaForm.*; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; +import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE; import static jdk.internal.org.objectweb.asm.Opcodes.*; /** @@ -1030,6 +1034,7 @@ abstract class MethodHandleImpl { // That way we can lazily load the code and set up the constants. private static class BindCaller { private static MethodType INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class); + private static MethodType REFLECT_INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object.class, Object[].class); static MethodHandle bindCaller(MethodHandle mh, Class hostClass) { // Code in the boot layer should now be careful while creating method handles or @@ -1042,15 +1047,48 @@ abstract class MethodHandleImpl { hostClass.getName().startsWith("java.lang.invoke."))) { throw new InternalError(); // does not happen, and should not anyway } + + MemberName member = mh.internalMemberName(); + if (member != null) { + // Look up the CSM adapter method with the same method name + // but with an additional caller class parameter. If present, + // bind the adapter's method handle with the lookup class as + // the caller class argument + MemberName csmAdapter = IMPL_LOOKUP.resolveOrNull(member.getReferenceKind(), + new MemberName(member.getDeclaringClass(), + member.getName(), + member.getMethodType().appendParameterTypes(Class.class), + member.getReferenceKind())); + if (csmAdapter != null) { + assert !csmAdapter.isCallerSensitive(); + MethodHandle dmh = DirectMethodHandle.make(csmAdapter); + dmh = MethodHandles.insertArguments(dmh, dmh.type().parameterCount() - 1, hostClass); + dmh = new WrappedMember(dmh, mh.type(), member, mh.isInvokeSpecial(), hostClass); + return dmh; + } + } + + // If no adapter method for CSM with an additional Class parameter + // is present, then inject an invoker class that is the caller + // invoking the method handle of the CSM + try { + return bindCallerWithInjectedInvoker(mh, hostClass); + } catch (ReflectiveOperationException ex) { + throw uncaughtException(ex); + } + } + + private static MethodHandle bindCallerWithInjectedInvoker(MethodHandle mh, Class hostClass) + throws ReflectiveOperationException + { // For simplicity, convert mh to a varargs-like method. MethodHandle vamh = prepareForInvoker(mh); // Cache the result of makeInjectedInvoker once per argument class. - MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass); + MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass).invoker(); return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass); } - private static MethodHandle makeInjectedInvoker(Class targetClass) { - try { + private static Class makeInjectedInvoker(Class targetClass) { /* * The invoker class defined to the same class loader as the lookup class * but in an unnamed package so that the class bytes can be cached and @@ -1064,21 +1102,80 @@ abstract class MethodHandleImpl { name = name.replace('/', '_'); } Class invokerClass = new Lookup(targetClass) - .makeHiddenClassDefiner(name, INJECTED_INVOKER_TEMPLATE) - .defineClass(true); + .makeHiddenClassDefiner(name, INJECTED_INVOKER_TEMPLATE, Set.of(NESTMATE)) + .defineClass(true, targetClass); assert checkInjectedInvoker(targetClass, invokerClass); - return IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT); - } catch (ReflectiveOperationException ex) { - throw uncaughtException(ex); - } + return invokerClass; } - private static ClassValue CV_makeInjectedInvoker = new ClassValue() { - @Override protected MethodHandle computeValue(Class hostClass) { - return makeInjectedInvoker(hostClass); + private static ClassValue CV_makeInjectedInvoker = new ClassValue<>() { + @Override + protected InjectedInvokerHolder computeValue(Class hostClass) { + return new InjectedInvokerHolder(makeInjectedInvoker(hostClass)); } }; + /* + * Returns a method handle of an invoker class injected for reflection + * implementation use with the following signature: + * reflect_invoke_V(MethodHandle mh, Object target, Object[] args) + * + * Method::invoke on a caller-sensitive method will call + * MethodAccessorImpl::invoke(Object, Object[]) through reflect_invoke_V + * target.csm(args) + * NativeMethodAccesssorImpl::invoke(target, args) + * MethodAccessImpl::invoke(target, args) + * InjectedInvoker::reflect_invoke_V(vamh, target, args); + * method::invoke(target, args) + * p.Foo::m + * + * An injected invoker class is a hidden class which has the same + * defining class loader, runtime package, and protection domain + * as the given caller class. + */ + static MethodHandle reflectiveInvoker(Class caller) { + return BindCaller.CV_makeInjectedInvoker.get(caller).reflectInvoker(); + } + + private static final class InjectedInvokerHolder { + private final Class invokerClass; + // lazily resolved and cached DMH(s) of invoke_V methods + private MethodHandle invoker; + private MethodHandle reflectInvoker; + + private InjectedInvokerHolder(Class invokerClass) { + this.invokerClass = invokerClass; + } + + private MethodHandle invoker() { + var mh = invoker; + if (mh == null) { + try { + invoker = mh = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex) { + throw new InternalError(ex); + } + } + return mh; + } + + private MethodHandle reflectInvoker() { + var mh = reflectInvoker; + if (mh == null) { + try { + reflectInvoker = mh = IMPL_LOOKUP.findStatic(invokerClass, "reflect_invoke_V", REFLECT_INVOKER_MT); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex) { + throw new InternalError(ex); + } + } + return mh; + } + } + // Adapt mh so that it can be called directly from an injected invoker: private static MethodHandle prepareForInvoker(MethodHandle mh) { mh = mh.asFixedArity(); @@ -1115,6 +1212,8 @@ abstract class MethodHandleImpl { MethodHandle invoker = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT); MethodHandle vamh = prepareForInvoker(MH_checkCallerClass); return (boolean)invoker.invoke(vamh, new Object[]{ invokerClass }); + } catch (Error|RuntimeException ex) { + throw ex; } catch (Throwable ex) { throw new InternalError(ex); } @@ -1151,27 +1250,50 @@ abstract class MethodHandleImpl { ClassWriter cw = new ClassWriter(0); // private static class InjectedInvoker { + // /* this is used to wrap DMH(s) of caller-sensitive methods */ // @Hidden // static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable { // return vamh.invokeExact(args); // } + // /* this is used in caller-sensitive reflective method accessor */ + // @Hidden + // static Object reflect_invoke_V(MethodHandle vamh, Object target, Object[] args) throws Throwable { + // return vamh.invokeExact(target, args); + // } + // } // } cw.visit(CLASSFILE_VERSION, ACC_PRIVATE | ACC_SUPER, "InjectedInvoker", null, "java/lang/Object", null); + { + var mv = cw.visitMethod(ACC_STATIC, "invoke_V", + "(Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;", + null, null); + + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, 1); + mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact", + "([Ljava/lang/Object;)Ljava/lang/Object;", false); + mv.visitInsn(ARETURN); + mv.visitMaxs(2, 2); + mv.visitEnd(); + + cw.visitEnd(); + } - MethodVisitor mv = cw.visitMethod(ACC_STATIC, "invoke_V", - "(Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;", - null, null); - - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact", - "([Ljava/lang/Object;)Ljava/lang/Object;", false); - mv.visitInsn(ARETURN); - mv.visitMaxs(2, 2); - mv.visitEnd(); - - cw.visitEnd(); + { + var mv = cw.visitMethod(ACC_STATIC, "reflect_invoke_V", + "(Ljava/lang/invoke/MethodHandle;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", + null, null); + mv.visitCode(); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, 1); + mv.visitVarInsn(ALOAD, 2); + mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact", + "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false); + mv.visitInsn(ARETURN); + mv.visitMaxs(3, 3); + mv.visitEnd(); + } return cw.toByteArray(); } } @@ -1503,6 +1625,52 @@ abstract class MethodHandleImpl { public VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { return VarHandles.insertCoordinates(target, pos, values); } + + + @Override + public MethodHandle unreflectConstructor(Constructor ctor) throws IllegalAccessException { + return IMPL_LOOKUP.unreflectConstructor(ctor); + } + + @Override + public MethodHandle unreflectField(Field field, boolean isSetter) throws IllegalAccessException { + return isSetter ? IMPL_LOOKUP.unreflectSetter(field) : IMPL_LOOKUP.unreflectGetter(field); + } + + @Override + public MethodHandle findVirtual(Class defc, String name, MethodType type) throws IllegalAccessException { + try { + return IMPL_LOOKUP.findVirtual(defc, name, type); + } catch (NoSuchMethodException e) { + return null; + } + } + + @Override + public MethodHandle findStatic(Class defc, String name, MethodType type) throws IllegalAccessException { + try { + return IMPL_LOOKUP.findStatic(defc, name, type); + } catch (NoSuchMethodException e) { + return null; + } + } + + @Override + public MethodHandle reflectiveInvoker(Class caller) { + Objects.requireNonNull(caller); + return BindCaller.reflectiveInvoker(caller); + } + + @Override + public Lookup defineHiddenClassWithClassData(Lookup caller, String name, byte[] bytes, Object classData, boolean initialize) { + // skip name and access flags validation + return caller.makeHiddenClassDefiner(name, bytes, Set.of()).defineClassAsLookup(initialize, classData); + } + + @Override + public Class[] exceptionTypes(MethodHandle handle) { + return VarHandles.exceptionTypes(handle); + } }); } @@ -2109,15 +2277,16 @@ abstract class MethodHandleImpl { // Indexes into constant method handles: static final int - MH_cast = 0, - MH_selectAlternative = 1, - MH_countedLoopPred = 2, - MH_countedLoopStep = 3, - MH_initIterator = 4, - MH_iteratePred = 5, - MH_iterateNext = 6, - MH_Array_newInstance = 7, - MH_LIMIT = 8; + MH_cast = 0, + MH_selectAlternative = 1, + MH_countedLoopPred = 2, + MH_countedLoopStep = 3, + MH_initIterator = 4, + MH_iteratePred = 5, + MH_iterateNext = 6, + MH_Array_newInstance = 7, + MH_VarHandles_handleCheckedExceptions = 8, + MH_LIMIT = 9; static MethodHandle getConstantHandle(int idx) { MethodHandle handle = HANDLES[idx]; @@ -2167,6 +2336,9 @@ abstract class MethodHandleImpl { case MH_Array_newInstance: return IMPL_LOOKUP.findStatic(Array.class, "newInstance", MethodType.methodType(Object.class, Class.class, int.class)); + case MH_VarHandles_handleCheckedExceptions: + return IMPL_LOOKUP.findStatic(VarHandles.class, "handleCheckedExceptions", + MethodType.methodType(void.class, Throwable.class)); } } catch (ReflectiveOperationException ex) { throw newInternalError(ex); diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java b/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java index dd0a2417e19a97a258ab7a17aee716af61df931b..8a949a77e8e0815f9c99ee6fab92d367f4da67cf 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,7 @@ package java.lang.invoke; -import jdk.internal.access.JavaLangAccess; -import jdk.internal.access.SharedSecrets; +import jdk.internal.misc.VM; import jdk.internal.ref.CleanerFactory; import sun.invoke.util.Wrapper; @@ -35,7 +34,6 @@ import java.lang.reflect.Field; import static java.lang.invoke.MethodHandleNatives.Constants.*; import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE; -import static java.lang.invoke.MethodHandleStatics.UNSAFE; import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; /** @@ -248,6 +246,7 @@ class MethodHandleNatives { return true; } static { + VM.setJavaLangInvokeInited(); assert(verifyConstants()); } @@ -258,7 +257,6 @@ class MethodHandleNatives { * The JVM is linking an invokedynamic instruction. Create a reified call site for it. */ static MemberName linkCallSite(Object callerObj, - int indexInCP, Object bootstrapMethodObj, Object nameObj, Object typeObj, Object staticArguments, @@ -317,7 +315,6 @@ class MethodHandleNatives { // this implements the upcall from the JVM, MethodHandleNatives.linkDynamicConstant: static Object linkDynamicConstant(Object callerObj, - int indexInCP, Object bootstrapMethodObj, Object nameObj, Object typeObj, Object staticArguments) { @@ -667,8 +664,7 @@ class MethodHandleNatives { static boolean canBeCalledVirtual(MemberName mem) { assert(mem.isInvocable()); - return mem.getName().equals("getContextClassLoader") && - canBeCalledVirtual(mem, java.lang.Thread.class); + return mem.getName().equals("getContextClassLoader") && canBeCalledVirtual(mem, java.lang.Thread.class); } static boolean canBeCalledVirtual(MemberName symbolicRef, Class definingClass) { @@ -678,16 +674,4 @@ class MethodHandleNatives { return (definingClass.isAssignableFrom(symbolicRefClass) || // Msym overrides Mdef symbolicRefClass.isInterface()); // Mdef implements Msym } - - private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); - /* - * Returns the class data set by the VM in the Class::classData field. - * - * This is also invoked by LambdaForms as it cannot use condy via - * MethodHandles.classData due to bootstrapping issue. - */ - static Object classData(Class c) { - UNSAFE.ensureClassInitialized(c); - return JLA.classData(c); - } } diff --git a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java index 9e25dd5bfc2d5f1ee96ea385f36f5d190f8bc648..743ebb6675996de06691fbb2cbded1afef2d46fc 100644 --- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java +++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java @@ -32,6 +32,7 @@ import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.org.objectweb.asm.Type; import jdk.internal.reflect.CallerSensitive; +import jdk.internal.reflect.CallerSensitiveAdapter; import jdk.internal.reflect.Reflection; import jdk.internal.vm.annotation.ForceInline; import sun.invoke.util.ValueConversions; @@ -63,7 +64,9 @@ import java.util.stream.Stream; import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; import static java.lang.invoke.MethodHandleImpl.Intrinsic; import static java.lang.invoke.MethodHandleNatives.Constants.*; +import static java.lang.invoke.MethodHandleStatics.UNSAFE; import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; +import static java.lang.invoke.MethodHandleStatics.newInternalError; import static java.lang.invoke.MethodType.methodType; /** @@ -117,14 +120,15 @@ public class MethodHandles { } /** - * This reflected$lookup method is the alternate implementation of - * the lookup method when being invoked by reflection. + * This lookup method is the alternate implementation of + * the lookup method with a leading caller class argument which is + * non-caller-sensitive. This method is only invoked by reflection + * and method handle. */ - @CallerSensitive - private static Lookup reflected$lookup() { - Class caller = Reflection.getCallerClass(); + @CallerSensitiveAdapter + private static Lookup lookup(Class caller) { if (caller.getClassLoader() == null) { - throw newIllegalArgumentException("illegal lookupClass: "+caller); + throw newInternalError("calling lookup() reflectively is not supported: "+caller); } return new Lookup(caller); } @@ -329,7 +333,7 @@ public class MethodHandles { throw new IllegalAccessException(caller + " does not have ORIGINAL access"); } - Object classdata = MethodHandleNatives.classData(caller.lookupClass()); + Object classdata = classData(caller.lookupClass()); if (classdata == null) return null; try { @@ -341,6 +345,17 @@ public class MethodHandles { } } + /* + * Returns the class data set by the VM in the Class::classData field. + * + * This is also invoked by LambdaForms as it cannot use condy via + * MethodHandles::classData due to bootstrapping issue. + */ + static Object classData(Class c) { + UNSAFE.ensureClassInitialized(c); + return SharedSecrets.getJavaLangAccess().classData(c); + } + /** * Returns the element at the specified index in the * {@linkplain #classData(Lookup, String, Class) class data}, @@ -860,40 +875,20 @@ public class MethodHandles { * with all public types that are accessible to {@code M0}. {@code M0} * reads {@code M1} and hence the set of accessible types includes: * - *

    Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.
    - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
    - * Public types in the following packages are accessible to the - * lookup class and the previous lookup class. - *
    Equally accessible types to {@code M0} and {@code M1}
    unconditional-exported packages from {@code M1}
    unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}
    unconditional-exported packages from a third module {@code M2} - * if both {@code M0} and {@code M1} read {@code M2}
    qualified-exported packages from {@code M1} to {@code M0}
    qualified-exported packages from {@code M0} to {@code M1} - * if {@code M1} reads {@code M0}
    qualified-exported packages from a third module {@code M2} to - * both {@code M0} and {@code M1} if both {@code M0} and {@code M1} read {@code M2}
    + *

      + *
    • unconditional-exported packages from {@code M1}
    • + *
    • unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}
    • + *
    • + * unconditional-exported packages from a third module {@code M2}if both {@code M0} + * and {@code M1} read {@code M2} + *
    • + *
    • qualified-exported packages from {@code M1} to {@code M0}
    • + *
    • qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}
    • + *
    • + * qualified-exported packages from a third module {@code M2} to both {@code M0} and + * {@code M1} if both {@code M0} and {@code M1} read {@code M2} + *
    • + *
    * *

    Access modes

    * @@ -960,7 +955,7 @@ public class MethodHandles { * 2R * * - * {@code CL.in(D).in(C)} hop back to module + * {@code CL.in(D).in(C)} hop back to module * * * @@ -969,7 +964,7 @@ public class MethodHandles { * 2R * * - * {@code PRI1 = privateLookupIn(C1,CL)} + * {@code PRI1 = privateLookupIn(C1,CL)} * * PRO * PRI @@ -978,7 +973,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1a = privateLookupIn(C,PRI1)} + * {@code PRI1a = privateLookupIn(C,PRI1)} * * PRO * PRI @@ -987,7 +982,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.in(C1)} same package + * {@code PRI1.in(C1)} same package * * * @@ -996,7 +991,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.in(C1)} different package + * {@code PRI1.in(C1)} different package * * * @@ -1005,7 +1000,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.in(D)} different module + * {@code PRI1.in(D)} different module * * * @@ -1014,7 +1009,7 @@ public class MethodHandles { * 2R * * - * {@code PRI1.dropLookupMode(PROTECTED)} + * {@code PRI1.dropLookupMode(PROTECTED)} * * * PRI @@ -1023,7 +1018,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.dropLookupMode(PRIVATE)} + * {@code PRI1.dropLookupMode(PRIVATE)} * * * @@ -1032,7 +1027,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.dropLookupMode(PACKAGE)} + * {@code PRI1.dropLookupMode(PACKAGE)} * * * @@ -1041,7 +1036,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.dropLookupMode(MODULE)} + * {@code PRI1.dropLookupMode(MODULE)} * * * @@ -1050,7 +1045,7 @@ public class MethodHandles { * 1R * * - * {@code PRI1.dropLookupMode(PUBLIC)} + * {@code PRI1.dropLookupMode(PUBLIC)} * * * @@ -1058,7 +1053,7 @@ public class MethodHandles { * * none * - * {@code PRI2 = privateLookupIn(D,CL)} + * {@code PRI2 = privateLookupIn(D,CL)} * * PRO * PRI @@ -1067,7 +1062,7 @@ public class MethodHandles { * 2R * * - * {@code privateLookupIn(D,PRI1)} + * {@code privateLookupIn(D,PRI1)} * * PRO * PRI @@ -1076,7 +1071,7 @@ public class MethodHandles { * 2R * * - * {@code privateLookupIn(C,PRI2)} fails + * {@code privateLookupIn(C,PRI2)} fails * * * @@ -1085,7 +1080,7 @@ public class MethodHandles { * IAE * * - * {@code PRI2.in(D2)} same package + * {@code PRI2.in(D2)} same package * * * @@ -1094,7 +1089,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.in(D2)} different package + * {@code PRI2.in(D2)} different package * * * @@ -1103,7 +1098,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.in(C1)} hop back to module + * {@code PRI2.in(C1)} hop back to module * * * @@ -1112,7 +1107,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.in(E)} hop to third module + * {@code PRI2.in(E)} hop to third module * * * @@ -1121,7 +1116,7 @@ public class MethodHandles { * none * * - * {@code PRI2.dropLookupMode(PROTECTED)} + * {@code PRI2.dropLookupMode(PROTECTED)} * * * PRI @@ -1130,7 +1125,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.dropLookupMode(PRIVATE)} + * {@code PRI2.dropLookupMode(PRIVATE)} * * * @@ -1139,7 +1134,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.dropLookupMode(PACKAGE)} + * {@code PRI2.dropLookupMode(PACKAGE)} * * * @@ -1148,7 +1143,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.dropLookupMode(MODULE)} + * {@code PRI2.dropLookupMode(MODULE)} * * * @@ -1157,7 +1152,7 @@ public class MethodHandles { * 2R * * - * {@code PRI2.dropLookupMode(PUBLIC)} + * {@code PRI2.dropLookupMode(PUBLIC)} * * * @@ -1166,7 +1161,7 @@ public class MethodHandles { * none * * - * {@code CL.dropLookupMode(PROTECTED)} + * {@code CL.dropLookupMode(PROTECTED)} * * * PRI @@ -1175,7 +1170,7 @@ public class MethodHandles { * 1R * * - * {@code CL.dropLookupMode(PRIVATE)} + * {@code CL.dropLookupMode(PRIVATE)} * * * @@ -1184,7 +1179,7 @@ public class MethodHandles { * 1R * * - * {@code CL.dropLookupMode(PACKAGE)} + * {@code CL.dropLookupMode(PACKAGE)} * * * @@ -1193,7 +1188,7 @@ public class MethodHandles { * 1R * * - * {@code CL.dropLookupMode(MODULE)} + * {@code CL.dropLookupMode(MODULE)} * * * @@ -1202,7 +1197,7 @@ public class MethodHandles { * 1R * * - * {@code CL.dropLookupMode(PUBLIC)} + * {@code CL.dropLookupMode(PUBLIC)} * * * @@ -1211,7 +1206,7 @@ public class MethodHandles { * none * * - * {@code PUB = publicLookup()} + * {@code PUB = publicLookup()} * * * @@ -1220,7 +1215,7 @@ public class MethodHandles { * U * * - * {@code PUB.in(D)} different module + * {@code PUB.in(D)} different module * * * @@ -1229,7 +1224,7 @@ public class MethodHandles { * U * * - * {@code PUB.in(D).in(E)} third module + * {@code PUB.in(D).in(E)} third module * * * @@ -1238,7 +1233,7 @@ public class MethodHandles { * U * * - * {@code PUB.dropLookupMode(UNCONDITIONAL)} + * {@code PUB.dropLookupMode(UNCONDITIONAL)} * * * @@ -1247,7 +1242,7 @@ public class MethodHandles { * none * * - * {@code privateLookupIn(C1,PUB)} fails + * {@code privateLookupIn(C1,PUB)} fails * * * @@ -1256,7 +1251,7 @@ public class MethodHandles { * IAE * * - * {@code ANY.in(X)}, for inaccessible {@code X} + * {@code ANY.in(X)}, for inaccessible {@code X} * * * @@ -2359,15 +2354,16 @@ public class MethodHandles { /** * Returns a ClassDefiner that creates a {@code Class} object of a hidden class - * from the given bytes. No package name check on the given name. + * from the given bytes and the given options. No package name check on the given name. * * @param name fully-qualified name that specifies the prefix of the hidden class * @param bytes class bytes - * @return ClassDefiner that defines a hidden class of the given bytes. + * @param options class options + * @return ClassDefiner that defines a hidden class of the given bytes and options. */ - ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) { + ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set options) { // skip name and access flags validation - return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), Set.of(), false); + return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false); } /** diff --git a/src/java.base/share/classes/java/lang/invoke/VarHandles.java b/src/java.base/share/classes/java/lang/invoke/VarHandles.java index fb86bfab0e8c7deff098c42cc674ec463f2f8ac8..45cdb75b2ee3045549ea1574fcfd0048d052fa6d 100644 --- a/src/java.base/share/classes/java/lang/invoke/VarHandles.java +++ b/src/java.base/share/classes/java/lang/invoke/VarHandles.java @@ -31,12 +31,9 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.lang.reflect.Parameter; import java.nio.ByteOrder; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -45,8 +42,6 @@ import java.util.stream.Stream; import static java.lang.invoke.MethodHandleStatics.UNSAFE; import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT; import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; final class VarHandles { @@ -359,13 +354,13 @@ final class VarHandles { return target; } - public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { + public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) { Objects.requireNonNull(target); - Objects.requireNonNull(filterToTarget); - Objects.requireNonNull(filterFromTarget); + Objects.requireNonNull(pFilterToTarget); + Objects.requireNonNull(pFilterFromTarget); //check that from/to filters do not throw checked exceptions - noCheckedExceptions(filterToTarget); - noCheckedExceptions(filterFromTarget); + MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget); + MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget); List> newCoordinates = new ArrayList<>(); List> additionalCoordinates = new ArrayList<>(); @@ -473,8 +468,9 @@ final class VarHandles { List> newCoordinates = new ArrayList<>(targetCoordinates); for (int i = 0 ; i < filters.length ; i++) { - noCheckedExceptions(filters[i]); - MethodType filterType = filters[i].type(); + MethodHandle filter = Objects.requireNonNull(filters[i]); + filter = adaptForCheckedExceptions(filter); + MethodType filterType = filter.type(); if (filterType.parameterCount() != 1) { throw newIllegalArgumentException("Invalid filter type " + filterType); } else if (newCoordinates.get(pos + i) != filterType.returnType()) { @@ -564,10 +560,10 @@ final class VarHandles { return adjustedType; } - public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { + public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) { Objects.requireNonNull(target); - Objects.requireNonNull(filter); - noCheckedExceptions(filter); + Objects.requireNonNull(pFilter); + MethodHandle filter = adaptForCheckedExceptions(pFilter); List> targetCoordinates = target.coordinateTypes(); if (pos < 0 || pos >= targetCoordinates.size()) { @@ -604,42 +600,55 @@ final class VarHandles { (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes)); } - private static void noCheckedExceptions(MethodHandle handle) { + private static MethodHandle adaptForCheckedExceptions(MethodHandle target) { + Class[] exceptionTypes = exceptionTypes(target); + if (exceptionTypes != null) { // exceptions known + if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) { + throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions"); + } + return target; // no adaptation needed + } else { + MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions); + MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch + handler = MethodHandles.collectArguments(zero, 0, handler); + return MethodHandles.catchException(target, Throwable.class, handler); + } + } + + static void handleCheckedExceptions(Throwable throwable) throws Throwable { + if (isCheckedException(throwable.getClass())) { + throw new IllegalStateException("Adapter handle threw checked exception", throwable); + } + throw throwable; + } + + static Class[] exceptionTypes(MethodHandle handle) { if (handle instanceof DirectMethodHandle directHandle) { byte refKind = directHandle.member.getReferenceKind(); MethodHandleInfo info = new InfoFromMemberName( MethodHandles.Lookup.IMPL_LOOKUP, directHandle.member, refKind); - final Class[] exceptionTypes; if (MethodHandleNatives.refKindIsMethod(refKind)) { - exceptionTypes = info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP) + return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP) .getExceptionTypes(); } else if (MethodHandleNatives.refKindIsField(refKind)) { - exceptionTypes = null; + return new Class[0]; } else if (MethodHandleNatives.refKindIsConstructor(refKind)) { - exceptionTypes = info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP) + return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP) .getExceptionTypes(); } else { throw new AssertionError("Cannot get here"); } - if (exceptionTypes != null) { - if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) { - throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions"); - } - } } else if (handle instanceof DelegatingMethodHandle) { - noCheckedExceptions(((DelegatingMethodHandle)handle).getTarget()); - } else { - //bound - BoundMethodHandle boundHandle = (BoundMethodHandle)handle; - for (int i = 0 ; i < boundHandle.fieldCount() ; i++) { - Object arg = boundHandle.arg(i); - if (arg instanceof MethodHandle){ - noCheckedExceptions((MethodHandle) arg); - } - } + return exceptionTypes(((DelegatingMethodHandle)handle).getTarget()); + } else if (handle instanceof NativeMethodHandle) { + return new Class[0]; } + + assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle; + // unknown + return null; } private static boolean isCheckedException(Class clazz) { diff --git a/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java b/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java index a412dd753cc74e05371ee97abf0b0a0a116de18f..05b010c18747557d5d0d85eec97c551a964a957d 100644 --- a/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java +++ b/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java @@ -327,7 +327,7 @@ public class ModuleDescriptor */ @Override public int hashCode() { - int hash = name.hashCode() * 43 + mods.hashCode(); + int hash = name.hashCode() * 43 + modsHashCode(mods); if (compiledVersion != null) hash = hash * 43 + compiledVersion.hashCode(); if (rawCompiledVersion != null) @@ -505,7 +505,7 @@ public class ModuleDescriptor */ @Override public int hashCode() { - int hash = mods.hashCode(); + int hash = modsHashCode(mods); hash = hash * 43 + source.hashCode(); return hash * 43 + targets.hashCode(); } @@ -708,7 +708,7 @@ public class ModuleDescriptor */ @Override public int hashCode() { - int hash = mods.hashCode(); + int hash = modsHashCode(mods); hash = hash * 43 + source.hashCode(); return hash * 43 + targets.hashCode(); } @@ -893,7 +893,8 @@ public class ModuleDescriptor * integer or a string. Tokens are separated by the punctuation characters * {@code '.'}, {@code '-'}, or {@code '+'}, or by transitions from a * sequence of digits to a sequence of characters that are neither digits - * nor punctuation characters, or vice versa. + * nor punctuation characters, or vice versa. Consecutive repeated + * punctuation characters are treated as a single punctuation character. * *
      * @@ -1033,13 +1034,6 @@ public class ModuleDescriptor while (i < n) { c = v.charAt(i); - if (c >= '0' && c <= '9') - i = takeNumber(v, i, pre); - else - i = takeString(v, i, pre); - if (i >= n) - break; - c = v.charAt(i); if (c == '.' || c == '-') { i++; continue; @@ -1048,6 +1042,10 @@ public class ModuleDescriptor i++; break; } + if (c >= '0' && c <= '9') + i = takeNumber(v, i, pre); + else + i = takeString(v, i, pre); } if (c == '+' && i >= n) @@ -1055,17 +1053,14 @@ public class ModuleDescriptor while (i < n) { c = v.charAt(i); - if (c >= '0' && c <= '9') - i = takeNumber(v, i, build); - else - i = takeString(v, i, build); - if (i >= n) - break; - c = v.charAt(i); if (c == '.' || c == '-' || c == '+') { i++; continue; } + if (c >= '0' && c <= '9') + i = takeNumber(v, i, build); + else + i = takeString(v, i, build); } this.version = v; @@ -2261,7 +2256,7 @@ public class ModuleDescriptor int hc = hash; if (hc == 0) { hc = name.hashCode(); - hc = hc * 43 + Objects.hashCode(modifiers); + hc = hc * 43 + modsHashCode(modifiers); hc = hc * 43 + requires.hashCode(); hc = hc * 43 + Objects.hashCode(packages); hc = hc * 43 + exports.hashCode(); @@ -2546,6 +2541,18 @@ public class ModuleDescriptor .collect(Collectors.joining(" ")); } + /** + * Generates and returns a hashcode for the enum instances. The returned hashcode + * is a value based on the {@link Enum#name() name} of each enum instance. + */ + private static int modsHashCode(Iterable> enums) { + int h = 0; + for (Enum e : enums) { + h = h * 43 + Objects.hashCode(e.name()); + } + return h; + } + private static > int compare(T obj1, T obj2) { if (obj1 != null) { diff --git a/src/java.base/share/classes/java/lang/ref/Cleaner.java b/src/java.base/share/classes/java/lang/ref/Cleaner.java index a736f23ad2f80734b84797791e6d43d41bc5a6a8..a4769e112b6e689118408c71f3399de400601b47 100644 --- a/src/java.base/share/classes/java/lang/ref/Cleaner.java +++ b/src/java.base/share/classes/java/lang/ref/Cleaner.java @@ -86,9 +86,13 @@ import java.util.function.Function; * by the Cleaner when the CleaningExample instance has become phantom reachable. *
      {@code
        * public class CleaningExample implements AutoCloseable {
      - *        // A cleaner, preferably one shared within a library
      - *        private static final Cleaner cleaner = ;
      + *        // A cleaner (preferably one shared within a library,
      +          // but for the sake of example, a new one is created here)
      + *        private static final Cleaner cleaner = Cleaner.create();
        *
      + *        // State class captures information necessary for cleanup.
      + *        // It must hold no reference to the instance being cleaned
      + *        // and therefore it is a static inner class in this example.
        *        static class State implements Runnable {
        *
        *            State(...) {
      diff --git a/src/java.base/share/classes/java/lang/ref/Finalizer.java b/src/java.base/share/classes/java/lang/ref/Finalizer.java
      index d5838b7a6b1b461d7dff80b400895ffbf089e606..18aedf11bb316f1a7a301559f11c84eeb8c8efa6 100644
      --- a/src/java.base/share/classes/java/lang/ref/Finalizer.java
      +++ b/src/java.base/share/classes/java/lang/ref/Finalizer.java
      @@ -61,9 +61,17 @@ final class Finalizer extends FinalReference { /* Package-private; must
               return queue;
           }
       
      +    static final boolean ENABLED = isFinalizationEnabled();
      +
      +    private static native boolean isFinalizationEnabled();
      +
           /* Invoked by VM */
           static void register(Object finalizee) {
      -        new Finalizer(finalizee);
      +        if (ENABLED) {
      +            new Finalizer(finalizee);
      +        } else {
      +            throw new InternalError("unexpected call to Finalizer::register when finalization is disabled");
      +        }
           }
       
           private void runFinalizer(JavaLangAccess jla) {
      @@ -130,7 +138,7 @@ final class Finalizer extends FinalReference { /* Package-private; must
       
           /* Called by Runtime.runFinalization() */
           static void runFinalization() {
      -        if (VM.initLevel() == 0) {
      +        if (VM.initLevel() == 0 || ! ENABLED) {
                   return;
               }
       
      @@ -182,14 +190,16 @@ final class Finalizer extends FinalReference { /* Package-private; must
           }
       
           static {
      -        ThreadGroup tg = Thread.currentThread().getThreadGroup();
      -        for (ThreadGroup tgn = tg;
      -             tgn != null;
      -             tg = tgn, tgn = tg.getParent());
      -        Thread finalizer = new FinalizerThread(tg);
      -        finalizer.setPriority(Thread.MAX_PRIORITY - 2);
      -        finalizer.setDaemon(true);
      -        finalizer.start();
      +        if (ENABLED) {
      +            ThreadGroup tg = Thread.currentThread().getThreadGroup();
      +            for (ThreadGroup tgn = tg;
      +                 tgn != null;
      +                 tg = tgn, tgn = tg.getParent());
      +            Thread finalizer = new FinalizerThread(tg);
      +            finalizer.setPriority(Thread.MAX_PRIORITY - 2);
      +            finalizer.setDaemon(true);
      +            finalizer.start();
      +        }
           }
       
       }
      diff --git a/src/java.base/share/classes/java/lang/reflect/Constructor.java b/src/java.base/share/classes/java/lang/reflect/Constructor.java
      index 400a8990f8d22f6b2f77e02b1b0b406d6e3cc47c..73ad66d5d5dc62a621ab2f6b40fc86e34b7e63bd 100644
      --- a/src/java.base/share/classes/java/lang/reflect/Constructor.java
      +++ b/src/java.base/share/classes/java/lang/reflect/Constructor.java
      @@ -26,6 +26,7 @@
       package java.lang.reflect;
       
       import jdk.internal.access.SharedSecrets;
      +import jdk.internal.misc.VM;
       import jdk.internal.reflect.CallerSensitive;
       import jdk.internal.reflect.ConstructorAccessor;
       import jdk.internal.reflect.Reflection;
      @@ -63,19 +64,17 @@ import java.util.StringJoiner;
        * @since 1.1
        */
       public final class Constructor extends Executable {
      -    @Stable
      -    private Class            clazz;
      -    private int                 slot;
      -    private Class[]          parameterTypes;
      -    private Class[]          exceptionTypes;
      -    @Stable
      -    private int                 modifiers;
      +    private final Class            clazz;
      +    private final int                 slot;
      +    private final Class[]          parameterTypes;
      +    private final Class[]          exceptionTypes;
      +    private final int                 modifiers;
           // Generics and annotations support
      -    private transient String    signature;
      +    private final transient String    signature;
           // generic info repository; lazily initialized
           private transient ConstructorRepository genericInfo;
      -    private byte[]              annotations;
      -    private byte[]              parameterAnnotations;
      +    private final byte[]              annotations;
      +    private final byte[]              parameterAnnotations;
       
           // Generics infrastructure
           // Accessor for factory
      @@ -492,9 +491,6 @@ public final class Constructor extends Executable {
               if (checkAccess)
                   checkAccess(caller, clazz, clazz, modifiers);
       
      -        if ((clazz.getModifiers() & Modifier.ENUM) != 0)
      -            throw new IllegalArgumentException("Cannot reflectively create enum objects");
      -
               ConstructorAccessor ca = constructorAccessor;   // read @Stable
               if (ca == null) {
                   ca = acquireConstructorAccessor();
      @@ -534,6 +530,7 @@ public final class Constructor extends Executable {
           // synchronization will probably make the implementation more
           // scalable.
           private ConstructorAccessor acquireConstructorAccessor() {
      +
               // First check to see if one has been created yet, and take it
               // if so.
               Constructor root = this.root;
      @@ -542,8 +539,14 @@ public final class Constructor extends Executable {
                   constructorAccessor = tmp;
               } else {
                   // Otherwise fabricate one and propagate it up to the root
      +            // Ensure the declaring class is not an Enum class.
      +            if ((clazz.getModifiers() & Modifier.ENUM) != 0)
      +                throw new IllegalArgumentException("Cannot reflectively create enum objects");
      +
                   tmp = reflectionFactory.newConstructorAccessor(this);
      -            setConstructorAccessor(tmp);
      +            // set the constructor accessor only if it's not using native implementation
      +            if (VM.isJavaLangInvokeInited())
      +                setConstructorAccessor(tmp);
               }
       
               return tmp;
      diff --git a/src/java.base/share/classes/java/lang/reflect/Field.java b/src/java.base/share/classes/java/lang/reflect/Field.java
      index e8d0e68671b25f939affe3ae1aae7b2deec20072..eb4677f01efb9e9b54d94d39c92d92f4600432a7 100644
      --- a/src/java.base/share/classes/java/lang/reflect/Field.java
      +++ b/src/java.base/share/classes/java/lang/reflect/Field.java
      @@ -65,23 +65,19 @@ import sun.reflect.annotation.TypeAnnotationParser;
        */
       public final
       class Field extends AccessibleObject implements Member {
      -
      -    @Stable
      -    private Class            clazz;
      -    private int                 slot;
      +    private final Class            clazz;
      +    private final int                 slot;
           // This is guaranteed to be interned by the VM in the 1.4
           // reflection implementation
      -    private String              name;
      -    @Stable
      -    private Class            type;
      -    @Stable
      -    private int                 modifiers;
      -    private boolean             trustedFinal;
      +    private final String              name;
      +    private final Class            type;
      +    private final int                 modifiers;
      +    private final boolean             trustedFinal;
           // Generics and annotations support
      -    private transient String    signature;
      +    private final transient String    signature;
           // generic info repository; lazily initialized
           private transient FieldRepository genericInfo;
      -    private byte[]              annotations;
      +    private final byte[]              annotations;
           // Cached field accessor created without override
           @Stable
           private FieldAccessor fieldAccessor;
      diff --git a/src/java.base/share/classes/java/lang/reflect/Method.java b/src/java.base/share/classes/java/lang/reflect/Method.java
      index 037c4c7008a2a91441651a20e3fccbaf7e6b5d41..5d8fe026b406eae1662b134f940cd01097c42346 100644
      --- a/src/java.base/share/classes/java/lang/reflect/Method.java
      +++ b/src/java.base/share/classes/java/lang/reflect/Method.java
      @@ -26,7 +26,9 @@
       package java.lang.reflect;
       
       import jdk.internal.access.SharedSecrets;
      +import jdk.internal.misc.VM;
       import jdk.internal.reflect.CallerSensitive;
      +import jdk.internal.reflect.CallerSensitiveAdapter;
       import jdk.internal.reflect.MethodAccessor;
       import jdk.internal.reflect.Reflection;
       import jdk.internal.vm.annotation.ForceInline;
      @@ -67,24 +69,22 @@ import java.util.StringJoiner;
        * @since 1.1
        */
       public final class Method extends Executable {
      -    @Stable
      -    private Class            clazz;
      -    private int                 slot;
      +    private final Class            clazz;
      +    private final int                 slot;
           // This is guaranteed to be interned by the VM in the 1.4
           // reflection implementation
      -    private String              name;
      -    private Class            returnType;
      -    private Class[]          parameterTypes;
      -    private Class[]          exceptionTypes;
      -    @Stable
      -    private int                 modifiers;
      +    private final String              name;
      +    private final Class            returnType;
      +    private final Class[]          parameterTypes;
      +    private final Class[]          exceptionTypes;
      +    private final int                 modifiers;
           // Generics and annotations support
      -    private transient String              signature;
      +    private final transient String    signature;
           // generic info repository; lazily initialized
           private transient MethodRepository genericInfo;
      -    private byte[]              annotations;
      -    private byte[]              parameterAnnotations;
      -    private byte[]              annotationDefault;
      +    private final byte[]              annotations;
      +    private final byte[]              parameterAnnotations;
      +    private final byte[]              annotationDefault;
           @Stable
           private MethodAccessor      methodAccessor;
           // For sharing of MethodAccessors. This branching structure is
      @@ -553,20 +553,64 @@ public final class Method extends Executable {
           @ForceInline // to ensure Reflection.getCallerClass optimization
           @IntrinsicCandidate
           public Object invoke(Object obj, Object... args)
      -        throws IllegalAccessException, IllegalArgumentException,
      -           InvocationTargetException
      +        throws IllegalAccessException, InvocationTargetException
           {
      +        boolean callerSensitive = isCallerSensitive();
      +        Class caller = null;
      +        if (!override || callerSensitive) {
      +            caller = Reflection.getCallerClass();
      +        }
      +
      +        // Reflection::getCallerClass filters all subclasses of
      +        // jdk.internal.reflect.MethodAccessorImpl and Method::invoke(Object, Object[])
      +        // Should not call Method::invoke(Object, Object[], Class) here
      +        if (!override) {
      +            checkAccess(caller, clazz,
      +                    Modifier.isStatic(modifiers) ? null : obj.getClass(),
      +                    modifiers);
      +        }
      +        MethodAccessor ma = methodAccessor;             // read @Stable
      +        if (ma == null) {
      +            ma = acquireMethodAccessor();
      +        }
      +
      +        return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
      +    }
      +
      +    /**
      +     * This is to support MethodHandle calling caller-sensitive Method::invoke
      +     * that may invoke a caller-sensitive method in order to get the original caller
      +     * class (not the injected invoker).
      +     *
      +     * If this adapter is not presented, MethodHandle invoking Method::invoke
      +     * will get an invoker class, a hidden nestmate of the original caller class,
      +     * that becomes the caller class invoking Method::invoke.
      +     */
      +    @CallerSensitiveAdapter
      +    private Object invoke(Object obj, Object[] args, Class caller)
      +            throws IllegalAccessException, InvocationTargetException
      +    {
      +        boolean callerSensitive = isCallerSensitive();
               if (!override) {
      -            Class caller = Reflection.getCallerClass();
                   checkAccess(caller, clazz,
                               Modifier.isStatic(modifiers) ? null : obj.getClass(),
                               modifiers);
               }
      -        MethodAccessor ma = methodAccessor;             // read volatile
      +        MethodAccessor ma = methodAccessor;             // read @Stable
               if (ma == null) {
                   ma = acquireMethodAccessor();
               }
      -        return ma.invoke(obj, args);
      +
      +        return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
      +    }
      +
      +    @Stable private Boolean callerSensitive;       // lazily initialize
      +    private boolean isCallerSensitive() {
      +        Boolean cs = callerSensitive;
      +        if (cs == null) {
      +            callerSensitive = cs = Reflection.isCallerSensitive(this);
      +        }
      +        return cs;
           }
       
           /**
      @@ -672,8 +716,10 @@ public final class Method extends Executable {
                   methodAccessor = tmp;
               } else {
                   // Otherwise fabricate one and propagate it up to the root
      -            tmp = reflectionFactory.newMethodAccessor(this);
      -            setMethodAccessor(tmp);
      +            tmp = reflectionFactory.newMethodAccessor(this, isCallerSensitive());
      +            // set the method accessor only if it's not using native implementation
      +            if (VM.isJavaLangInvokeInited())
      +                setMethodAccessor(tmp);
               }
       
               return tmp;
      diff --git a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java
      index 62c81c42f5c8dc641ca66dee35dc3206d59bdb67..c2d388d01bac0ed9935571a2b130cf49bd256e4d 100644
      --- a/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java
      +++ b/src/java.base/share/classes/java/lang/runtime/ObjectMethods.java
      @@ -29,9 +29,11 @@ import java.lang.invoke.ConstantCallSite;
       import java.lang.invoke.MethodHandle;
       import java.lang.invoke.MethodHandles;
       import java.lang.invoke.MethodType;
      +import java.lang.invoke.StringConcatFactory;
       import java.lang.invoke.TypeDescriptor;
       import java.security.AccessController;
       import java.security.PrivilegedAction;
      +import java.util.ArrayList;
       import java.util.Arrays;
       import java.util.HashMap;
       import java.util.List;
      @@ -52,6 +54,8 @@ public class ObjectMethods {
       
           private ObjectMethods() { }
       
      +    private static final int MAX_STRING_CONCAT_SLOTS = 20;
      +
           private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
           private static final MethodType NAMES_MT = MethodType.methodType(List.class);
           private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
      @@ -251,44 +255,110 @@ public class ObjectMethods {
            * @param names           the names
            * @return the method handle
            */
      -    private static MethodHandle makeToString(Class receiverClass,
      -                                            List getters,
      +    private static MethodHandle makeToString(MethodHandles.Lookup lookup,
      +                                            Class receiverClass,
      +                                            MethodHandle[] getters,
                                                   List names) {
      -        // This is a pretty lousy algorithm; we spread the receiver over N places,
      -        // apply the N getters, apply N toString operations, and concat the result with String.format
      -        // Better to use String.format directly, or delegate to StringConcatFactory
      -        // Also probably want some quoting around String components
      -
      -        assert getters.size() == names.size();
      -
      -        int[] invArgs = new int[getters.size()];
      -        Arrays.fill(invArgs, 0);
      -        MethodHandle[] filters = new MethodHandle[getters.size()];
      -        StringBuilder sb = new StringBuilder();
      -        sb.append(receiverClass.getSimpleName()).append("[");
      -        for (int i=0; i> splits;
      +        MethodHandle[] toSplit = getters;
      +        int namesIndex = 0;
      +        do {
      +            /* StringConcatFactory::makeConcatWithConstants can only deal with 200 slots, longs and double occupy two
      +             * the rest 1 slot, we need to chop the current `getters` into chunks, it could be that for records with
      +             * a lot of components that we need to do a couple of iterations. The main difference between the first
      +             * iteration and the rest would be on the recipe
      +             */
      +            splits = split(toSplit);
      +            mhs = new MethodHandle[splits.size()];
      +            for (int splitIndex = 0; splitIndex < splits.size(); splitIndex++) {
      +                String recipe = "";
      +                if (firstTime && splitIndex == 0) {
      +                    recipe = receiverClass.getSimpleName() + "[";
      +                }
      +                for (int i = 0; i < splits.get(splitIndex).size(); i++) {
      +                    recipe += firstTime ? names.get(namesIndex) + "=" + "\1" : "\1";
      +                    if (firstTime && namesIndex != names.size() - 1) {
      +                        recipe += ", ";
      +                    }
      +                    namesIndex++;
      +                }
      +                if (firstTime && splitIndex == splits.size() - 1) {
      +                    recipe += "]";
      +                }
      +                Class[] concatTypeArgs = new Class[splits.get(splitIndex).size()];
      +                // special case: no need to create another getters if there is only one split
      +                MethodHandle[] currentSplitGetters = new MethodHandle[splits.get(splitIndex).size()];
      +                for (int j = 0; j < splits.get(splitIndex).size(); j++) {
      +                    concatTypeArgs[j] = splits.get(splitIndex).get(j).type().returnType();
      +                    currentSplitGetters[j] = splits.get(splitIndex).get(j);
      +                }
      +                MethodType concatMT = MethodType.methodType(String.class, concatTypeArgs);
      +                try {
      +                    mhs[splitIndex] = StringConcatFactory.makeConcatWithConstants(
      +                            lookup, "",
      +                            concatMT,
      +                            recipe,
      +                            new Object[0]
      +                    ).getTarget();
      +                    mhs[splitIndex] = MethodHandles.filterArguments(mhs[splitIndex], 0, currentSplitGetters);
      +                    // this will spread the receiver class across all the getters
      +                    mhs[splitIndex] = MethodHandles.permuteArguments(
      +                            mhs[splitIndex],
      +                            MethodType.methodType(String.class, receiverClass),
      +                            new int[splits.get(splitIndex).size()]
      +                    );
      +                } catch (Throwable t) {
      +                    throw new RuntimeException(t);
      +                }
      +            }
      +            toSplit = mhs;
      +            firstTime = false;
      +        } while (splits.size() > 1);
      +        return mhs[0];
      +    }
      +
      +    /**
      +     * Chops the getters into smaller chunks according to the maximum number of slots
      +     * StringConcatFactory::makeConcatWithConstants can chew
      +     * @param getters the current getters
      +     * @return chunks that wont surpass the maximum number of slots StringConcatFactory::makeConcatWithConstants can chew
      +     */
      +    private static List> split(MethodHandle[] getters) {
      +        List> splits = new ArrayList<>();
      +
      +        int slots = 0;
      +
      +        // Need to peel, so that neither call has more than acceptable number
      +        // of slots for the arguments.
      +        List cArgs = new ArrayList<>();
      +        for (MethodHandle methodHandle : getters) {
      +            Class returnType = methodHandle.type().returnType();
      +            int needSlots = (returnType == long.class || returnType == double.class) ? 2 : 1;
      +            if (slots + needSlots > MAX_STRING_CONCAT_SLOTS) {
      +                splits.add(cArgs);
      +                cArgs = new ArrayList<>();
      +                slots = 0;
      +            }
      +            cArgs.add(methodHandle);
      +            slots += needSlots;
               }
      -        else {
      -            MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters);
      -            formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs);
      +
      +        // Flush the tail slice
      +        if (!cArgs.isEmpty()) {
      +            splits.add(cArgs);
               }
       
      -        return formatter;
      +        return splits;
           }
       
           /**
      @@ -326,15 +396,15 @@ public class ObjectMethods {
            *                     if invoked by a condy
            * @throws IllegalArgumentException if the bootstrap arguments are invalid
            *                                  or inconsistent
      -     * @throws NullPointerException if any argument but {@code lookup} is {@code null},
      -     *                              in the case of the {@code getters} argument, its
      -     *                              contents cannot be {@code null} either
      +     * @throws NullPointerException if any argument is {@code null} or if any element
      +     *                              in the {@code getters} array is {@code null}
            * @throws Throwable if any exception is thrown during call site construction
            */
           public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
                                          Class recordClass,
                                          String names,
                                          MethodHandle... getters) throws Throwable {
      +        requireNonNull(lookup);
               requireNonNull(methodName);
               requireNonNull(type);
               requireNonNull(recordClass);
      @@ -367,7 +437,7 @@ public class ObjectMethods {
                       List nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
                       if (nameList.size() != getterList.size())
                           throw new IllegalArgumentException("Name list and accessor list do not match");
      -                yield makeToString(recordClass, getterList, nameList);
      +                yield makeToString(lookup, recordClass, getters, nameList);
                   }
                   default -> throw new IllegalArgumentException(methodName);
               };
      diff --git a/src/java.base/share/classes/java/math/BigDecimal.java b/src/java.base/share/classes/java/math/BigDecimal.java
      index 8660a4513959af83beb6e9c0ec34b8a96c7cc4c7..b13906ebae9ce8c3466c16a6ac399490244f96fb 100644
      --- a/src/java.base/share/classes/java/math/BigDecimal.java
      +++ b/src/java.base/share/classes/java/math/BigDecimal.java
      @@ -4405,7 +4405,7 @@ public class BigDecimal extends Number implements Comparable {
                   x = -x;
               if (y < 0)
                   y = -y;
      -        return (x < y) ? -1 : ((x == y) ? 0 : 1);
      +        return Long.compare(x, y);
           }
       
           private static int saturateLong(long s) {
      diff --git a/src/java.base/share/classes/java/net/CookieManager.java b/src/java.base/share/classes/java/net/CookieManager.java
      index adc405b9b81b3788a2aa72e15201a3b52a6df181..b1540ad5612b9dca151c740cb3fe97782f12aef3 100644
      --- a/src/java.base/share/classes/java/net/CookieManager.java
      +++ b/src/java.base/share/classes/java/net/CookieManager.java
      @@ -447,13 +447,7 @@ public class CookieManager extends CookieHandler
                   // Check creation time. Sort older first
                   long creation1 = c1.getCreationTime();
                   long creation2 = c2.getCreationTime();
      -            if (creation1 < creation2) {
      -                return -1;
      -            }
      -            if (creation1 > creation2) {
      -                return 1;
      -            }
      -            return 0;
      +            return Long.compare(creation1, creation2);
               }
           }
       }
      diff --git a/src/java.base/share/classes/java/net/DatagramSocketImpl.java b/src/java.base/share/classes/java/net/DatagramSocketImpl.java
      index 0b77a7dd33b0152f0bb4a71de9c38167f1ee3775..c0b282bab56c7ea1a3819298901ad6d2b7a60f04 100644
      --- a/src/java.base/share/classes/java/net/DatagramSocketImpl.java
      +++ b/src/java.base/share/classes/java/net/DatagramSocketImpl.java
      @@ -27,6 +27,7 @@ package java.net;
       
       import java.io.FileDescriptor;
       import java.io.IOException;
      +import java.io.UncheckedIOException;
       import java.util.Objects;
       import java.util.Set;
       
      @@ -99,19 +100,30 @@ public abstract class DatagramSocketImpl implements SocketOptions {
            * packet has been received for that address, then a subsequent call to
            * send or receive may throw a PortUnreachableException.
            * Note, there is no guarantee that the exception will be thrown.
      +     *
      +     * @implSpec The default implementation of this method throws {@code SocketException}.
      +     *
            * @param   address the remote InetAddress to connect to
            * @param   port the remote port number
            * @throws  SocketException may be thrown if the socket cannot be
            *          connected to the remote destination
            * @since   1.4
            */
      -    protected void connect(InetAddress address, int port) throws SocketException {}
      +    protected void connect(InetAddress address, int port) throws SocketException {
      +        throw new SocketException("connect not implemented");
      +    }
       
           /**
            * Disconnects a datagram socket from its remote destination.
      +     *
      +     * @implSpec The default implementation of this method throws {@code UncheckedIOException}.
      +     *
      +     * @throws UncheckedIOException if disconnect fails or no implementation is provided
            * @since 1.4
            */
      -    protected void disconnect() {}
      +    protected void disconnect() {
      +        throw new UncheckedIOException(new SocketException("disconnect not implemented"));
      +    }
       
           /**
            * Peek at the packet to see who it is from. Updates the specified {@code InetAddress}
      diff --git a/src/java.base/share/classes/java/net/HttpCookie.java b/src/java.base/share/classes/java/net/HttpCookie.java
      index dd8ae13914d1c8f4d181450f27db275abc70a532..0214359ccded8a2c4aad9bfe7b1b7bf882be2809 100644
      --- a/src/java.base/share/classes/java/net/HttpCookie.java
      +++ b/src/java.base/share/classes/java/net/HttpCookie.java
      @@ -1078,13 +1078,13 @@ public final class HttpCookie implements Cloneable {
               int version = 0;
       
               header = header.toLowerCase();
      -        if (header.indexOf("expires=") != -1) {
      +        if (header.contains("expires=")) {
                   // only netscape cookie using 'expires'
                   version = 0;
      -        } else if (header.indexOf("version=") != -1) {
      +        } else if (header.contains("version=")) {
                   // version is mandatory for rfc 2965/2109 cookie
                   version = 1;
      -        } else if (header.indexOf("max-age") != -1) {
      +        } else if (header.contains("max-age")) {
                   // rfc 2965/2109 use 'max-age'
                   version = 1;
               } else if (startsWithIgnoreCase(header, SET_COOKIE2)) {
      diff --git a/src/java.base/share/classes/java/net/HttpURLConnection.java b/src/java.base/share/classes/java/net/HttpURLConnection.java
      index 9f7779dd011b1d99d70d2a7c610f7b28e84e2070..dba500f017d2d34e07517d7fb42960364772ada2 100644
      --- a/src/java.base/share/classes/java/net/HttpURLConnection.java
      +++ b/src/java.base/share/classes/java/net/HttpURLConnection.java
      @@ -600,7 +600,7 @@ public abstract class HttpURLConnection extends URLConnection {
           public long getHeaderFieldDate(String name, long Default) {
               String dateString = getHeaderField(name);
               try {
      -            if (dateString.indexOf("GMT") == -1) {
      +            if (!dateString.contains("GMT")) {
                       dateString = dateString+" GMT";
                   }
                   return Date.parse(dateString);
      diff --git a/src/java.base/share/classes/java/net/Inet4AddressImpl.java b/src/java.base/share/classes/java/net/Inet4AddressImpl.java
      index 4cbe28f998b1e1f022beb827cf7df80d2adc548d..c7feaf4c195e6e8d0d389e011cb2c2140387f69f 100644
      --- a/src/java.base/share/classes/java/net/Inet4AddressImpl.java
      +++ b/src/java.base/share/classes/java/net/Inet4AddressImpl.java
      @@ -24,6 +24,9 @@
        */
       package java.net;
       import java.io.IOException;
      +import java.net.spi.InetAddressResolver.LookupPolicy;
      +
      +import static java.net.spi.InetAddressResolver.LookupPolicy.IPV4;
       
       /*
        * Package private implementation of InetAddressImpl for IPv4.
      @@ -32,8 +35,14 @@ import java.io.IOException;
        */
       final class Inet4AddressImpl implements InetAddressImpl {
           public native String getLocalHostName() throws UnknownHostException;
      -    public native InetAddress[]
      -        lookupAllHostAddr(String hostname) throws UnknownHostException;
      +    public InetAddress[] lookupAllHostAddr(String hostname, LookupPolicy lookupPolicy)
      +            throws UnknownHostException {
      +        if ((lookupPolicy.characteristics() & IPV4) == 0) {
      +            throw new UnknownHostException(hostname);
      +        }
      +        return lookupAllHostAddr(hostname);
      +    }
      +    private native InetAddress[] lookupAllHostAddr(String hostname) throws UnknownHostException;
           public native String getHostByAddr(byte[] addr) throws UnknownHostException;
           private native boolean isReachable0(byte[] addr, int timeout, byte[] ifaddr, int ttl) throws IOException;
       
      diff --git a/src/java.base/share/classes/java/net/Inet6Address.java b/src/java.base/share/classes/java/net/Inet6Address.java
      index bbb31b452418a535f46d27ce53f642d00a577d28..751623536e765794de62ce1597af76455d1d5348 100644
      --- a/src/java.base/share/classes/java/net/Inet6Address.java
      +++ b/src/java.base/share/classes/java/net/Inet6Address.java
      @@ -119,10 +119,9 @@ import java.util.Arrays;
        * 

      Special IPv6 address

      * *
      - * - * - * - * - *
      Description of IPv4-mapped address
      IPv4-mapped addressOf the form ::ffff:w.x.y.z, this IPv6 address is used to + *
      + *
      IPv4-mapped address
      + *
      Of the form ::ffff:w.x.y.z, this IPv6 address is used to * represent an IPv4 address. It allows the native program to * use the same address data structure and also the same * socket when communicating with both IPv4 and IPv6 nodes. @@ -132,12 +131,13 @@ import java.util.Arrays; * return an IPv4-mapped address. These classes can take an * IPv4-mapped address as input, both in byte array and text * representation. However, it will be converted into an IPv4 - * address.
      + * address. + * + * * *

      Textual representation of IPv6 scoped addresses

      * - *

      The textual representation of IPv6 addresses as described above can be + *

      The textual representation of IPv6 addresses as described above can be * extended to specify IPv6 scoped addresses. This extension to the basic * addressing architecture is described in [draft-ietf-ipngwg-scoping-arch-04.txt]. * diff --git a/src/java.base/share/classes/java/net/Inet6AddressImpl.java b/src/java.base/share/classes/java/net/Inet6AddressImpl.java index f956a50e311229b900362aeb35c95a6f5b2b202f..87fefbe37ba32f18e71daecb33120759c95cd17d 100644 --- a/src/java.base/share/classes/java/net/Inet6AddressImpl.java +++ b/src/java.base/share/classes/java/net/Inet6AddressImpl.java @@ -25,10 +25,9 @@ package java.net; import java.io.IOException; +import java.net.spi.InetAddressResolver.LookupPolicy; -import static java.net.InetAddress.IPv6; -import static java.net.InetAddress.PREFER_IPV6_VALUE; -import static java.net.InetAddress.PREFER_SYSTEM_VALUE; +import static java.net.InetAddress.PLATFORM_LOOKUP_POLICY; /* * Package private implementation of InetAddressImpl for dual @@ -48,8 +47,13 @@ final class Inet6AddressImpl implements InetAddressImpl { public native String getLocalHostName() throws UnknownHostException; - public native InetAddress[] lookupAllHostAddr(String hostname) - throws UnknownHostException; + public InetAddress[] lookupAllHostAddr(String hostname, LookupPolicy lookupPolicy) + throws UnknownHostException { + return lookupAllHostAddr(hostname, lookupPolicy.characteristics()); + } + + private native InetAddress[] lookupAllHostAddr(String hostname, int characteristics) + throws UnknownHostException; public native String getHostByAddr(byte[] addr) throws UnknownHostException; @@ -96,8 +100,9 @@ final class Inet6AddressImpl implements InetAddressImpl { public synchronized InetAddress anyLocalAddress() { if (anyLocalAddress == null) { - if (InetAddress.preferIPv6Address == PREFER_IPV6_VALUE || - InetAddress.preferIPv6Address == PREFER_SYSTEM_VALUE) { + int flags = PLATFORM_LOOKUP_POLICY.characteristics(); + if (InetAddress.ipv6AddressesFirst(flags) || + InetAddress.systemAddressesOrder(flags)) { anyLocalAddress = new Inet6Address(); anyLocalAddress.holder().hostName = "::"; } else { @@ -109,9 +114,9 @@ final class Inet6AddressImpl implements InetAddressImpl { public synchronized InetAddress loopbackAddress() { if (loopbackAddress == null) { - boolean preferIPv6Address = - InetAddress.preferIPv6Address == PREFER_IPV6_VALUE || - InetAddress.preferIPv6Address == PREFER_SYSTEM_VALUE; + int flags = PLATFORM_LOOKUP_POLICY.characteristics(); + boolean preferIPv6Address = InetAddress.ipv6AddressesFirst(flags) || + InetAddress.systemAddressesOrder(flags); for (int i = 0; i < 2; i++) { InetAddress address; diff --git a/src/java.base/share/classes/java/net/InetAddress.java b/src/java.base/share/classes/java/net/InetAddress.java index b43c88e4f0e62150fb8badd31c49fbb3ea515e07..3875216768be9deab04ee261dc940cba55f0c336 100644 --- a/src/java.base/share/classes/java/net/InetAddress.java +++ b/src/java.base/share/classes/java/net/InetAddress.java @@ -25,6 +25,11 @@ package java.net; +import java.net.spi.InetAddressResolver; +import java.net.spi.InetAddressResolverProvider; +import java.net.spi.InetAddressResolver.LookupPolicy; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.List; import java.util.NavigableSet; import java.util.ArrayList; @@ -40,19 +45,31 @@ import java.io.ObjectInputStream.GetField; import java.io.ObjectOutputStream; import java.io.ObjectOutputStream.PutField; import java.lang.annotation.Native; +import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicLong; import java.util.Arrays; +import java.util.concurrent.locks.ReentrantLock; +import java.util.stream.Stream; + +import jdk.internal.misc.VM; import jdk.internal.access.JavaNetInetAddressAccess; import jdk.internal.access.SharedSecrets; +import jdk.internal.vm.annotation.Stable; +import sun.net.ResolverProviderConfiguration; import sun.security.action.*; import sun.net.InetAddressCachePolicy; import sun.net.util.IPAddressUtil; import sun.nio.cs.UTF_8; +import static java.net.spi.InetAddressResolver.LookupPolicy.IPV4; +import static java.net.spi.InetAddressResolver.LookupPolicy.IPV4_FIRST; +import static java.net.spi.InetAddressResolver.LookupPolicy.IPV6; +import static java.net.spi.InetAddressResolver.LookupPolicy.IPV6_FIRST; + /** * This class represents an Internet Protocol (IP) address. * @@ -128,25 +145,35 @@ import sun.nio.cs.UTF_8; * address format, please refer to Inet6Address#format. * - *

      There is a couple of - * System Properties affecting how IPv4 and IPv6 addresses are used.

      + *

      There is a couple of + * System Properties affecting how IPv4 and IPv6 addresses are used. * - *

      Host Name Resolution

      + *

      Host Name Resolution

      + * + *

      The InetAddress class provides methods to resolve host names to + * their IP addresses and vice versa. The actual resolution is delegated to an + * {@linkplain InetAddressResolver InetAddress resolver}. * - * Host name-to-IP address resolution is accomplished through - * the use of a combination of local machine configuration information - * and network naming services such as the Domain Name System (DNS) - * and Network Information Service(NIS). The particular naming - * services(s) being used is by default the local machine configured - * one. For any host name, its corresponding IP address is returned. + *

      Host name-to-IP address resolution maps a host name to an IP address. + * For any host name, its corresponding IP address is returned. * *

      Reverse name resolution means that for any IP address, * the host associated with the IP address is returned. * - *

      The InetAddress class provides methods to resolve host names to - * their IP addresses and vice versa. + *

      The built-in InetAddress resolver implementation does + * host name-to-IP address resolution and vice versa through the use of + * a combination of local machine configuration information and network + * naming services such as the Domain Name System (DNS) and the Lightweight Directory + * Access Protocol (LDAP). + * The particular naming services that the built-in resolver uses by default + * depends on the configuration of the local machine. + * + *

      {@code InetAddress} has a service provider mechanism for InetAddress resolvers + * that allows a custom InetAddress resolver to be used instead of the built-in implementation. + * {@link InetAddressResolverProvider} is the service provider class. Its API docs provide all the + * details on this mechanism. * - *

      InetAddress Caching

      + *

      InetAddress Caching

      * * The InetAddress class has a cache to store successful as well as * unsuccessful host name resolutions. @@ -198,10 +225,6 @@ import sun.nio.cs.UTF_8; */ public class InetAddress implements java.io.Serializable { - @Native static final int PREFER_IPV4_VALUE = 0; - @Native static final int PREFER_IPV6_VALUE = 1; - @Native static final int PREFER_SYSTEM_VALUE = 2; - /** * Specify the address family: Internet Protocol, Version 4 * @since 1.4 @@ -214,9 +237,6 @@ public class InetAddress implements java.io.Serializable { */ @Native static final int IPv6 = 2; - /* Specify address family preference */ - static transient final int preferIPv6Address; - static class InetAddressHolder { /** * Reserve the original application specified hostname. @@ -288,8 +308,11 @@ public class InetAddress implements java.io.Serializable { return holder; } - /* Used to store the name service provider */ - private static transient NameService nameService; + /* Used to store the system-wide resolver */ + @Stable + private static volatile InetAddressResolver resolver; + + private static final InetAddressResolver BUILTIN_RESOLVER; /** * Used to store the best available hostname. @@ -301,22 +324,25 @@ public class InetAddress implements java.io.Serializable { @java.io.Serial private static final long serialVersionUID = 3286316764910316507L; + // "java.net.preferIPv4Stack" system property value + private static final String PREFER_IPV4_STACK_VALUE; + + // "java.net.preferIPv6Addresses" system property value + private static final String PREFER_IPV6_ADDRESSES_VALUE; + + // "jdk.net.hosts.file" system property value + private static final String HOSTS_FILE_NAME; + /* * Load net library into runtime, and perform initializations. */ static { - String str = GetPropertyAction.privilegedGetProperty("java.net.preferIPv6Addresses"); - if (str == null) { - preferIPv6Address = PREFER_IPV4_VALUE; - } else if (str.equalsIgnoreCase("true")) { - preferIPv6Address = PREFER_IPV6_VALUE; - } else if (str.equalsIgnoreCase("false")) { - preferIPv6Address = PREFER_IPV4_VALUE; - } else if (str.equalsIgnoreCase("system")) { - preferIPv6Address = PREFER_SYSTEM_VALUE; - } else { - preferIPv6Address = PREFER_IPV4_VALUE; - } + PREFER_IPV4_STACK_VALUE = + GetPropertyAction.privilegedGetProperty("java.net.preferIPv4Stack"); + PREFER_IPV6_ADDRESSES_VALUE = + GetPropertyAction.privilegedGetProperty("java.net.preferIPv6Addresses"); + HOSTS_FILE_NAME = + GetPropertyAction.privilegedGetProperty("jdk.net.hosts.file"); jdk.internal.loader.BootLoader.loadLibrary("net"); SharedSecrets.setJavaNetInetAddressAccess( new JavaNetInetAddressAccess() { @@ -324,13 +350,6 @@ public class InetAddress implements java.io.Serializable { return ia.holder.getOriginalHostName(); } - public InetAddress getByName(String hostName, - InetAddress hostAddress) - throws UnknownHostException - { - return InetAddress.getByName(hostName, hostAddress); - } - public int addressValue(Inet4Address inet4Address) { return inet4Address.addressValue(); } @@ -343,6 +362,131 @@ public class InetAddress implements java.io.Serializable { init(); } + /** + * Creates an address lookup policy from {@code "java.net.preferIPv4Stack"}, + * {@code "java.net.preferIPv6Addresses"} system property values, and O/S configuration. + */ + private static final LookupPolicy initializePlatformLookupPolicy() { + // Calculate AddressFamily value first + boolean ipv4Available = isIPv4Available(); + if ("true".equals(PREFER_IPV4_STACK_VALUE) && ipv4Available) { + return LookupPolicy.of(IPV4); + } + // Check if IPv6 is not supported + if (InetAddress.impl instanceof Inet4AddressImpl) { + return LookupPolicy.of(IPV4); + } + // Check if system supports IPv4, if not use IPv6 + if (!ipv4Available) { + return LookupPolicy.of(IPV6); + } + // If both address families are needed - check preferIPv6Addresses value + if (PREFER_IPV6_ADDRESSES_VALUE != null) { + if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("true")) { + return LookupPolicy.of(IPV4 | IPV6 | IPV6_FIRST); + } + if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("false")) { + return LookupPolicy.of(IPV4 | IPV6 | IPV4_FIRST); + } + if (PREFER_IPV6_ADDRESSES_VALUE.equalsIgnoreCase("system")) { + return LookupPolicy.of(IPV4 | IPV6); + } + } + // Default value with both address families needed - IPv4 addresses come first + return LookupPolicy.of(IPV4 | IPV6 | IPV4_FIRST); + } + + static boolean systemAddressesOrder(int lookupCharacteristics) { + return (lookupCharacteristics & (IPV4_FIRST | IPV6_FIRST)) == 0; + } + + static boolean ipv4AddressesFirst(int lookupCharacteristics) { + return (lookupCharacteristics & IPV4_FIRST) != 0; + } + + static boolean ipv6AddressesFirst(int lookupCharacteristics) { + return (lookupCharacteristics & IPV6_FIRST) != 0; + } + + // Native method to check if IPv4 is available + private static native boolean isIPv4Available(); + + /** + * The {@code RuntimePermission("inetAddressResolverProvider")} is + * necessary to subclass and instantiate the {@code InetAddressResolverProvider} + * class, as well as to obtain resolver from an instance of that class, + * and it is also required to obtain the operating system name resolution configurations. + */ + private static final RuntimePermission INET_ADDRESS_RESOLVER_PERMISSION = + new RuntimePermission("inetAddressResolverProvider"); + + private static final ReentrantLock RESOLVER_LOCK = new ReentrantLock(); + private static volatile InetAddressResolver bootstrapResolver; + + @SuppressWarnings("removal") + private static InetAddressResolver resolver() { + InetAddressResolver cns = resolver; + if (cns != null) { + return cns; + } + if (VM.isBooted()) { + RESOLVER_LOCK.lock(); + boolean bootstrapSet = false; + try { + cns = resolver; + if (cns != null) { + return cns; + } + // Protection against provider calling InetAddress APIs during initialization + if (bootstrapResolver != null) { + return bootstrapResolver; + } + bootstrapResolver = BUILTIN_RESOLVER; + bootstrapSet = true; + + if (HOSTS_FILE_NAME != null) { + // The default resolver service is already host file resolver + cns = BUILTIN_RESOLVER; + } else if (System.getSecurityManager() != null) { + PrivilegedAction pa = InetAddress::loadResolver; + cns = AccessController.doPrivileged( + pa, null, INET_ADDRESS_RESOLVER_PERMISSION); + } else { + cns = loadResolver(); + } + + InetAddress.resolver = cns; + return cns; + } finally { + // We want to clear bootstrap resolver reference only after an attempt to + // instantiate a resolver has been completed. + if (bootstrapSet) { + bootstrapResolver = null; + } + RESOLVER_LOCK.unlock(); + } + } else { + return BUILTIN_RESOLVER; + } + } + + private static InetAddressResolver loadResolver() { + return ServiceLoader.load(InetAddressResolverProvider.class) + .findFirst() + .map(nsp -> nsp.get(builtinConfiguration())) + .orElse(BUILTIN_RESOLVER); + } + + private static InetAddressResolverProvider.Configuration builtinConfiguration() { + return new ResolverProviderConfiguration(BUILTIN_RESOLVER, () -> { + try { + return impl.getLocalHostName(); + } catch (UnknownHostException unknownHostException) { + return "localhost"; + } + }); + } + /** * Constructor for the Socket.accept() method. * This creates an empty InetAddress, which is filled in by @@ -555,7 +699,7 @@ public class InetAddress implements java.io.Serializable { * this host name will be remembered and returned; * otherwise, a reverse name lookup will be performed * and the result will be returned based on the system - * configured name lookup service. If a lookup of the name service + * configured resolver. If a lookup of the name service * is required, call * {@link #getCanonicalHostName() getCanonicalHostName}. * @@ -656,10 +800,11 @@ public class InetAddress implements java.io.Serializable { * @see SecurityManager#checkConnect */ private static String getHostFromNameService(InetAddress addr, boolean check) { - String host = null; + String host; + var resolver = resolver(); try { // first lookup the hostname - host = nameService.getHostByAddr(addr.getAddress()); + host = resolver.lookupByAddress(addr.getAddress()); /* check to see if calling code is allowed to know * the hostname for this IP address, ie, connect to the host @@ -691,11 +836,12 @@ public class InetAddress implements java.io.Serializable { host = addr.getHostAddress(); return host; } - } catch (SecurityException e) { + } catch (RuntimeException | UnknownHostException e) { + // 'resolver.lookupByAddress' and 'InetAddress.getAllByName0' delegate to + // the system-wide resolver, which could be a custom one. At that point we + // treat any unexpected RuntimeException thrown by the resolver as we would + // treat an UnknownHostException or an unmatched host name. host = addr.getHostAddress(); - } catch (UnknownHostException e) { - host = addr.getHostAddress(); - // let next provider resolve the hostname } return host; } @@ -755,8 +901,9 @@ public class InetAddress implements java.io.Serializable { * string returned is of the form: hostname / literal IP * address. * - * If the host name is unresolved, no reverse name service lookup - * is performed. The hostname part will be represented by an empty string. + * If the host name is unresolved, no reverse lookup + * is performed. The hostname part will be represented + * by an empty string. * * @return a string representation of this IP address. */ @@ -821,11 +968,9 @@ public class InetAddress implements java.io.Serializable { // in cache when the result is obtained private static final class NameServiceAddresses implements Addresses { private final String host; - private final InetAddress reqAddr; - NameServiceAddresses(String host, InetAddress reqAddr) { + NameServiceAddresses(String host) { this.host = host; - this.reqAddr = reqAddr; } @Override @@ -849,7 +994,7 @@ public class InetAddress implements java.io.Serializable { UnknownHostException ex; int cachePolicy; try { - inetAddresses = getAddressesFromNameService(host, reqAddr); + inetAddresses = getAddressesFromNameService(host); ex = null; cachePolicy = InetAddressCachePolicy.get(); } catch (UnknownHostException uhe) { @@ -875,7 +1020,7 @@ public class InetAddress implements java.io.Serializable { expirySet.add(cachedAddresses); } } - if (inetAddresses == null) { + if (inetAddresses == null || inetAddresses.length == 0) { throw ex == null ? new UnknownHostException(host) : ex; } return inetAddresses; @@ -889,81 +1034,48 @@ public class InetAddress implements java.io.Serializable { } /** - * NameService provides host and address lookup service - * - * @since 9 - */ - private interface NameService { - - /** - * Lookup a host mapping by name. Retrieve the IP addresses - * associated with a host - * - * @param host the specified hostname - * @return array of IP addresses for the requested host - * @throws UnknownHostException - * if no IP address for the {@code host} could be found - */ - InetAddress[] lookupAllHostAddr(String host) - throws UnknownHostException; - - /** - * Lookup the host corresponding to the IP address provided - * - * @param addr byte array representing an IP address - * @return {@code String} representing the host name mapping - * @throws UnknownHostException - * if no host found for the specified IP address - */ - String getHostByAddr(byte[] addr) throws UnknownHostException; - - } - - /** - * The default NameService implementation, which delegates to the underlying + * The default InetAddressResolver implementation, which delegates to the underlying * OS network libraries to resolve host address mappings. * * @since 9 */ - private static final class PlatformNameService implements NameService { + private static final class PlatformResolver implements InetAddressResolver { - public InetAddress[] lookupAllHostAddr(String host) - throws UnknownHostException - { - return impl.lookupAllHostAddr(host); + public Stream lookupByName(String host, LookupPolicy policy) + throws UnknownHostException { + Objects.requireNonNull(host); + Objects.requireNonNull(policy); + return Arrays.stream(impl.lookupAllHostAddr(host, policy)); } - public String getHostByAddr(byte[] addr) - throws UnknownHostException - { + public String lookupByAddress(byte[] addr) + throws UnknownHostException { + Objects.requireNonNull(addr); + if (addr.length != Inet4Address.INADDRSZ && addr.length != Inet6Address.INADDRSZ) { + throw new IllegalArgumentException("Invalid address length"); + } return impl.getHostByAddr(addr); } } /** - * The HostsFileNameService provides host address mapping + * The HostsFileResolver provides host address mapping * by reading the entries in a hosts file, which is specified by * {@code jdk.net.hosts.file} system property * *

      The file format is that which corresponds with the /etc/hosts file * IP Address host alias list. * - *

      When the file lookup is enabled it replaces the default NameService + *

      When the file lookup is enabled it replaces the default InetAddressResolver * implementation * * @since 9 */ - private static final class HostsFileNameService implements NameService { - - private static final InetAddress[] EMPTY_ARRAY = new InetAddress[0]; - - // Specify if only IPv4 addresses should be returned by HostsFileService implementation - private static final boolean preferIPv4Stack = Boolean.parseBoolean( - GetPropertyAction.privilegedGetProperty("java.net.preferIPv4Stack")); + private static final class HostsFileResolver implements InetAddressResolver { private final String hostsFile; - public HostsFileNameService(String hostsFileName) { + public HostsFileResolver(String hostsFileName) { this.hostsFile = hostsFileName; } @@ -974,17 +1086,22 @@ public class InetAddress implements java.io.Serializable { * * @param addr byte array representing an IP address * @return {@code String} representing the host name mapping - * @throws UnknownHostException - * if no host found for the specified IP address + * @throws UnknownHostException if no host found for the specified IP address + * @throws IllegalArgumentException if IP address is of illegal length + * @throws NullPointerException if addr is {@code null} */ @Override - public String getHostByAddr(byte[] addr) throws UnknownHostException { + public String lookupByAddress(byte[] addr) throws UnknownHostException { String hostEntry; String host = null; + Objects.requireNonNull(addr); + // Check the length of the address array + if (addr.length != Inet4Address.INADDRSZ && addr.length != Inet6Address.INADDRSZ) { + throw new IllegalArgumentException("Invalid address length"); + } try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), - UTF_8.INSTANCE)) - { + UTF_8.INSTANCE)) { while (hostsFileScanner.hasNextLine()) { hostEntry = hostsFileScanner.nextLine(); if (!hostEntry.startsWith("#")) { @@ -1020,22 +1137,31 @@ public class InetAddress implements java.io.Serializable { * with the specified host name. * * @param host the specified hostname - * @return array of IP addresses for the requested host + * @param lookupPolicy IP addresses lookup policy which specifies addresses + * family and their order + * @return stream of IP addresses for the requested host + * @throws NullPointerException if either parameter is {@code null} * @throws UnknownHostException * if no IP address for the {@code host} could be found */ - public InetAddress[] lookupAllHostAddr(String host) + public Stream lookupByName(String host, LookupPolicy lookupPolicy) throws UnknownHostException { String hostEntry; String addrStr; byte addr[]; + + Objects.requireNonNull(host); + Objects.requireNonNull(lookupPolicy); List inetAddresses = new ArrayList<>(); List inet4Addresses = new ArrayList<>(); List inet6Addresses = new ArrayList<>(); + int flags = lookupPolicy.characteristics(); + boolean needIPv4 = (flags & IPv4) != 0; + boolean needIPv6 = (flags & IPv6) != 0; // lookup the file and create a list InetAddress for the specified host try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), - UTF_8.INSTANCE)) { + UTF_8.INSTANCE)) { while (hostsFileScanner.hasNextLine()) { hostEntry = hostsFileScanner.nextLine(); if (!hostEntry.startsWith("#")) { @@ -1047,10 +1173,10 @@ public class InetAddress implements java.io.Serializable { if (addr != null) { InetAddress address = InetAddress.getByAddress(host, addr); inetAddresses.add(address); - if (address instanceof Inet4Address) { + if (address instanceof Inet4Address && needIPv4) { inet4Addresses.add(address); } - if (address instanceof Inet6Address) { + if (address instanceof Inet6Address && needIPv6) { inet6Addresses.add(address); } } @@ -1062,33 +1188,38 @@ public class InetAddress implements java.io.Serializable { throw new UnknownHostException("Unable to resolve host " + host + " as hosts file " + hostsFile + " not found "); } - - List res; - // If "preferIPv4Stack" system property is set to "true" then return - // only IPv4 addresses - if (preferIPv4Stack) { - res = inet4Addresses; - } else { - // Otherwise, analyse "preferIPv6Addresses" value - res = switch (preferIPv6Address) { - case PREFER_IPV4_VALUE -> concatAddresses(inet4Addresses, inet6Addresses); - case PREFER_IPV6_VALUE -> concatAddresses(inet6Addresses, inet4Addresses); - default -> inetAddresses; - }; + // Check if only IPv4 addresses are requested + if (needIPv4 && !needIPv6) { + checkResultsList(inet4Addresses, host); + return inet4Addresses.stream(); } - - if (res.isEmpty()) { - throw new UnknownHostException("Unable to resolve host " + host - + " in hosts file " + hostsFile); + // Check if only IPv6 addresses are requested + if (!needIPv4 && needIPv6) { + checkResultsList(inet6Addresses, host); + return inet6Addresses.stream(); } - return res.toArray(EMPTY_ARRAY); + // If both type of addresses are requested: + // First, check if there is any results. Then arrange + // addresses according to LookupPolicy value. + checkResultsList(inetAddresses, host); + if (ipv6AddressesFirst(flags)) { + return Stream.concat(inet6Addresses.stream(), inet4Addresses.stream()); + } else if (ipv4AddressesFirst(flags)) { + return Stream.concat(inet4Addresses.stream(), inet6Addresses.stream()); + } + // Only "system" addresses order is possible at this stage + assert systemAddressesOrder(flags); + return inetAddresses.stream(); } - private static List concatAddresses(List firstPart, - List secondPart) { - List result = new ArrayList<>(firstPart); - result.addAll(secondPart); - return result; + // Checks if result list with addresses is not empty. + // If it is empty throw an UnknownHostException. + private void checkResultsList(List addressesList, String hostName) + throws UnknownHostException { + if (addressesList.isEmpty()) { + throw new UnknownHostException("Unable to resolve host " + hostName + + " in hosts file " + hostsFile); + } } private String removeComments(String hostsEntry) { @@ -1130,45 +1261,52 @@ public class InetAddress implements java.io.Serializable { static final InetAddressImpl impl; + /** + * Platform-wide {@code LookupPolicy} initialized from {@code "java.net.preferIPv4Stack"}, + * {@code "java.net.preferIPv6Addresses"} system properties. + */ + static final LookupPolicy PLATFORM_LOOKUP_POLICY; + static { // create the impl impl = InetAddressImplFactory.create(); - // create name service - nameService = createNameService(); + // impl must be initialized before calling this method + PLATFORM_LOOKUP_POLICY = initializePlatformLookupPolicy(); + + // create built-in resolver + BUILTIN_RESOLVER = createBuiltinInetAddressResolver(); } /** - * Create an instance of the NameService interface based on + * Create an instance of the InetAddressResolver interface based on * the setting of the {@code jdk.net.hosts.file} system property. * - *

      The default NameService is the PlatformNameService, which typically + *

      The default InetAddressResolver is the PlatformResolver, which typically * delegates name and address resolution calls to the underlying * OS network libraries. * - *

      A HostsFileNameService is created if the {@code jdk.net.hosts.file} + *

      A HostsFileResolver is created if the {@code jdk.net.hosts.file} * system property is set. If the specified file doesn't exist, the name or * address lookup will result in an UnknownHostException. Thus, non existent * hosts file is handled as if the file is empty. * - * @return a NameService + * @return an InetAddressResolver */ - private static NameService createNameService() { - - String hostsFileName = - GetPropertyAction.privilegedGetProperty("jdk.net.hosts.file"); - NameService theNameService; - if (hostsFileName != null) { - theNameService = new HostsFileNameService(hostsFileName); + private static InetAddressResolver createBuiltinInetAddressResolver() { + InetAddressResolver theResolver; + if (HOSTS_FILE_NAME != null) { + theResolver = new HostsFileResolver(HOSTS_FILE_NAME); } else { - theNameService = new PlatformNameService(); + theResolver = new PlatformResolver(); } - return theNameService; + return theResolver; } /** * Creates an InetAddress based on the provided host name and IP address. - * No name service is checked for the validity of the address. + * The system-wide {@linkplain InetAddressResolver resolver} is not used to check + * the validity of the address. * *

      The host name can either be a machine name, such as * "{@code www.example.com}", or a textual representation of its IP @@ -1251,15 +1389,9 @@ public class InetAddress implements java.io.Serializable { return InetAddress.getAllByName(host)[0]; } - // called from deployment cache manager - private static InetAddress getByName(String host, InetAddress reqAddr) - throws UnknownHostException { - return InetAddress.getAllByName(host, reqAddr)[0]; - } - /** * Given the name of a host, returns an array of its IP addresses, - * based on the configured name service on the system. + * based on the configured system {@linkplain InetAddressResolver resolver}. * *

      The host name can either be a machine name, such as * "{@code www.example.com}", or a textual representation of its IP @@ -1298,11 +1430,6 @@ public class InetAddress implements java.io.Serializable { */ public static InetAddress[] getAllByName(String host) throws UnknownHostException { - return getAllByName(host, null); - } - - private static InetAddress[] getAllByName(String host, InetAddress reqAddr) - throws UnknownHostException { if (host == null || host.isEmpty()) { InetAddress[] ret = new InetAddress[1]; @@ -1364,7 +1491,7 @@ public class InetAddress implements java.io.Serializable { // We were expecting an IPv6 Literal, but got something else throw new UnknownHostException("["+host+"]"); } - return getAllByName0(host, reqAddr, true, true); + return getAllByName0(host, true, true); } /** @@ -1414,25 +1541,18 @@ public class InetAddress implements java.io.Serializable { return zone; } - private static InetAddress[] getAllByName0 (String host) - throws UnknownHostException - { - return getAllByName0(host, true); - } - /** * package private so SocketPermission can call it */ static InetAddress[] getAllByName0 (String host, boolean check) throws UnknownHostException { - return getAllByName0 (host, null, check, true); + return getAllByName0(host, check, true); } /** * Designated lookup method. * * @param host host name to look up - * @param reqAddr requested address to be the 1st in returned array * @param check perform security check * @param useCache use cached value if not expired else always * perform name service lookup (and cache the result) @@ -1440,7 +1560,6 @@ public class InetAddress implements java.io.Serializable { * @throws UnknownHostException if host name is not found */ private static InetAddress[] getAllByName0(String host, - InetAddress reqAddr, boolean check, boolean useCache) throws UnknownHostException { @@ -1498,7 +1617,7 @@ public class InetAddress implements java.io.Serializable { // the name service and install it within cache... Addresses oldAddrs = cache.putIfAbsent( host, - addrs = new NameServiceAddresses(host, reqAddr) + addrs = new NameServiceAddresses(host) ); if (oldAddrs != null) { // lost putIfAbsent race addrs = oldAddrs; @@ -1509,47 +1628,30 @@ public class InetAddress implements java.io.Serializable { return addrs.get().clone(); } - static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr) + static InetAddress[] getAddressesFromNameService(String host) throws UnknownHostException { - InetAddress[] addresses = null; + Stream addresses = null; UnknownHostException ex = null; + var resolver = resolver(); try { - addresses = nameService.lookupAllHostAddr(host); - } catch (UnknownHostException uhe) { + addresses = resolver.lookupByName(host, PLATFORM_LOOKUP_POLICY); + } catch (RuntimeException | UnknownHostException x) { if (host.equalsIgnoreCase("localhost")) { - addresses = new InetAddress[]{impl.loopbackAddress()}; - } else { + addresses = Stream.of(impl.loopbackAddress()); + } else if (x instanceof UnknownHostException uhe) { ex = uhe; + } else { + ex = new UnknownHostException(); + ex.initCause(x); } } - - if (addresses == null) { + InetAddress[] result = addresses == null ? null + : addresses.toArray(InetAddress[]::new); + if (result == null || result.length == 0) { throw ex == null ? new UnknownHostException(host) : ex; } - - // More to do? - if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) { - // Find it? - int i = 1; - for (; i < addresses.length; i++) { - if (addresses[i].equals(reqAddr)) { - break; - } - } - // Rotate - if (i < addresses.length) { - InetAddress tmp, tmp2 = reqAddr; - for (int j = 0; j < i; j++) { - tmp = addresses[j]; - addresses[j] = tmp2; - tmp2 = tmp; - } - addresses[i] = tmp2; - } - } - - return addresses; + return result; } /** @@ -1557,8 +1659,7 @@ public class InetAddress implements java.io.Serializable { * The argument is in network byte order: the highest order * byte of the address is in {@code getAddress()[0]}. * - *

      This method doesn't block, i.e. no reverse name service lookup - * is performed. + *

      This method doesn't block, i.e. no reverse lookup is performed. * *

      IPv4 address byte array must be 4 bytes long and IPv6 byte array * must be 16 bytes long @@ -1637,7 +1738,7 @@ public class InetAddress implements java.io.Serializable { // call getAllByName0 without security checks and // without using cached data try { - localAddr = getAllByName0(local, null, false, false)[0]; + localAddr = getAllByName0(local, false, false)[0]; } catch (UnknownHostException uhe) { // Rethrow with a more informative error message. UnknownHostException uhe2 = diff --git a/src/java.base/share/classes/java/net/InetAddressImpl.java b/src/java.base/share/classes/java/net/InetAddressImpl.java index a2f8ea010528e11d736f0be388a034f4ad66383a..f0364ffaedf46b86a124d9a71851504e83638b36 100644 --- a/src/java.base/share/classes/java/net/InetAddressImpl.java +++ b/src/java.base/share/classes/java/net/InetAddressImpl.java @@ -24,7 +24,10 @@ */ package java.net; + import java.io.IOException; +import java.net.spi.InetAddressResolver.LookupPolicy; + /* * Package private interface to "implementation" used by * {@link InetAddress}. @@ -38,7 +41,7 @@ sealed interface InetAddressImpl permits Inet4AddressImpl, Inet6AddressImpl { String getLocalHostName() throws UnknownHostException; InetAddress[] - lookupAllHostAddr(String hostname) throws UnknownHostException; + lookupAllHostAddr(String hostname, LookupPolicy lookupPolicy) throws UnknownHostException; String getHostByAddr(byte[] addr) throws UnknownHostException; InetAddress anyLocalAddress(); diff --git a/src/java.base/share/classes/java/net/NetMulticastSocket.java b/src/java.base/share/classes/java/net/NetMulticastSocket.java index 79959e3ef6cd10ab49e4209e740320acf66708c4..4160156997a27d94d939da9ce8b2dca465f25fad 100644 --- a/src/java.base/share/classes/java/net/NetMulticastSocket.java +++ b/src/java.base/share/classes/java/net/NetMulticastSocket.java @@ -56,11 +56,6 @@ final class NetMulticastSocket extends MulticastSocket { */ private final DatagramSocketImpl impl; - /** - * Are we using an older DatagramSocketImpl? - */ - private final boolean oldImpl; - /** * Set when a socket is ST_CONNECTED until we are certain * that any packets which might have been received prior @@ -76,11 +71,9 @@ final class NetMulticastSocket extends MulticastSocket { * Connection state: * ST_NOT_CONNECTED = socket not connected * ST_CONNECTED = socket connected - * ST_CONNECTED_NO_IMPL = socket connected but not at impl level */ static final int ST_NOT_CONNECTED = 0; static final int ST_CONNECTED = 1; - static final int ST_CONNECTED_NO_IMPL = 2; int connectState = ST_NOT_CONNECTED; @@ -97,7 +90,6 @@ final class NetMulticastSocket extends MulticastSocket { NetMulticastSocket(DatagramSocketImpl impl) { super((MulticastSocket) null); this.impl = Objects.requireNonNull(impl); - this.oldImpl = checkOldImpl(impl); } /** @@ -135,59 +127,24 @@ final class NetMulticastSocket extends MulticastSocket { if (!isBound()) bind(new InetSocketAddress(0)); - // old impls do not support connect/disconnect - if (oldImpl) { - connectState = ST_CONNECTED_NO_IMPL; - } else { - try { - getImpl().connect(address, port); - - // socket is now connected by the impl - connectState = ST_CONNECTED; - // Do we need to filter some packets? - int avail = getImpl().dataAvailable(); - if (avail == -1) { - throw new SocketException(); - } - explicitFilter = avail > 0; - if (explicitFilter) { - bytesLeftToFilter = getReceiveBufferSize(); - } - } catch (SocketException se) { + getImpl().connect(address, port); - // connection will be emulated by DatagramSocket - connectState = ST_CONNECTED_NO_IMPL; - } + // socket is now connected by the impl + connectState = ST_CONNECTED; + // Do we need to filter some packets? + int avail = getImpl().dataAvailable(); + if (avail == -1) { + throw new SocketException(); + } + explicitFilter = avail > 0; + if (explicitFilter) { + bytesLeftToFilter = getReceiveBufferSize(); } connectedAddress = address; connectedPort = port; } - /** - * Return true if the given DatagramSocketImpl is an "old" impl. An old impl - * is one that doesn't implement the abstract methods added in Java SE 1.4. - */ - @SuppressWarnings("removal") - private static boolean checkOldImpl(DatagramSocketImpl impl) { - // DatagramSocketImpl.peekData() is a protected method, therefore we need to use - // getDeclaredMethod, therefore we need permission to access the member - try { - AccessController.doPrivileged( - new PrivilegedExceptionAction<>() { - public Void run() throws NoSuchMethodException { - Class[] cl = new Class[1]; - cl[0] = DatagramPacket.class; - impl.getClass().getDeclaredMethod("peekData", cl); - return null; - } - }); - return false; - } catch (java.security.PrivilegedActionException e) { - return true; - } - } - /** * Return the {@code DatagramSocketImpl} attached to this socket, * creating the socket if not already created. @@ -382,19 +339,11 @@ final class NetMulticastSocket extends MulticastSocket { SecurityManager security = System.getSecurityManager(); if (security != null) { while (true) { - String peekAd = null; int peekPort = 0; // peek at the packet to see who it is from. - if (!oldImpl) { - // We can use the new peekData() API - DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); - peekPort = getImpl().peekData(peekPacket); - peekAd = peekPacket.getAddress().getHostAddress(); - } else { - InetAddress adr = new InetAddress(); - peekPort = getImpl().peek(adr); - peekAd = adr.getHostAddress(); - } + DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); + peekPort = getImpl().peekData(peekPacket); + String peekAd = peekPacket.getAddress().getHostAddress(); try { security.checkAccept(peekAd, peekPort); // security check succeeded - so now break @@ -418,7 +367,7 @@ final class NetMulticastSocket extends MulticastSocket { } } DatagramPacket tmp = null; - if ((connectState == ST_CONNECTED_NO_IMPL) || explicitFilter) { + if (explicitFilter) { // We have to do the filtering the old fashioned way since // the native impl doesn't support connect or the connect // via the impl failed, or .. "explicitFilter" may be set when @@ -426,21 +375,11 @@ final class NetMulticastSocket extends MulticastSocket { // when packets from other sources might be queued on socket. boolean stop = false; while (!stop) { - InetAddress peekAddress = null; - int peekPort = -1; // peek at the packet to see who it is from. - if (!oldImpl) { - // We can use the new peekData() API - DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); - peekPort = getImpl().peekData(peekPacket); - peekAddress = peekPacket.getAddress(); - } else { - // this api only works for IPv4 - peekAddress = new InetAddress(); - peekPort = getImpl().peek(peekAddress); - } - if ((!connectedAddress.equals(peekAddress)) || - (connectedPort != peekPort)) { + DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); + int peekPort = getImpl().peekData(peekPacket); + InetAddress peekAddress = peekPacket.getAddress(); + if ((!connectedAddress.equals(peekAddress)) || (connectedPort != peekPort)) { // throw the packet away and silently continue tmp = new DatagramPacket( new byte[1024], 1024); @@ -578,11 +517,7 @@ final class NetMulticastSocket extends MulticastSocket { public synchronized void setReuseAddress(boolean on) throws SocketException { if (isClosed()) throw new SocketException("Socket is closed"); - // Integer instead of Boolean for compatibility with older DatagramSocketImpl - if (oldImpl) - getImpl().setOption(SocketOptions.SO_REUSEADDR, on ? -1 : 0); - else - getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on)); + getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on)); } @Override @@ -809,9 +744,6 @@ final class NetMulticastSocket extends MulticastSocket { if (!(mcastaddr instanceof InetSocketAddress addr)) throw new IllegalArgumentException("Unsupported address type"); - if (oldImpl) - throw new UnsupportedOperationException(); - checkAddress(addr.getAddress(), "joinGroup"); @SuppressWarnings("removal") SecurityManager security = System.getSecurityManager(); @@ -835,9 +767,6 @@ final class NetMulticastSocket extends MulticastSocket { if (!(mcastaddr instanceof InetSocketAddress addr)) throw new IllegalArgumentException("Unsupported address type"); - if (oldImpl) - throw new UnsupportedOperationException(); - checkAddress(addr.getAddress(), "leaveGroup"); @SuppressWarnings("removal") SecurityManager security = System.getSecurityManager(); diff --git a/src/java.base/share/classes/java/net/ServerSocket.java b/src/java.base/share/classes/java/net/ServerSocket.java index 3d985f84df3cebf5e761d441a807714c56c49f3d..9441e6476e31967d88795e8667b966dd6749ee48 100644 --- a/src/java.base/share/classes/java/net/ServerSocket.java +++ b/src/java.base/share/classes/java/net/ServerSocket.java @@ -78,17 +78,17 @@ import sun.net.PlatformSocketImpl; */ public class ServerSocket implements java.io.Closeable { /** - * Various states of this socket. + * The underlying SocketImpl */ - private boolean created = false; - private boolean bound = false; - private boolean closed = false; - private Object closeLock = new Object(); + private final SocketImpl impl; /** - * The implementation of this Socket. + * Various states of this socket, need stateLock to change. */ - private SocketImpl impl; + private volatile boolean created; // impl.create(boolean) called + private volatile boolean bound; + private volatile boolean closed; + private final Object stateLock = new Object(); /** * Creates a server socket with a user-specified {@code SocketImpl}. @@ -124,7 +124,7 @@ public class ServerSocket implements java.io.Closeable { * @revised 1.4 */ public ServerSocket() throws IOException { - setImpl(); + this.impl = createImpl(); } /** @@ -264,18 +264,15 @@ public class ServerSocket implements java.io.Closeable { * @since 1.1 */ public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { - setImpl(); if (port < 0 || port > 0xFFFF) - throw new IllegalArgumentException( - "Port value out of range: " + port); + throw new IllegalArgumentException("Port value out of range: " + port); if (backlog < 1) - backlog = 50; + backlog = 50; + + this.impl = createImpl(); try { bind(new InetSocketAddress(bindAddr, port), backlog); - } catch(SecurityException e) { - close(); - throw e; - } catch(IOException e) { + } catch (IOException | SecurityException e) { close(); throw e; } @@ -289,35 +286,36 @@ public class ServerSocket implements java.io.Closeable { * @throws SocketException if creation fails. * @since 1.4 */ - SocketImpl getImpl() throws SocketException { - if (!created) - createImpl(); + private SocketImpl getImpl() throws SocketException { + if (!created) { + synchronized (stateLock) { + if (!created) { + if (closed) { + throw new SocketException("Socket is closed"); + } + try { + impl.create(true); + } catch (SocketException e) { + throw e; + } catch (IOException e) { + throw new SocketException(e.getMessage()); + } + created = true; + } + } + } return impl; } - private void setImpl() { + /** + * Create a SocketImpl for a server socket. + */ + private static SocketImpl createImpl() { SocketImplFactory factory = ServerSocket.factory; if (factory != null) { - impl = factory.createSocketImpl(); + return factory.createSocketImpl(); } else { - impl = SocketImpl.createPlatformSocketImpl(true); - } - } - - /** - * Creates the socket implementation. - * - * @throws SocketException if creation fails - * @since 1.4 - */ - void createImpl() throws SocketException { - if (impl == null) - setImpl(); - try { - impl.create(true); - created = true; - } catch (IOException e) { - throw new SocketException(e.getMessage()); + return SocketImpl.createPlatformSocketImpl(true); } } @@ -379,21 +377,21 @@ public class ServerSocket implements java.io.Closeable { if (epoint.isUnresolved()) throw new SocketException("Unresolved address"); if (backlog < 1) - backlog = 50; - try { - @SuppressWarnings("removal") - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkListen(epoint.getPort()); + backlog = 50; + + @SuppressWarnings("removal") + SecurityManager security = System.getSecurityManager(); + if (security != null) + security.checkListen(epoint.getPort()); + + synchronized (stateLock) { + if (closed) + throw new SocketException("Socket is closed"); + if (bound) + throw new SocketException("Already bound"); getImpl().bind(epoint.getAddress(), epoint.getPort()); getImpl().listen(backlog); bound = true; - } catch(SecurityException e) { - bound = false; - throw e; - } catch(IOException e) { - bound = false; - throw e; } } @@ -711,12 +709,15 @@ public class ServerSocket implements java.io.Closeable { * @revised 1.4 */ public void close() throws IOException { - synchronized(closeLock) { - if (isClosed()) - return; - if (created) - impl.close(); - closed = true; + synchronized (stateLock) { + if (!closed) { + closed = true; + + // close underlying socket if created + if (created) { + impl.close(); + } + } } } @@ -760,9 +761,7 @@ public class ServerSocket implements java.io.Closeable { * @since 1.4 */ public boolean isClosed() { - synchronized(closeLock) { - return closed; - } + return closed; } /** @@ -783,7 +782,7 @@ public class ServerSocket implements java.io.Closeable { * @since 1.1 * @see #getSoTimeout() */ - public synchronized void setSoTimeout(int timeout) throws SocketException { + public void setSoTimeout(int timeout) throws SocketException { if (isClosed()) throw new SocketException("Socket is closed"); if (timeout < 0) @@ -799,7 +798,7 @@ public class ServerSocket implements java.io.Closeable { * @since 1.1 * @see #setSoTimeout(int) */ - public synchronized int getSoTimeout() throws IOException { + public int getSoTimeout() throws IOException { if (isClosed()) throw new SocketException("Socket is closed"); Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT); @@ -984,7 +983,7 @@ public class ServerSocket implements java.io.Closeable { * @since 1.4 * @see #getReceiveBufferSize */ - public synchronized void setReceiveBufferSize (int size) throws SocketException { + public void setReceiveBufferSize (int size) throws SocketException { if (!(size > 0)) { throw new IllegalArgumentException("negative receive size"); } @@ -1007,8 +1006,7 @@ public class ServerSocket implements java.io.Closeable { * @see #setReceiveBufferSize(int) * @since 1.4 */ - public synchronized int getReceiveBufferSize() - throws SocketException{ + public int getReceiveBufferSize() throws SocketException { if (isClosed()) throw new SocketException("Socket is closed"); int result = 0; diff --git a/src/java.base/share/classes/java/net/SocketPermission.java b/src/java.base/share/classes/java/net/SocketPermission.java index b28969d144d4b04e2bb32979d81bbfa94dba8a59..aca7642931f4a9610ab249facbacc5e6831decf4 100644 --- a/src/java.base/share/classes/java/net/SocketPermission.java +++ b/src/java.base/share/classes/java/net/SocketPermission.java @@ -30,12 +30,10 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; -import java.net.InetAddress; import java.security.AccessController; import java.security.Permission; import java.security.PermissionCollection; import java.security.PrivilegedAction; -import java.security.Security; import java.util.Collections; import java.util.Enumeration; import java.util.Map; @@ -333,7 +331,7 @@ public final class SocketPermission extends Permission ind = host.lastIndexOf(':'); host = "[" + host.substring(0, ind) + "]" + host.substring(ind); - } else if (tokens == 8 && host.indexOf("::") == -1) { + } else if (tokens == 8 && !host.contains("::")) { // IPv6 address only, not followed by port host = "[" + host + "]"; } else { @@ -1297,7 +1295,7 @@ public final class SocketPermission extends Permission /* public String toString() { - StringBuffer s = new StringBuffer(super.toString() + "\n" + + StringBuilder s = new StringBuilder(super.toString() + "\n" + "cname = " + cname + "\n" + "wildcard = " + wildcard + "\n" + "invalid = " + invalid + "\n" + diff --git a/src/java.base/share/classes/java/net/URL.java b/src/java.base/share/classes/java/net/URL.java index 35d9503df19122e1e4bbb3a594af0002b59937d5..4ab1f5740a330c8dc37695e2dd2f8d1d7ee3871d 100644 --- a/src/java.base/share/classes/java/net/URL.java +++ b/src/java.base/share/classes/java/net/URL.java @@ -1762,7 +1762,7 @@ final class UrlDeserializedState { String reconstituteUrlString() { - // pre-compute length of StringBuffer + // pre-compute length of StringBuilder int len = protocol.length() + 1; if (authority != null && !authority.isEmpty()) len += 2 + authority.length(); diff --git a/src/java.base/share/classes/java/net/doc-files/net-properties.html b/src/java.base/share/classes/java/net/doc-files/net-properties.html index ea0311b71614627141a1e77f81e95097d7314f61..0c2d3e232dad4ef40d03d713ec36b1679dbc5cbd 100644 --- a/src/java.base/share/classes/java/net/doc-files/net-properties.html +++ b/src/java.base/share/classes/java/net/doc-files/net-properties.html @@ -1,6 +1,6 @@ - *

        URI.{@linkplain java.net.URI#create create}(relativeName).{@linkplain java.net.URI#normalize() normalize}().{@linkplain java.net.URI#getPath getPath}().equals(relativeName)
      + * {@snippet id="valid-relative-name" lang=java : + * // @link substring="create" target="URI#create" @link substring=normalize target="URI#normalize" @link substring=getPath target="URI#getPath" : + * URI.create(relativeName).normalize().getPath().equals(relativeName) + * } * *

      All methods in this interface might throw a SecurityException. * @@ -338,6 +343,51 @@ public interface JavaFileManager extends Closeable, Flushable, OptionChecker { FileObject sibling) throws IOException; + /** + * Returns a {@linkplain JavaFileObject file object} for output + * representing the specified class of the specified kind in the + * given package-oriented location. + * + *

      The provided {@code originatingFiles} represent files that + * were, in an unspecified way, used to create the content of + * the file created by this method. See {@code originatingElements} + * in {@link Filer#createSourceFile}. {@link Elements#getFileObjectOf} + * may be used to convert the {@code Element}s to {@code FileObject}s. + * + * @implSpec The default implementation calls + * {@link #getJavaFileForOutput(javax.tools.JavaFileManager.Location, java.lang.String, javax.tools.JavaFileObject.Kind, javax.tools.FileObject) } + * with the first element of the {@code originatingFiles}, if any, as a {@code sibling}. + * + * @param location a package-oriented location + * @param className the name of a class + * @param kind the kind of file, must be one of {@link + * JavaFileObject.Kind#SOURCE SOURCE} or {@link + * JavaFileObject.Kind#CLASS CLASS} + * @param originatingFiles the files which are contributing to this newly created file; + * {@code null} is equivalent to empty {@code originatingFiles}, + * meaning no known originating files + * @return a file object for output + * @throws IllegalArgumentException if sibling is not known to + * this file manager, or if the location is not known to this file + * manager and the file manager does not support unknown + * locations, or if the kind is not valid, or if the location is + * not an output location + * @throws IOException if an I/O error occurred, or if {@link + * #close} has been called and this file manager cannot be + * reopened + * @throws IllegalStateException {@link #close} has been called + * and this file manager cannot be reopened + * @since 18 + * @see Filer#createSourceFile + */ + default JavaFileObject getJavaFileForOutputForOriginatingFiles(Location location, + String className, + Kind kind, + FileObject... originatingFiles) + throws IOException { + return getJavaFileForOutput(location, className, kind, siblingFrom(originatingFiles)); + } + /** * Returns a {@linkplain FileObject file object} for input * representing the specified relative @@ -356,7 +406,9 @@ public interface JavaFileManager extends Closeable, Flushable, OptionChecker { * StandardLocation#SOURCE_PATH SOURCE_PATH} location, this method * might be called like so: * - *

      getFileForInput(SOURCE_PATH, "com.sun.tools.javac", "resources/compiler.properties");
      + * {@snippet id="call-getFileForInput" lang=java : + * getFileForInput(SOURCE_PATH, "com.sun.tools.javac", "resources/compiler.properties"); + * } * *

      If the call was executed on Windows, with SOURCE_PATH set to * "C:\Documents and Settings\UncleBob\src\share\classes", @@ -430,6 +482,59 @@ public interface JavaFileManager extends Closeable, Flushable, OptionChecker { FileObject sibling) throws IOException; + /** + * Returns a {@linkplain FileObject file object} for output + * representing the specified relative + * name in the specified package in the given location. + * + *

      The provided {@code originatingFiles} represent files that + * were, in an unspecified way, used to create the content of + * the file created by this method. See {@code originatingElements} + * in {@link Filer#createResource}. {@link Elements#getFileObjectOf} + * may be used to convert the {@code Element}s to {@code FileObject}s. + * + *

      If the returned object represents a {@linkplain + * JavaFileObject.Kind#SOURCE source} or {@linkplain + * JavaFileObject.Kind#CLASS class} file, it must be an instance + * of {@link JavaFileObject}. + * + *

      Informally, the file object returned by this method is + * located in the concatenation of the location, package name, and + * relative name or in a location inferred from the {@code originatingFiles}. + * See {@link #getFileForInput getFileForInput} for an example. + * + * @implSpec The default implementation calls + * {@link #getFileForOutput(javax.tools.JavaFileManager.Location, java.lang.String, java.lang.String, javax.tools.FileObject) } + * with the first element of the {@code originatingFiles}, if any, as a {@code sibling}. + * + * @param location an output location + * @param packageName a package name + * @param relativeName a relative name + * @param originatingFiles the files which are contributing to this newly created file; + * {@code null} is equivalent to empty {@code originatingFiles}, + * meaning no known originating files + * @return a file object + * @throws IllegalArgumentException if sibling is not known to + * this file manager, or if the location is not known to this file + * manager and the file manager does not support unknown + * locations, or if {@code relativeName} is not valid, + * or if the location is not an output location + * @throws IOException if an I/O error occurred, or if {@link + * #close} has been called and this file manager cannot be + * reopened + * @throws IllegalStateException if {@link #close} has been called + * and this file manager cannot be reopened + * @since 18 + * @see Filer#createResource + */ + default FileObject getFileForOutputForOriginatingFiles(Location location, + String packageName, + String relativeName, + FileObject... originatingFiles) + throws IOException { + return getFileForOutput(location, packageName, relativeName, siblingFrom(originatingFiles)); + } + /** * Flushes any resources opened for output by this file manager * directly or indirectly. Flushing a closed file manager has no @@ -566,16 +671,17 @@ public interface JavaFileManager extends Closeable, Flushable, OptionChecker { *

      For a package-oriented location, a file object is contained in the location if there exist * values for packageName and relativeName such that either of the following * calls would return the {@link #isSameFile same} file object: - *

      -     *     getFileForInput(location, packageName, relativeName)
      -     *     getFileForOutput(location, packageName, relativeName, null)
      -     * 
      + * {@snippet : + * // @highlight region substring=packageName type=italic @highlight region substring=relativeName type=italic : + * getFileForInput(location, packageName, relativeName) + * getFileForOutput(location, packageName, relativeName, null) // @end @end + * } * *

      For a module-oriented location, a file object is contained in the location if there exists * a module that may be obtained by the call: - *

      -     *     getLocationForModule(location, moduleName)
      -     * 
      + * {@snippet id="call-getLocationForModule" lang=java : + * getLocationForModule(location, moduleName) // @highlight substring=moduleName type=italic + * } * such that the file object is contained in the (package-oriented) location for that module. * * @implSpec This implementation throws {@code UnsupportedOperationException}. @@ -594,4 +700,8 @@ public interface JavaFileManager extends Closeable, Flushable, OptionChecker { throw new UnsupportedOperationException(); } + private static FileObject siblingFrom(FileObject[] originatingFiles) { + return originatingFiles != null && originatingFiles.length > 0 ? originatingFiles[0] : null; + } + } diff --git a/src/java.compiler/share/classes/javax/tools/StandardJavaFileManager.java b/src/java.compiler/share/classes/javax/tools/StandardJavaFileManager.java index 5b6590bf926a524536f781e67c2edc4f5de33e92..bd36f64be6f879d6eaa31fc8236f0f2bdf3203cd 100644 --- a/src/java.compiler/share/classes/javax/tools/StandardJavaFileManager.java +++ b/src/java.compiler/share/classes/javax/tools/StandardJavaFileManager.java @@ -75,9 +75,10 @@ import java.util.List; * {@linkplain FileObject#openReader(boolean)} * must succeed if the following would succeed (ignoring * encoding issues): - *
      - *
      new {@linkplain java.io.FileInputStream#FileInputStream(File) FileInputStream}(new {@linkplain File#File(java.net.URI) File}({@linkplain FileObject fileObject}.{@linkplain FileObject#toUri() toUri}()))
      - *
      + * {@snippet id="equiv-input" lang=java : + * // @link substring=FileInputStream target="java.io.FileInputStream#FileInputStream(File)" @link regex="File\b" target="File#File(java.net.URI)" @link substring=fileObject target=FileObject @link substring=toUri target="FileObject#toUri()" : + * new FileInputStream(new File(fileObject.toUri())) + * } * *
    • * and the methods @@ -85,9 +86,10 @@ import java.util.List; * {@linkplain FileObject#openWriter()} must * succeed if the following would succeed (ignoring encoding * issues): - *
      - *
      new {@linkplain java.io.FileOutputStream#FileOutputStream(File) FileOutputStream}(new {@linkplain File#File(java.net.URI) File}({@linkplain FileObject fileObject}.{@linkplain FileObject#toUri() toUri}()))
      - *
      + * {@snippet id="equiv-output" lang=java : + * // @link substring=FileOutputStream target="java.io.FileOutputStream#FileOutputStream(File)" @link regex="File\b" target="File#File(java.net.URI)" @link substring=fileObject target=FileObject @link substring=toUri target="FileObject#toUri()" : + * new FileOutputStream(new File(fileObject.toUri())) + * } *
    • * * @@ -241,9 +243,9 @@ public interface StandardJavaFileManager extends JavaFileManager { * Returns file objects representing the given files. * Convenience method equivalent to: * - *
      -     *     getJavaFileObjectsFromFiles({@linkplain java.util.Arrays#asList Arrays.asList}(files))
      -     * 
      + * {@snippet id="equiv-getJavaFileObjects" lang=java : + * getJavaFileObjectsFromFiles(Arrays.asList(files)) // @link substring="Arrays.asList" target="Arrays#asList" + * } * * @param files an array of files * @return a list of file objects @@ -259,9 +261,9 @@ public interface StandardJavaFileManager extends JavaFileManager { * Returns file objects representing the given paths. * Convenience method equivalent to: * - *
      -     *     getJavaFileObjectsFromPaths({@linkplain java.util.Arrays#asList Arrays.asList}(paths))
      -     * 
      + * {@snippet id="equiv-getJavaFileObjectsFromPaths" lang=java : + * getJavaFileObjectsFromPaths(Arrays.asList(paths)) // @link substring="Arrays.asList" target="Arrays#asList" + * } * * @implSpec * The default implementation will only throw {@code NullPointerException} @@ -296,9 +298,9 @@ public interface StandardJavaFileManager extends JavaFileManager { * Returns file objects representing the given file names. * Convenience method equivalent to: * - *
      -     *     getJavaFileObjectsFromStrings({@linkplain java.util.Arrays#asList Arrays.asList}(names))
      -     * 
      + * {@snippet id="equiv-getJavaFileObjectsFromStrings" lang=java : + * getJavaFileObjectsFromStrings(Arrays.asList(names)) // @link substring="Arrays.asList" target="Arrays#asList" + * } * * @param names a list of file names * @return a list of file objects diff --git a/src/java.compiler/share/classes/javax/tools/package-info.java b/src/java.compiler/share/classes/javax/tools/package-info.java index c5ec54e7871e0495204da9cc29df9996a20b2512..963e6f2261c43a32a4f83689f215ecb49eff714b 100644 --- a/src/java.compiler/share/classes/javax/tools/package-info.java +++ b/src/java.compiler/share/classes/javax/tools/package-info.java @@ -52,7 +52,9 @@ * a default compiler is provided, it can be located using the * {@link javax.tools.ToolProvider}, for example: * - *

      {@code JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();} + * {@snippet id="show-getSystemJavaCompiler" lang=java : + * JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + * } * *

      It is possible to provide alternative compilers or tools * through the {@linkplain java.util.ServiceLoader service provider @@ -64,12 +66,16 @@ * META-INF/services/javax.tools.JavaCompiler}. This file would * contain the single line: * - *

      {@code com.vendor.VendorJavaCompiler} + * {@snippet id="show-service" : + * com.vendor.VendorJavaCompiler + * } * - *

      If the jar file is on the class path, VendorJavaCompiler can be + *

      If the jar file is on the class path, {@code VendorJavaCompiler} can be * located using code like this: * - *

      {@code JavaCompiler compiler = ServiceLoader.load(JavaCompiler.class).iterator().next();} + * {@snippet id="show-serviceLoader" lang=java : + * JavaCompiler compiler = ServiceLoader.load(JavaCompiler.class).iterator().next(); + * } * * @author Peter von der Ahé * @author Jonathan Gibbons diff --git a/src/java.compiler/share/classes/javax/tools/snippet-files/JavaSourceFromString.java b/src/java.compiler/share/classes/javax/tools/snippet-files/JavaSourceFromString.java new file mode 100644 index 0000000000000000000000000000000000000000..f0555a02e9e3baf276857052c22659a1923d5bf1 --- /dev/null +++ b/src/java.compiler/share/classes/javax/tools/snippet-files/JavaSourceFromString.java @@ -0,0 +1,54 @@ +// @replace region replacement="" +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.tools.SimpleJavaFileObject; +import java.net.URI; +// @end +/** + * A file object used to represent source coming from a string. + */ +public class JavaSourceFromString extends SimpleJavaFileObject { + /** + * The source code of this "file". + */ + final String code; + + /** + * Constructs a new JavaSourceFromString. + * @param name the name of the compilation unit represented by this file object + * @param code the source code for the compilation unit represented by this file object + */ + JavaSourceFromString(String name, String code) { + super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), // @link substring="URI.create" target="URI#create(String)" + Kind.SOURCE); + this.code = code; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return code; + } +} diff --git a/src/java.compiler/share/classes/module-info.java b/src/java.compiler/share/classes/module-info.java index 3d937e09f0cc88d558360becf9b7158f0199de09..0793855d1dc6efb9846d77c5219be91b8a25ce84 100644 --- a/src/java.compiler/share/classes/module-info.java +++ b/src/java.compiler/share/classes/module-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,9 @@ */ /** - * Defines the Language Model, Annotation Processing, and Java Compiler APIs. + * Defines the {@index "Language Model"}, {@index "Annotation Processing"}, and + * {@index "Java Compiler"} APIs. + * *

      * These APIs model declarations and types of the Java programming language, * and define interfaces for tools such as compilers which can be invoked diff --git a/src/java.desktop/macosx/classes/apple/laf/JRSUIControl.java b/src/java.desktop/macosx/classes/apple/laf/JRSUIControl.java index e3579449b7570396b7c0767272d2720ebfd27fe2..6e6c86ccf7ac33d8e1116a1c8bd4978cb7635e9a 100644 --- a/src/java.desktop/macosx/classes/apple/laf/JRSUIControl.java +++ b/src/java.desktop/macosx/classes/apple/laf/JRSUIControl.java @@ -114,7 +114,7 @@ public final class JRSUIControl { changes.putAll(other.changes); } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected synchronized void finalize() throws Throwable { if (cfDictionaryPtr == 0) return; disposeCFDictionary(cfDictionaryPtr); diff --git a/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java b/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java index e64e9b158b568d9f30726e80102607f51277d4b9..248ae55f6d74d4f59c89499a4924baea7c9d4185 100644 --- a/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java +++ b/src/java.desktop/macosx/classes/com/apple/eawt/_AppEventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -281,7 +281,7 @@ class _AppEventHandler { } } - class _PreferencesDispatcher extends _AppEventDispatcher { + static class _PreferencesDispatcher extends _AppEventDispatcher { synchronized void setHandler(final PreferencesHandler handler) { super.setHandler(handler); @@ -294,20 +294,20 @@ class _AppEventHandler { } } - class _OpenAppDispatcher extends _QueuingAppEventDispatcher { + static class _OpenAppDispatcher extends _QueuingAppEventDispatcher { void performUsing(com.apple.eawt._OpenAppHandler handler, _NativeEvent event) { handler.handleOpenApp(); } } - class _AppReOpenedDispatcher extends _AppEventMultiplexor { + static class _AppReOpenedDispatcher extends _AppEventMultiplexor { void performOnListener(AppReopenedListener listener, final _NativeEvent event) { final AppReopenedEvent e = new AppReopenedEvent(); listener.appReopened(e); } } - class _AppForegroundDispatcher extends _BooleanAppEventMultiplexor { + static class _AppForegroundDispatcher extends _BooleanAppEventMultiplexor { AppForegroundEvent createEvent(final boolean isTrue) { return new AppForegroundEvent(); } void performFalseEventOn(final AppForegroundListener listener, final AppForegroundEvent e) { @@ -319,7 +319,7 @@ class _AppEventHandler { } } - class _HiddenAppDispatcher extends _BooleanAppEventMultiplexor { + static class _HiddenAppDispatcher extends _BooleanAppEventMultiplexor { AppHiddenEvent createEvent(final boolean isTrue) { return new AppHiddenEvent(); } void performFalseEventOn(final AppHiddenListener listener, final AppHiddenEvent e) { @@ -331,7 +331,7 @@ class _AppEventHandler { } } - class _UserSessionDispatcher extends _BooleanAppEventMultiplexor { + static class _UserSessionDispatcher extends _BooleanAppEventMultiplexor { UserSessionEvent createEvent(final boolean isTrue) { return new UserSessionEvent(Reason.UNSPECIFIED); } @@ -349,7 +349,7 @@ class _AppEventHandler { } } - class _ScreenSleepDispatcher extends _BooleanAppEventMultiplexor { + static class _ScreenSleepDispatcher extends _BooleanAppEventMultiplexor { ScreenSleepEvent createEvent(final boolean isTrue) { return new ScreenSleepEvent(); } void performFalseEventOn(final ScreenSleepListener listener, final ScreenSleepEvent e) { @@ -365,7 +365,7 @@ class _AppEventHandler { } } - class _SystemSleepDispatcher extends _BooleanAppEventMultiplexor { + static class _SystemSleepDispatcher extends _BooleanAppEventMultiplexor { SystemSleepEvent createEvent(final boolean isTrue) { return new SystemSleepEvent(); } void performFalseEventOn(final SystemSleepListener listener, final SystemSleepEvent e) { @@ -381,7 +381,7 @@ class _AppEventHandler { } } - class _OpenFileDispatcher extends _QueuingAppEventDispatcher { + static class _OpenFileDispatcher extends _QueuingAppEventDispatcher { void performUsing(final OpenFilesHandler handler, final _NativeEvent event) { // create file list from fileNames final List fileNameList = event.get(0); @@ -394,7 +394,7 @@ class _AppEventHandler { } } - class _PrintFileDispatcher extends _QueuingAppEventDispatcher { + static class _PrintFileDispatcher extends _QueuingAppEventDispatcher { void performUsing(final PrintFilesHandler handler, final _NativeEvent event) { // create file list from fileNames final List fileNameList = event.get(0); @@ -406,7 +406,7 @@ class _AppEventHandler { } // Java URLs can't handle unknown protocol types, which is why we use URIs - class _OpenURIDispatcher extends _QueuingAppEventDispatcher { + static class _OpenURIDispatcher extends _QueuingAppEventDispatcher { void performUsing(final OpenURIHandler handler, final _NativeEvent event) { final String urlString = event.get(0); try { @@ -450,7 +450,7 @@ class _AppEventHandler { } } - abstract class _AppEventMultiplexor { + abstract static class _AppEventMultiplexor { private final Map listenerToAppContext = new IdentityHashMap(); boolean nativeListenerRegistered; @@ -503,7 +503,7 @@ class _AppEventHandler { } } - abstract class _BooleanAppEventMultiplexor extends _AppEventMultiplexor { + abstract static class _BooleanAppEventMultiplexor extends _AppEventMultiplexor { @Override void performOnListener(L listener, final _NativeEvent event) { final boolean isTrue = Boolean.TRUE.equals(event.get(0)); @@ -530,7 +530,7 @@ class _AppEventHandler { * * User code is not (and should not be) run under any synchronized lock. */ - abstract class _AppEventDispatcher { + abstract static class _AppEventDispatcher { H _handler; AppContext handlerContext; @@ -575,7 +575,7 @@ class _AppEventHandler { } } - abstract class _QueuingAppEventDispatcher extends _AppEventDispatcher { + abstract static class _QueuingAppEventDispatcher extends _AppEventDispatcher { List<_NativeEvent> queuedEvents = new LinkedList<_NativeEvent>(); @Override diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaBorder.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaBorder.java index f9e099fd4d48c3765f2013866ffab90954a6ea9c..cf75ab164bac54104e30e32113f9f401b7d51ae1 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaBorder.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaBorder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -128,7 +128,7 @@ public abstract class AquaBorder implements Border, UIResource { if (!((javax.swing.text.JTextComponent)focusable).isEditable()) return false; } - return (focusable != null && focusable instanceof JComponent && ((JComponent)focusable).hasFocus()); + return (focusable instanceof JComponent jComponent) && jComponent.hasFocus(); } @Override diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaButtonBorder.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaButtonBorder.java index f58c518d2d4179911e913f5f414c21268e8adc33..1d11a0a8d96f4e35ebe60d1b8bf66916a52f4508 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaButtonBorder.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaButtonBorder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -145,9 +145,9 @@ public abstract class AquaButtonBorder extends AquaBorder implements Border, UIR * @param c the component for which this border insets value applies */ public Insets getBorderInsets(final Component c) { - if (c == null || !(c instanceof AbstractButton)) return new Insets(0, 0, 0, 0); + if (!(c instanceof AbstractButton button)) return new Insets(0, 0, 0, 0); - Insets margin = ((AbstractButton)c).getMargin(); + Insets margin = button.getMargin(); margin = (margin == null) ? new InsetsUIResource(0, 0, 0, 0) : (Insets)margin.clone(); margin.top += sizeVariant.margins.top; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java index 06f84d0eae12e5a27bb3cbde969891ce8ef39f87..c25d89559fc0c25e17a01ef01916761842e79502 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -598,8 +598,7 @@ public class AquaComboBoxUI extends BasicComboBoxUI implements Sizeable { final boolean editable = comboBox.isEditable(); final Dimension size; - if (!editable && arrowButton != null && arrowButton instanceof AquaComboBoxButton) { - final AquaComboBoxButton button = (AquaComboBoxButton)arrowButton; + if (!editable && arrowButton instanceof final AquaComboBoxButton button) { final Insets buttonInsets = button.getInsets(); // Insets insets = comboBox.getInsets(); final Insets insets = new Insets(0, 5, 0, 25);//comboBox.getInsets(); diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java index 71a4f01211607e2a3b1b193265ace9ffbeee4833..d8bfca02fe75d9dd1063e98dbdf95734f85513c8 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileChooserUI.java @@ -519,14 +519,14 @@ public class AquaFileChooserUI extends FileChooserUI { void setPackageIsTraversable(final Object o) { int newProp = -1; - if (o != null && o instanceof String) newProp = parseTraversableProperty((String)o); + if (o instanceof String s) newProp = parseTraversableProperty(s); if (newProp != -1) fPackageIsTraversable = newProp; else fPackageIsTraversable = sGlobalPackageIsTraversable; } void setApplicationIsTraversable(final Object o) { int newProp = -1; - if (o != null && o instanceof String) newProp = parseTraversableProperty((String)o); + if (o instanceof String s) newProp = parseTraversableProperty(s); if (newProp != -1) fApplicationIsTraversable = newProp; else fApplicationIsTraversable = sGlobalApplicationIsTraversable; } @@ -1985,11 +1985,11 @@ public class AquaFileChooserUI extends FileChooserUI { static { Object o = UIManager.get(PACKAGE_TRAVERSABLE_PROPERTY); - if (o != null && o instanceof String) sGlobalPackageIsTraversable = parseTraversableProperty((String)o); + if (o instanceof String s) sGlobalPackageIsTraversable = parseTraversableProperty(s); else sGlobalPackageIsTraversable = kOpenConditional; o = UIManager.get(APPLICATION_TRAVERSABLE_PROPERTY); - if (o != null && o instanceof String) sGlobalApplicationIsTraversable = parseTraversableProperty((String)o); + if (o instanceof String s) sGlobalApplicationIsTraversable = parseTraversableProperty(s); else sGlobalApplicationIsTraversable = kOpenConditional; } static final String sDataPrefix = "FileChooser."; @@ -2445,7 +2445,7 @@ public class AquaFileChooserUI extends FileChooserUI { // Convenience, to translate from the JList directory view to the Mac-style JTable // & minimize diffs between this and BasicFileChooserUI @SuppressWarnings("serial") // Superclass is not serializable across versions - class JTableExtension extends JTable { + static class JTableExtension extends JTable { public void setSelectedIndex(final int index) { getSelectionModel().setSelectionInterval(index, index); } diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java index 14aa78ec8498f2bd1e9dfeb02da50fb49d533e91..80ffc080f999e20663670e727d66dc757c775220 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java @@ -278,7 +278,7 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi // @param a an integer array // @param lo0 left boundary of array partition // @param hi0 right boundary of array partition - abstract class QuickSort { + abstract static class QuickSort { final void quickSort(final Vector v, final int lo0, final int hi0) { int lo = lo0; int hi = hi0; @@ -338,7 +338,7 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi protected abstract boolean lt(SortableFile a, SortableFile b); } - class QuickSortNames extends QuickSort { + static class QuickSortNames extends QuickSort { protected boolean lt(final SortableFile a, final SortableFile b) { final String aLower = a.fName.toLowerCase(); final String bLower = b.fName.toLowerCase(); @@ -346,14 +346,14 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi } } - class QuickSortDates extends QuickSort { + static class QuickSortDates extends QuickSort { protected boolean lt(final SortableFile a, final SortableFile b) { return a.fDateValue < b.fDateValue; } } // for speed in sorting, displaying - class SortableFile /* extends FileView */{ + static class SortableFile /* extends FileView */{ File fFile; String fName; long fDateValue; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFramePaneUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFramePaneUI.java index e12033fceb5feb1fa8fd7df8e4f078da21882fbb..a0c26ac7841236a9216e6830d5f41c06859a168c 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFramePaneUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFramePaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -187,7 +187,7 @@ public class AquaInternalFramePaneUI extends BasicDesktopPaneUI implements Mouse } @SuppressWarnings("serial") // JDK implementation class - class AquaDockingDesktopManager extends AquaInternalFrameManager { + static class AquaDockingDesktopManager extends AquaInternalFrameManager { public void openFrame(final JInternalFrame f) { final JInternalFrame.JDesktopIcon desktopIcon = f.getDesktopIcon(); final Container dock = desktopIcon.getParent(); diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaLookAndFeel.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaLookAndFeel.java index 610b408c99b372cd8330543b75b088d8f8fc4c1a..dad0b2279ebeff20c6e653803205e7e5e2564575 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaLookAndFeel.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaLookAndFeel.java @@ -188,8 +188,8 @@ public class AquaLookAndFeel extends BasicLookAndFeel { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(AquaMnemonicHandler.getInstance()); final PopupFactory popupFactory = PopupFactory.getSharedInstance(); - if (popupFactory != null && popupFactory instanceof ScreenPopupFactory) { - ((ScreenPopupFactory)popupFactory).setActive(false); + if (popupFactory instanceof ScreenPopupFactory spf) { + spf.setActive(false); } super.uninitialize(); diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaRootPaneUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaRootPaneUI.java index a4e179645a958bd3d6e916845233b45d86e89e00..2b4e1bb0867f8e6a46483bffd26d75367940b884 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaRootPaneUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaRootPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,8 +75,7 @@ public class AquaRootPaneUI extends BasicRootPaneUI implements AncestorListener, // it is not since we are going to grab the one that was set on the JFrame. :( final Component parent = c.getParent(); - if (parent != null && parent instanceof JFrame) { - final JFrame frameParent = (JFrame)parent; + if (parent instanceof JFrame frameParent) { final Color bg = frameParent.getBackground(); if (bg == null || bg instanceof UIResource) { frameParent.setBackground(UIManager.getColor("Panel.background")); @@ -126,8 +125,8 @@ public class AquaRootPaneUI extends BasicRootPaneUI implements AncestorListener, final Window owningWindow = SwingUtilities.getWindowAncestor(jmb); // Could be a JDialog, and may have been added to a JRootPane not yet in a window. - if (owningWindow != null && owningWindow instanceof JFrame) { - ((AquaMenuBarUI)mbui).setScreenMenuBar((JFrame)owningWindow); + if (owningWindow instanceof JFrame frame) { + ((AquaMenuBarUI)mbui).setScreenMenuBar(frame); } } } @@ -154,8 +153,8 @@ public class AquaRootPaneUI extends BasicRootPaneUI implements AncestorListener, final Window owningWindow = SwingUtilities.getWindowAncestor(jmb); // Could be a JDialog, and may have been added to a JRootPane not yet in a window. - if (owningWindow != null && owningWindow instanceof JFrame) { - ((AquaMenuBarUI)mbui).clearScreenMenuBar((JFrame)owningWindow); + if (owningWindow instanceof JFrame frame) { + ((AquaMenuBarUI)mbui).clearScreenMenuBar(frame); } } } diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaSliderUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaSliderUI.java index 3775fc859e44348111e479578bc190d68dd412ab..50da054c1f8dcb5b27830953a5e81b261de0bbe6 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaSliderUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaSliderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -266,8 +266,8 @@ public class AquaSliderUI extends BasicSliderUI implements Sizeable { if (slider.getPaintTicks() || slider.getPaintLabels()) return true; final Object shouldPaintArrowThumbProperty = slider.getClientProperty("Slider.paintThumbArrowShape"); - if (shouldPaintArrowThumbProperty != null && shouldPaintArrowThumbProperty instanceof Boolean) { - return ((Boolean)shouldPaintArrowThumbProperty).booleanValue(); + if (shouldPaintArrowThumbProperty instanceof Boolean b) { + return b; } return false; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java index 5722b28e576c6a40856267219443c69816b42025..6c92b5bbf8ad729b2026d160d737cc55a85cf106 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java @@ -3261,7 +3261,7 @@ public class AquaTabbedPaneCopyFromBasicUI extends TabbedPaneUI implements Swing } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class ScrollableTabButton extends javax.swing.plaf.basic.BasicArrowButton implements UIResource, SwingConstants { + private static class ScrollableTabButton extends javax.swing.plaf.basic.BasicArrowButton implements UIResource, SwingConstants { public ScrollableTabButton(final int direction) { super(direction, UIManager.getColor("TabbedPane.selected"), UIManager.getColor("TabbedPane.shadow"), UIManager.getColor("TabbedPane.darkShadow"), UIManager.getColor("TabbedPane.highlight")); } diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaTableHeaderUI.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaTableHeaderUI.java index 85577ce46ca458377b1f0a31e4959fa1cdc84ccb..af5621657de1cd8fda58890ab3478376d51c713e 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaTableHeaderUI.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaTableHeaderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,9 +103,8 @@ public class AquaTableHeaderUI extends BasicTableHeaderUI { } final TableHeaderUI headerUI = target.getUI(); - if (headerUI == null || !(headerUI instanceof AquaTableHeaderUI)) return; + if (!(headerUI instanceof AquaTableHeaderUI aquaHeaderUI)) return; - final AquaTableHeaderUI aquaHeaderUI = (AquaTableHeaderUI)headerUI; aquaHeaderUI.sortColumn = tableColumn.getModelIndex(); aquaHeaderUI.sortOrder = sortDirection; final AquaTableCellRenderer renderer = aquaHeaderUI.new AquaTableCellRenderer(); @@ -145,8 +144,7 @@ public class AquaTableHeaderUI extends BasicTableHeaderUI { } protected static TableColumn getTableColumn(final JTableHeader target, final Object value) { - if (value == null || !(value instanceof Integer)) return null; - final int columnIndex = ((Integer)value).intValue(); + if (!(value instanceof Integer columnIndex)) return null; final TableColumnModel columnModel = target.getColumnModel(); if (columnIndex < 0 || columnIndex >= columnModel.getColumnCount()) return null; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/ScreenMenu.java b/src/java.desktop/macosx/classes/com/apple/laf/ScreenMenu.java index 4f6e006faf82825227cc311faa92f04a54074728..747e8ac137ecfc35cf6c939eecc0f4da4d374a5c 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/ScreenMenu.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/ScreenMenu.java @@ -351,11 +351,8 @@ final class ScreenMenu extends Menu // Tell our parent to add/remove us final MenuContainer parent = getParent(); - if (parent != null) { - if (parent instanceof ScreenMenu) { - final ScreenMenu sm = (ScreenMenu)parent; - sm.setChildVisible(fInvoker, b); - } + if (parent instanceof ScreenMenu sm) { + sm.setChildVisible(fInvoker, b); } } diff --git a/src/java.desktop/macosx/classes/sun/awt/CGraphicsEnvironment.java b/src/java.desktop/macosx/classes/sun/awt/CGraphicsEnvironment.java index e96ce7e18d79ac35bf2552e1ac6ef92b4278f7b0..fe4431e3091284a994bbc42e40f50330a41638dc 100644 --- a/src/java.desktop/macosx/classes/sun/awt/CGraphicsEnvironment.java +++ b/src/java.desktop/macosx/classes/sun/awt/CGraphicsEnvironment.java @@ -144,7 +144,7 @@ public final class CGraphicsEnvironment extends SunGraphicsEnvironment { } @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { try { super.finalize(); diff --git a/src/java.desktop/macosx/classes/sun/font/CFont.java b/src/java.desktop/macosx/classes/sun/font/CFont.java index 885fc7fc471d2bb3241b9d06b138ea76fe31cb10..073364719f04d06ef5ea155ce6d38609dc5ad838 100644 --- a/src/java.desktop/macosx/classes/sun/font/CFont.java +++ b/src/java.desktop/macosx/classes/sun/font/CFont.java @@ -206,7 +206,7 @@ public final class CFont extends PhysicalFont implements FontSubstitution { // In some italic cases the standard Mac cascade list is missing Arabic. listOfString.add("GeezaPro"); - FontManager fm = FontManagerFactory.getInstance(); + CFontManager fm = (CFontManager) FontManagerFactory.getInstance(); int numFonts = 1 + listOfString.size(); PhysicalFont[] fonts = new PhysicalFont[numFonts]; fonts[0] = this; @@ -222,7 +222,7 @@ public final class CFont extends PhysicalFont implements FontSubstitution { // Don't know why we get the weird name above .. replace. s = "AppleSymbols"; } - Font2D f2d = fm.findFont2D(s, Font.PLAIN, FontManager.NO_FALLBACK); + Font2D f2d = fm.getOrCreateFallbackFont(s); if (f2d == null || f2d == this) { continue; } @@ -247,7 +247,7 @@ public final class CFont extends PhysicalFont implements FontSubstitution { return compFont; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected synchronized void finalize() { if (nativeFontPtr != 0) { disposeNativeFont(nativeFontPtr); diff --git a/src/java.desktop/macosx/classes/sun/font/CFontManager.java b/src/java.desktop/macosx/classes/sun/font/CFontManager.java index 85182158ec152c3c130c7a8b6b087fd46d0b7b3a..5af2be3f60c97d158d7f8568f0b1478e92cec16d 100644 --- a/src/java.desktop/macosx/classes/sun/font/CFontManager.java +++ b/src/java.desktop/macosx/classes/sun/font/CFontManager.java @@ -33,8 +33,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Locale; +import java.util.Map; import java.util.TreeMap; import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; import javax.swing.plaf.FontUIResource; @@ -45,6 +47,7 @@ import sun.lwawt.macosx.*; public final class CFontManager extends SunFontManager { private static Hashtable genericFonts = new Hashtable(); + private final Map fallbackFonts = new ConcurrentHashMap<>(); @Override protected FontConfiguration createFontConfiguration() { @@ -283,9 +286,9 @@ public final class CFontManager extends SunFontManager { if (realFamily == null) return false; Font2D realFont = realFamily.getFontWithExactStyleMatch(style); - if (realFont == null || !(realFont instanceof CFont)) return false; + if (!(realFont instanceof CFont cFont)) return false; - CFont newFont = new CFont((CFont)realFont, logicalFamilyName); + CFont newFont = new CFont(cFont, logicalFamilyName); registerGenericFont(newFont, true); return true; @@ -321,4 +324,17 @@ public final class CFontManager extends SunFontManager { @Override protected void populateFontFileNameMap(HashMap fontToFileMap, HashMap fontToFamilyNameMap, HashMap> familyToFontListMap, Locale locale) {} + + Font2D getOrCreateFallbackFont(String fontName) { + Font2D font2D = findFont2D(fontName, Font.PLAIN, FontManager.NO_FALLBACK); + if (font2D != null || fontName.startsWith(".")) { + return font2D; + } else { + // macOS doesn't list some system fonts in [NSFontManager availableFontFamilies] output, + // so they are not registered in font manager as part of 'loadNativeFonts'. + // These fonts are present in [NSFontManager availableFonts] output though, + // and can be accessed in the same way as other system fonts. + return fallbackFonts.computeIfAbsent(fontName, name -> new CFont(name, null)); + } + } } diff --git a/src/java.desktop/macosx/classes/sun/font/CStrike.java b/src/java.desktop/macosx/classes/sun/font/CStrike.java index 088fb01591e2b83031bc59e6463c2e7e78c26a3d..eb049c3d449d4b1ffb975090ff7e2c9062244bc6 100644 --- a/src/java.desktop/macosx/classes/sun/font/CStrike.java +++ b/src/java.desktop/macosx/classes/sun/font/CStrike.java @@ -125,7 +125,7 @@ public final class CStrike extends PhysicalStrike { return nativeStrikePtr; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected synchronized void finalize() throws Throwable { if (nativeStrikePtr != 0) { disposeNativeStrikePtr(nativeStrikePtr); diff --git a/src/java.desktop/macosx/classes/sun/java2d/metal/MTLRenderer.java b/src/java.desktop/macosx/classes/sun/java2d/metal/MTLRenderer.java index 5ca368d446eeba742c83a4c501d1070ac7862a27..5f4b8183d42aab5e928672b20d1230d0da8445aa 100644 --- a/src/java.desktop/macosx/classes/sun/java2d/metal/MTLRenderer.java +++ b/src/java.desktop/macosx/classes/sun/java2d/metal/MTLRenderer.java @@ -110,7 +110,7 @@ class MTLRenderer extends BufferedRenderPipe { return new Tracer(this); } - private class Tracer extends MTLRenderer { + private static class Tracer extends MTLRenderer { private MTLRenderer mtlr; Tracer(MTLRenderer mtlr) { super(mtlr.rq); diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibility.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibility.java index c4311bf0f5233d113dfc771769a9621e5ba7a9ae..f338f25f05ed8d4d6a75582b7e4aa60b93ed06cf 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibility.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibility.java @@ -41,6 +41,7 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.Arrays; +import java.util.function.Function; import javax.accessibility.Accessible; import javax.accessibility.AccessibleAction; @@ -626,8 +627,8 @@ class CAccessibility implements PropertyChangeListener { return invokeAndWait(new Callable() { public Accessible call() throws Exception { Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - if (c == null || !(c instanceof Accessible)) return null; - return CAccessible.getCAccessible((Accessible)c); + if (!(c instanceof Accessible accessible)) return null; + return CAccessible.getCAccessible(accessible); } }, c); } @@ -662,21 +663,29 @@ class CAccessibility implements PropertyChangeListener { @Native static final int JAVA_AX_SELECTED_CHILDREN = -2; @Native static final int JAVA_AX_VISIBLE_CHILDREN = -3; + private static Object[] getTableRowChildrenAndRoles(Accessible a, Component c, int whichChildren, boolean allowIgnored, int tableRowIndex) { + return invokeGetChildrenAndRoles(a, c, whichChildren, allowIgnored, ChildrenOperations.createForTableRow(tableRowIndex)); + } + // Each child takes up two entries in the array: one for itself and one for its role - public static Object[] getChildrenAndRoles(final Accessible a, final Component c, final int whichChildren, final boolean allowIgnored) { + private static Object[] getChildrenAndRoles(final Accessible a, final Component c, final int whichChildren, final boolean allowIgnored) { + return invokeGetChildrenAndRoles(a, c, whichChildren, allowIgnored, ChildrenOperations.COMMON); + } + + private static Object[] invokeGetChildrenAndRoles(Accessible a, Component c, int whichChildren, boolean allowIgnored, ChildrenOperations ops) { if (a == null) return null; return invokeAndWait(new Callable() { public Object[] call() throws Exception { - return getChildrenAndRolesImpl(a, c, whichChildren, allowIgnored); + return getChildrenAndRolesImpl(a, c, whichChildren, allowIgnored, ops); } }, c); } - private static Object[] getChildrenAndRolesImpl(final Accessible a, final Component c, final int whichChildren, final boolean allowIgnored) { + private static Object[] getChildrenAndRolesImpl(Accessible a, Component c, int whichChildren, boolean allowIgnored, ChildrenOperations ops) { if (a == null) return null; ArrayList childrenAndRoles = new ArrayList(); - _addChildren(a, whichChildren, allowIgnored, childrenAndRoles); + _addChildren(a, whichChildren, allowIgnored, childrenAndRoles, ops); /* In case of fetching a selection, we need to check if * the active descendant is at the beginning of the list, or @@ -747,7 +756,7 @@ class CAccessibility implements PropertyChangeListener { while (!parentStack.isEmpty()) { Accessible p = parentStack.get(parentStack.size() - 1); - currentLevelChildren.addAll(Arrays.asList(getChildrenAndRolesImpl(p, c, JAVA_AX_ALL_CHILDREN, allowIgnored))); + currentLevelChildren.addAll(Arrays.asList(getChildrenAndRolesImpl(p, c, JAVA_AX_ALL_CHILDREN, allowIgnored, ChildrenOperations.COMMON))); if ((currentLevelChildren.size() == 0) || (index >= currentLevelChildren.size())) { if (!parentStack.isEmpty()) parentStack.remove(parentStack.size() - 1); if (!indexses.isEmpty()) index = indexses.remove(indexses.size() - 1); @@ -859,20 +868,70 @@ class CAccessibility implements PropertyChangeListener { return role; } + private interface ChildrenOperations { + boolean isContextValid(AccessibleContext accessibleContext); + int getChildrenCount(AccessibleContext accessibleContext); + Accessible getAccessibleChild(AccessibleContext accessibleContext, int childIndex); + + static ChildrenOperations COMMON = createForCommon(); + + static ChildrenOperations createForCommon() { + return new ChildrenOperations() { + @Override + public boolean isContextValid(AccessibleContext accessibleContext) { + return accessibleContext != null; + } + + @Override + public int getChildrenCount(AccessibleContext accessibleContext) { + assert isContextValid(accessibleContext); + return accessibleContext.getAccessibleChildrenCount(); + } + + @Override + public Accessible getAccessibleChild(AccessibleContext accessibleContext, int childIndex) { + assert isContextValid(accessibleContext); + return accessibleContext.getAccessibleChild(childIndex); + } + }; + } + + static ChildrenOperations createForTableRow(int tableRowIndex) { + return new ChildrenOperations() { + @Override + public boolean isContextValid(AccessibleContext accessibleContext) { + return accessibleContext instanceof AccessibleTable; + } + + @Override + public int getChildrenCount(AccessibleContext accessibleContext) { + assert isContextValid(accessibleContext); + return ((AccessibleTable)accessibleContext).getAccessibleColumnCount(); + } + + @Override + public Accessible getAccessibleChild(AccessibleContext accessibleContext, int childIndex) { + assert isContextValid(accessibleContext); + return ((AccessibleTable)accessibleContext).getAccessibleAt(tableRowIndex, childIndex); + } + }; + } + } + // Either gets the immediate children of a, or recursively gets all unignored children of a - private static void _addChildren(final Accessible a, final int whichChildren, final boolean allowIgnored, final ArrayList childrenAndRoles) { + private static void _addChildren(Accessible a, int whichChildren, boolean allowIgnored, ArrayList childrenAndRoles, ChildrenOperations ops) { if (a == null) return; final AccessibleContext ac = a.getAccessibleContext(); - if (ac == null) return; + if (!ops.isContextValid(ac)) return; - final int numChildren = ac.getAccessibleChildrenCount(); + final int numChildren = ops.getChildrenCount(ac); // each child takes up two entries in the array: itself, and its role // so the array holds alternating Accessible and AccessibleRole objects for (int i = 0; i < numChildren; i++) { - final Accessible child = ac.getAccessibleChild(i); + final Accessible child = ops.getAccessibleChild(ac, i); if (child == null) continue; final AccessibleContext context = child.getAccessibleContext(); @@ -894,7 +953,7 @@ class CAccessibility implements PropertyChangeListener { final AccessibleRole role = context.getAccessibleRole(); if (role != null && ignoredRoles != null && ignoredRoles.contains(roleKey(role))) { // Get the child's unignored children. - _addChildren(child, whichChildren, false, childrenAndRoles); + _addChildren(child, whichChildren, false, childrenAndRoles, ChildrenOperations.COMMON); } else { childrenAndRoles.add(child); childrenAndRoles.add(getAccessibleRole(child)); diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessible.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessible.java index 097f662b87cf9031d01352858d5f310f9b6f5337..d983635f9e9d7f9131ce0fe11d4d127dba9acb64 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessible.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessible.java @@ -74,6 +74,7 @@ class CAccessible extends CFRetainedResource implements Accessible { private static native void treeNodeExpanded(long ptr); private static native void treeNodeCollapsed(long ptr); private static native void selectedCellsChanged(long ptr); + private static native void tableContentCacheClear(long ptr); private Accessible accessible; @@ -124,6 +125,13 @@ class CAccessible extends CFRetainedResource implements Accessible { selectionChanged(ptr); } else if (name.equals(ACCESSIBLE_TABLE_MODEL_CHANGED)) { valueChanged(ptr); + if (CAccessible.getSwingAccessible(CAccessible.this) != null) { + Accessible a = CAccessible.getSwingAccessible(CAccessible.this); + AccessibleContext ac = a.getAccessibleContext(); + if ((ac != null) && (ac.getAccessibleRole() == AccessibleRole.TABLE)) { + tableContentCacheClear(ptr); + } + } } else if (name.equals(ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY)) { if (newValue instanceof AccessibleContext) { activeDescendant = (AccessibleContext)newValue; @@ -156,24 +164,18 @@ class CAccessible extends CFRetainedResource implements Accessible { treeNodeCollapsed(ptr); } - // At least for now don't handle combo box menu state changes. - // This may change when later fixing issues which currently - // exist for combo boxes, but for now the following is only - // for JPopupMenus, not for combobox menus. - if (parentRole != AccessibleRole.COMBO_BOX) { - if (thisRole == AccessibleRole.POPUP_MENU) { - if ( newValue != null && - ((AccessibleState)newValue) == AccessibleState.VISIBLE ) { - menuOpened(ptr); - } else if ( oldValue != null && - ((AccessibleState)oldValue) == AccessibleState.VISIBLE ) { - menuClosed(ptr); - } - } else if (thisRole == AccessibleRole.MENU_ITEM) { - if ( newValue != null && - ((AccessibleState)newValue) == AccessibleState.FOCUSED ) { - menuItemSelected(ptr); - } + if (thisRole == AccessibleRole.POPUP_MENU) { + if ( newValue != null && + ((AccessibleState)newValue) == AccessibleState.VISIBLE ) { + menuOpened(ptr); + } else if ( oldValue != null && + ((AccessibleState)oldValue) == AccessibleState.VISIBLE ) { + menuClosed(ptr); + } + } else if (thisRole == AccessibleRole.MENU_ITEM) { + if ( newValue != null && + ((AccessibleState)newValue) == AccessibleState.FOCUSED ) { + menuItemSelected(ptr); } } diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFRetainedResource.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFRetainedResource.java index de0553501e6b400a06c0e807ac581ac8384a54c5..43d6c218b29686652edc52357254e76a875f421b 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFRetainedResource.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFRetainedResource.java @@ -163,7 +163,7 @@ public class CFRetainedResource { } @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected final void finalize() throws Throwable { dispose(); } diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index eb97221dc728893322ebd7b5d0d78580e105ba68..1aa4eae1e5d1b375663aed01382a9d61549fc304 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -244,12 +244,12 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo c.execute(ptr -> nativeRevalidateNSWindowShadow(ptr)); }}, new Property(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) { - if (value == null || !(value instanceof java.io.File)) { + if (!(value instanceof java.io.File file)) { c.execute(ptr->nativeSetNSWindowRepresentedFilename(ptr, null)); return; } - final String filename = ((java.io.File)value).getAbsolutePath(); + final String filename = file.getAbsolutePath(); c.execute(ptr->nativeSetNSWindowRepresentedFilename(ptr, filename)); }}, new Property(WINDOW_FULL_CONTENT) { diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java index 4849c16b79f0ce303e8816d89872dabbcf32d158..8dd0246228437192f5d08799196fb925b527f87e 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java @@ -598,7 +598,7 @@ public final class CPrinterJob extends RasterPrinterJob { // The following methods are CPrinterJob specific. @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() { synchronized (fNSPrintInfoLock) { if (fNSPrintInfo != -1) { @@ -845,10 +845,10 @@ public final class CPrinterJob extends RasterPrinterJob { @Override protected MediaSize getMediaSize(Media media, PrintService service, PageFormat page) { - if (media == null || !(media instanceof MediaSizeName)) { + if (!(media instanceof MediaSizeName msn)) { return getDefaultMediaSize(page); } - MediaSize size = MediaSize.getMediaSizeForName((MediaSizeName) media); + MediaSize size = MediaSize.getMediaSizeForName(msn); return size != null ? size : getDefaultMediaSize(page); } diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java index 1b037510299e476c9a13fc7b52e3b486d91837ba..4a8f5bafe85206dfb243981fef3e1831e4a44700 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java @@ -426,8 +426,7 @@ public final class LWCToolkit extends LWToolkit { // TODO Auto-generated method stub } - class OSXPlatformFont extends sun.awt.PlatformFont - { + static class OSXPlatformFont extends sun.awt.PlatformFont { OSXPlatformFont(String name, int style) { super(name, style); diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m index 8333ff489720ff99e4b5355f2764316f6f12b5a0..5f1a6f4e3c152c50418eb2dce448afbc0f325521 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTEvent.m @@ -465,14 +465,23 @@ NsCharToJavaVirtualKeyCode(unichar ch, BOOL isDeadChar, lower = tolower(ch); offset = lower - 'a'; if (offset >= 0 && offset <= 25) { - // some chars in letter set are NOT actually A-Z characters?! - // skip them... + // checking for A-Z characters *postsTyped = YES; // do quick conversion *keyCode = java_awt_event_KeyEvent_VK_A + offset; *keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_STANDARD; return; - } + } else { + // checking for non-english characters + // this value comes from ExtendedKeyCodes.java + offset += 0x01000000; + *postsTyped = YES; + // do quick conversion + // the keyCode is off by 32, so adding it here + *keyCode = java_awt_event_KeyEvent_VK_A + offset + 32; + *keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_STANDARD; +return; + } } if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:ch]) { diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m index a1dc40ffd174f20a988a8aa09a47e0208fb38a94..7f297b0b0653137ae81b95af6f6e04bbcf439ff4 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m @@ -1516,54 +1516,6 @@ JNI_COCOA_ENTER(env); JNI_COCOA_EXIT(env); } -/* - * Class: sun_lwawt_macosx_CAccessible - * Method: menuOpened - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuOpened -(JNIEnv *env, jclass jklass, jlong element) -{ -JNI_COCOA_ENTER(env); - [ThreadUtilities performOnMainThread:@selector(postMenuOpened) - on:(JavaComponentAccessibility *)jlong_to_ptr(element) - withObject:nil - waitUntilDone:NO]; -JNI_COCOA_EXIT(env); -} - -/* - * Class: sun_lwawt_macosx_CAccessible - * Method: menuClosed - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuClosed -(JNIEnv *env, jclass jklass, jlong element) -{ -JNI_COCOA_ENTER(env); - [ThreadUtilities performOnMainThread:@selector(postMenuClosed) - on:(JavaComponentAccessibility *)jlong_to_ptr(element) - withObject:nil - waitUntilDone:NO]; -JNI_COCOA_EXIT(env); -} - -/* - * Class: sun_lwawt_macosx_CAccessible - * Method: menuItemSelected - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuItemSelected -(JNIEnv *env, jclass jklass, jlong element) -{ -JNI_COCOA_ENTER(env); - [ThreadUtilities performOnMainThread:@selector(postMenuItemSelected) - on:(JavaComponentAccessibility *)jlong_to_ptr(element) - withObject:nil - waitUntilDone:NO]; -JNI_COCOA_EXIT(env); -} - /* * Class: sun_lwawt_macosx_CAccessible * Method: unregisterFromCocoaAXSystem diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.h index bcaa0269576acb0cedf9c9372c3d539974f4e389..ef67c92a06d556f31253d4a4f47f6f48d7013a6c 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.h @@ -22,7 +22,7 @@ * questions. */ -#import "CommonComponentAccessibility.h" +#import "ComponentWrapperAccessibility.h" -@interface CellAccessibility : CommonComponentAccessibility +@interface CellAccessibility : ComponentWrapperAccessibility @end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.m index 05ac73bc4f271e625f0f7e87ab537f5c230a5924..c44309a1e3cf49a6a36465df7f1976103f1c588f 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CellAccessibility.m @@ -35,24 +35,6 @@ return NSAccessibilityCellRole;; } -- (NSArray *)accessibilityChildren -{ - NSArray *children = [super accessibilityChildren]; - if (children == NULL) { - NSString *javaRole = [self javaRole]; - CommonComponentAccessibility *newChild = [CommonComponentAccessibility createWithParent:self - accessible:self->fAccessible - role:javaRole - index:self->fIndex - withEnv:[ThreadUtilities getJNIEnv] - withView:self->fView - isWrapped:NO]; - return [NSArray arrayWithObject:newChild]; - } else { - return children; - } -} - - (NSInteger)accessibilityIndex { return self->fIndex; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m index 9d4582445a471cf3ac50e551053b6b3e32480f73..238b82f609e6ef188315cce627eba5527caa2b5a 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ColumnAccessibility.m @@ -49,61 +49,6 @@ static jmethodID jm_getChildrenAndRoles = NULL; return NSAccessibilityColumnRole; } -- (NSArray *)accessibilityChildren -{ - NSArray *children = [super accessibilityChildren]; - if (children == NULL) { - JNIEnv *env = [ThreadUtilities getJNIEnv]; - CommonComponentAccessibility *parent = [self accessibilityParent]; - if (parent->fAccessible == NULL) return nil; - GET_CHILDRENANDROLES_METHOD_RETURN(nil); - jobjectArray jchildrenAndRoles = (jobjectArray)(*env)->CallStaticObjectMethod(env, sjc_CAccessibility, jm_getChildrenAndRoles, - parent->fAccessible, parent->fComponent, sun_lwawt_macosx_CAccessibility_JAVA_AX_ALL_CHILDREN, NO); - CHECK_EXCEPTION(); - if (jchildrenAndRoles == NULL) return nil; - - jsize arrayLen = (*env)->GetArrayLength(env, jchildrenAndRoles); - NSMutableArray *childrenCells = [NSMutableArray arrayWithCapacity:arrayLen/2]; - - NSUInteger childIndex = fIndex; - - int inc = [(TableAccessibility *)[self accessibilityParent] accessibilityRowCount] * 2; - NSInteger i = childIndex * 2; - for(i; i < arrayLen; i += inc) - { - jobject /* Accessible */ jchild = (*env)->GetObjectArrayElement(env, jchildrenAndRoles, i); - jobject /* String */ jchildJavaRole = (*env)->GetObjectArrayElement(env, jchildrenAndRoles, i+1); - - NSString *childJavaRole = nil; - if (jchildJavaRole != NULL) { - DECLARE_CLASS_RETURN(sjc_AccessibleRole, "javax/accessibility/AccessibleRole", nil); - DECLARE_FIELD_RETURN(sjf_key, sjc_AccessibleRole, "key", "Ljava/lang/String;", nil); - jobject jkey = (*env)->GetObjectField(env, jchildJavaRole, sjf_key); - CHECK_EXCEPTION(); - childJavaRole = JavaStringToNSString(env, jkey); - (*env)->DeleteLocalRef(env, jkey); - } - - CellAccessibility *child = [[CellAccessibility alloc] initWithParent:self - withEnv:env - withAccessible:jchild - withIndex:childIndex - withView:self->fView - withJavaRole:childJavaRole]; - [childrenCells addObject:[[child retain] autorelease]]; - - (*env)->DeleteLocalRef(env, jchild); - (*env)->DeleteLocalRef(env, jchildJavaRole); - - childIndex += (inc / 2); - } - (*env)->DeleteLocalRef(env, jchildrenAndRoles); - return childrenCells; - } else { - return children; - } -} - - (NSInteger)accessibilityIndex { return fIndex; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.h index fc81a1e8e09760a387de0fb3bab5bb7a14c43fce..33ab5c5fd2e5cb9623ba41eb7023ab96a427efcd 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.h @@ -65,20 +65,16 @@ + (void) initializeRolesMap; -+ (CommonComponentAccessibility* _Nullable) getComponentAccessibility:(NSString* _Nonnull)role; -+ (CommonComponentAccessibility * _Nullable) getComponentAccessibility:(NSString * _Nonnull)role andParent:(CommonComponentAccessibility * _Nonnull)parent; ++ (Class _Nonnull) getComponentAccessibilityClass:(NSString* _Nonnull)role; ++ (Class _Nonnull) getComponentAccessibilityClass:(NSString * _Nonnull)role andParent:(CommonComponentAccessibility * _Nonnull)parent; + (NSArray* _Nullable)childrenOfParent:(CommonComponentAccessibility* _Nonnull)parent withEnv:(JNIEnv _Nonnull * _Nonnull)env withChildrenCode:(NSInteger)whichChildren allowIgnored:(BOOL)allowIgnored; + (NSArray* _Nullable)childrenOfParent:(CommonComponentAccessibility* _Nonnull)parent withEnv:(JNIEnv _Nonnull * _Nonnull)env withChildrenCode:(NSInteger)whichChildren allowIgnored:(BOOL)allowIgnored recursive:(BOOL)recursive; + (CommonComponentAccessibility* _Nullable) createWithParent:(CommonComponentAccessibility* _Nullable)parent accessible:(jobject _Nonnull)jaccessible role:(NSString* _Nonnull)javaRole index:(jint)index withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view; ++ (CommonComponentAccessibility* _Nullable) createWithParent:(CommonComponentAccessibility* _Nullable)parent withClass:(Class _Nonnull)classType accessible:(jobject _Nonnull)jaccessible role:(NSString* _Nonnull)javaRole index:(jint)index withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view; + (CommonComponentAccessibility* _Nullable) createWithAccessible:(jobject _Nonnull)jaccessible role:(NSString* _Nonnull)role index:(jint)index withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view; + (CommonComponentAccessibility* _Nullable) createWithAccessible:(jobject _Nonnull)jaccessible withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view; -// If the isWraped parameter is true, then the object passed as a parent was created based on the same java component, -// but performs a different NSAccessibilityRole of a table cell, or a list row, or tree row, -// and we need to create an element whose role corresponds to the role in Java. -+ (CommonComponentAccessibility* _Nullable) createWithParent:(CommonComponentAccessibility* _Nullable)parent accessible:(jobject _Nonnull)jaccessible role:(NSString* _Nonnull)javaRole index:(jint)index withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view isWrapped:(BOOL)wrapped; - // The current parameter is used to bypass the check for an item's index on the parent so that the item is created. This is necessary, // for example, for AccessibleJTreeNode, whose currentComponent has index -1 + (CommonComponentAccessibility* _Nullable) createWithAccessible:(jobject _Nonnull)jaccessible withEnv:(JNIEnv _Nonnull * _Nonnull)env withView:(NSView* _Nonnull)view isCurrent:(BOOL)current; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m index d5680e3d05a4ffc9b80780ee1516075cff05fdc1..69fc9908fd5388d006c50b38c624948e8797ef8b 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/CommonComponentAccessibility.m @@ -122,7 +122,7 @@ static jobject sAccessibilityClass = NULL; /* * Here we should keep all the mapping between the accessibility roles and implementing classes */ - rolesMap = [[NSMutableDictionary alloc] initWithCapacity:46]; + rolesMap = [[NSMutableDictionary alloc] initWithCapacity:51]; [rolesMap setObject:@"ButtonAccessibility" forKey:@"pushbutton"]; [rolesMap setObject:@"ImageAccessibility" forKey:@"icon"]; @@ -152,6 +152,11 @@ static jobject sAccessibilityClass = NULL; [rolesMap setObject:@"ListAccessibility" forKey:@"list"]; [rolesMap setObject:@"OutlineAccessibility" forKey:@"tree"]; [rolesMap setObject:@"TableAccessibility" forKey:@"table"]; + [rolesMap setObject:@"MenuBarAccessibility" forKey:@"menubar"]; + [rolesMap setObject:@"MenuAccessibility" forKey:@"menu"]; + [rolesMap setObject:@"MenuItemAccessibility" forKey:@"menuitem"]; + [rolesMap setObject:@"MenuAccessibility" forKey:@"popupmenu"]; + [rolesMap setObject:@"ProgressIndicatorAccessibility" forKey:@"progressbar"]; /* * All the components below should be ignored by the accessibility subsystem, @@ -218,9 +223,9 @@ static jobject sAccessibilityClass = NULL; /* * If new implementation of the accessible component peer for the given role exists - * return the allocated class otherwise return nil to let old implementation being initialized + * return the component's class otherwise return CommonComponentAccessibility */ -+ (CommonComponentAccessibility *) getComponentAccessibility:(NSString *)role ++ (Class) getComponentAccessibilityClass:(NSString *)role { AWT_ASSERT_APPKIT_THREAD; if (rolesMap == nil) { @@ -229,12 +234,12 @@ static jobject sAccessibilityClass = NULL; NSString *className = [rolesMap objectForKey:role]; if (className != nil) { - return [NSClassFromString(className) alloc]; + return NSClassFromString(className); } - return [CommonComponentAccessibility alloc]; + return [CommonComponentAccessibility class]; } -+ (CommonComponentAccessibility *) getComponentAccessibility:(NSString *)role andParent:(CommonComponentAccessibility *)parent ++ (Class) getComponentAccessibilityClass:(NSString *)role andParent:(CommonComponentAccessibility *)parent { AWT_ASSERT_APPKIT_THREAD; if (rolesMap == nil) { @@ -242,9 +247,9 @@ static jobject sAccessibilityClass = NULL; } NSString *className = [rowRolesMapForParent objectForKey:[[parent class] className]]; if (className == nil) { - return [CommonComponentAccessibility getComponentAccessibility:role]; + return [CommonComponentAccessibility getComponentAccessibilityClass:role]; } - return [NSClassFromString(className) alloc]; + return NSClassFromString(className); } - (id)initWithParent:(NSObject *)parent withEnv:(JNIEnv *)env withAccessible:(jobject)accessible withIndex:(jint)index withView:(NSView *)view withJavaRole:(NSString *)javaRole @@ -419,13 +424,20 @@ static jobject sAccessibilityClass = NULL; GET_CACCESSIBLE_CLASS_RETURN(NULL); DECLARE_STATIC_METHOD_RETURN(sjm_getCAccessible, sjc_CAccessible, "getCAccessible", "(Ljavax/accessibility/Accessible;)Lsun/lwawt/macosx/CAccessible;", NULL); - if ((*env)->IsInstanceOf(env, jaccessible, sjc_CAccessible)) { - return jaccessible; - } else if ((*env)->IsInstanceOf(env, jaccessible, sjc_Accessible)) { - jobject o = (*env)->CallStaticObjectMethod(env, sjc_CAccessible, sjm_getCAccessible, jaccessible); + + // jaccessible is a weak ref, check it's still alive + jobject jaccessibleLocal = (*env)->NewLocalRef(env, jaccessible); + if ((*env)->IsSameObject(env, jaccessibleLocal, NULL)) return NULL; + + if ((*env)->IsInstanceOf(env, jaccessibleLocal, sjc_CAccessible)) { + return jaccessibleLocal; // delete in the caller + } else if ((*env)->IsInstanceOf(env, jaccessibleLocal, sjc_Accessible)) { + jobject jCAX = (*env)->CallStaticObjectMethod(env, sjc_CAccessible, sjm_getCAccessible, jaccessibleLocal); CHECK_EXCEPTION(); - return o; + (*env)->DeleteLocalRef(env, jaccessibleLocal); + return jCAX; // delete in the caller } + (*env)->DeleteLocalRef(env, jaccessibleLocal); return NULL; } @@ -525,29 +537,25 @@ static jobject sAccessibilityClass = NULL; + (CommonComponentAccessibility *) createWithParent:(CommonComponentAccessibility *)parent accessible:(jobject)jaccessible role:(NSString *)javaRole index:(jint)index withEnv:(JNIEnv *)env withView:(NSView *)view { - return [CommonComponentAccessibility createWithParent:parent accessible:jaccessible role:javaRole index:index withEnv:env withView:view isWrapped:NO]; + Class classType = [self getComponentAccessibilityClass:javaRole andParent:parent]; + return [CommonComponentAccessibility createWithParent:parent withClass:classType accessible:jaccessible role:javaRole index:index withEnv:env withView:view]; } -+ (CommonComponentAccessibility *) createWithParent:(CommonComponentAccessibility *)parent accessible:(jobject)jaccessible role:(NSString *)javaRole index:(jint)index withEnv:(JNIEnv *)env withView:(NSView *)view isWrapped:(BOOL)wrapped ++ (CommonComponentAccessibility *) createWithParent:(CommonComponentAccessibility *)parent withClass:(Class)classType accessible:(jobject)jaccessible role:(NSString *)javaRole index:(jint)index withEnv:(JNIEnv *)env withView:(NSView *)view { GET_CACCESSIBLE_CLASS_RETURN(NULL); DECLARE_FIELD_RETURN(jf_ptr, sjc_CAccessible, "ptr", "J", NULL); // try to fetch the jCAX from Java, and return autoreleased jobject jCAX = [CommonComponentAccessibility getCAccessible:jaccessible withEnv:env]; if (jCAX == NULL) return nil; - if (!wrapped) { // If wrapped is true, then you don't need to get an existing instance, you need to create a new one - CommonComponentAccessibility *value = (CommonComponentAccessibility *) jlong_to_ptr((*env)->GetLongField(env, jCAX, jf_ptr)); - if (value != nil) { - (*env)->DeleteLocalRef(env, jCAX); - return [[value retain] autorelease]; - } + CommonComponentAccessibility *value = (CommonComponentAccessibility *) jlong_to_ptr((*env)->GetLongField(env, jCAX, jf_ptr)); + if (value != nil) { + (*env)->DeleteLocalRef(env, jCAX); + return [[value retain] autorelease]; } - // otherwise, create a new instance - CommonComponentAccessibility *newChild = [CommonComponentAccessibility getComponentAccessibility:javaRole andParent:parent]; - - // must init freshly -alloc'd object - [newChild initWithParent:parent withEnv:env withAccessible:jCAX withIndex:index withView:view withJavaRole:javaRole]; // must init new instance + CommonComponentAccessibility *newChild = + [[classType alloc] initWithParent:parent withEnv:env withAccessible:jCAX withIndex:index withView:view withJavaRole:javaRole]; // If creating a JPopupMenu (not a combobox popup list) need to fire menuOpened. // This is the only way to know if the menu is opening; visible state change @@ -561,10 +569,7 @@ static jobject sAccessibilityClass = NULL; [newChild retain]; (*env)->SetLongField(env, jCAX, jf_ptr, ptr_to_jlong(newChild)); - // the link is removed in the wrapper - if (!wrapped) { - (*env)->DeleteLocalRef(env, jCAX); - } + (*env)->DeleteLocalRef(env, jCAX); // return autoreleased instance return [newChild autorelease]; @@ -787,7 +792,7 @@ static jobject sAccessibilityClass = NULL; (*env)->DeleteLocalRef(env, axComponent); point.y += size.height; - point.y = [[[[self view] window] screen] frame].size.height - point.y; + point.y = [[[NSScreen screens] objectAtIndex:0] frame].size.height - point.y; return NSMakeRect(point.x, point.y, size.width, size.height); } @@ -985,7 +990,7 @@ static jobject sAccessibilityClass = NULL; point.y += size.height; // Now make it into Cocoa screen coords. - point.y = [[[[self view] window] screen] frame].size.height - point.y; + point.y = [[[NSScreen screens] objectAtIndex:0] frame].size.height - point.y; return point; } @@ -1093,7 +1098,7 @@ static jobject sAccessibilityClass = NULL; "(Ljava/awt/Container;FF)Ljavax/accessibility/Accessible;", nil); // Make it into java screen coords - point.y = [[[[self view] window] screen] frame].size.height - point.y; + point.y = [[[NSScreen screens] objectAtIndex:0] frame].size.height - point.y; jobject jparent = fComponent; @@ -1253,3 +1258,51 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_selectedCellsChanged waitUntilDone:NO]; JNI_COCOA_EXIT(env); } + +/* + * Class: sun_lwawt_macosx_CAccessible + * Method: menuOpened + * Signature: (I)V + */ +JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuOpened + (JNIEnv *env, jclass jklass, jlong element) +{ + JNI_COCOA_ENTER(env); + [ThreadUtilities performOnMainThread:@selector(postMenuOpened) + on:(CommonComponentAccessibility *)jlong_to_ptr(element) + withObject:nil + waitUntilDone:NO]; + JNI_COCOA_EXIT(env); +} + +/* + * Class: sun_lwawt_macosx_CAccessible + * Method: menuClosed + * Signature: (I)V + */ +JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuClosed + (JNIEnv *env, jclass jklass, jlong element) +{ + JNI_COCOA_ENTER(env); + [ThreadUtilities performOnMainThread:@selector(postMenuClosed) + on:(CommonComponentAccessibility *)jlong_to_ptr(element) + withObject:nil + waitUntilDone:NO]; + JNI_COCOA_EXIT(env); +} + +/* + * Class: sun_lwawt_macosx_CAccessible + * Method: menuItemSelected + * Signature: (I)V + */ +JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_menuItemSelected + (JNIEnv *env, jclass jklass, jlong element) +{ + JNI_COCOA_ENTER(env); + [ThreadUtilities performOnMainThread:@selector(postMenuItemSelected) + on:(CommonComponentAccessibility *)jlong_to_ptr(element) + withObject:nil + waitUntilDone:NO]; + JNI_COCOA_EXIT(env); +} diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.h new file mode 100644 index 0000000000000000000000000000000000000000..fd1e774c274cbdb5a766b2169d8a0457c1f5c452 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +#import "CommonComponentAccessibility.h" + +/** + * Some native a11y elements do not have direct peers in Java, like list rows and cells. + * However, these elements are required by Cocoa in order for a11y to work properly. + * The ComponentWrapperAccessibility interface provides a concept of wrapping an element + * originated from java (like a list item, or a table element) with a component + * which has a11y role required Cocoa (like NSAccessibilityRowRole, or NSAccessibilityCellRole) + * but does not have peer in java. + * + * The wrapping component becomes a parent of the wrapped child in the a11y hierarchy. + * The child component is created automatically on demand with the same set of arguments, + * except that it has a11y role of its java peer. + * + * It is important that only the wrapping component is linked with sun.lwawt.macosx.CAccessible + * and thus its lifecycle depends on the java accessible. So when the same java accessible is passed + * to create a native peer, the wrapping component is retrieved in case it has already been + * created (see [CommonComponentAccessibility createWithParent]). When the wrapping component is + * deallocated (as triggered from the java side) it releases the wrapped child. + */ +@interface ComponentWrapperAccessibility : CommonComponentAccessibility + +@property (nonatomic, retain) CommonComponentAccessibility *wrappedChild; + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.m new file mode 100644 index 0000000000000000000000000000000000000000..2101d7042fe62fa757022b09fcc8f2d6ebee1ee7 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ComponentWrapperAccessibility.m @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +#import "ComponentWrapperAccessibility.h" +#import "ThreadUtilities.h" + +@implementation ComponentWrapperAccessibility + +@synthesize wrappedChild; + +- (NSAccessibilityRole)accessibilityRole { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"You must override -(NSAccessibilityRole)accessibilityRole in a subclass"] + userInfo:nil]; +} + +- (NSArray *)accessibilityChildren { + if (!wrappedChild) { + wrappedChild = + [[CommonComponentAccessibility alloc] initWithParent:self + withEnv:[ThreadUtilities getJNIEnv] + withAccessible:fAccessible + withIndex:0 + withView:fView + withJavaRole:fJavaRole]; + } + return [NSArray arrayWithObject:wrappedChild]; +} + +- (void)dealloc { + if (wrappedChild) { + [wrappedChild release]; + } + [super dealloc]; +} + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.h index 2453f92e58fe052a0cbafb179de14294311c380d..130d12721e6de0e54a793204aaa5991885182cee 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.h @@ -22,7 +22,7 @@ * questions. */ -#import "CommonComponentAccessibility.h" +#import "ComponentWrapperAccessibility.h" -@interface ListRowAccessibility : CommonComponentAccessibility +@interface ListRowAccessibility : ComponentWrapperAccessibility @end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.m index 2c4d51e10ffab51c6849db66712dd2814bf8a69d..8b30080c85b78eb772eda242b61dbc6c9e4f9172 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ListRowAccessibility.m @@ -38,25 +38,6 @@ return NSAccessibilityRowRole; } -- (NSArray *)accessibilityChildren -{ - NSArray *children = [super accessibilityChildren]; - if (children == NULL) { - - // Since the row element has already been created, we should no create it again, but just retrieve it by a pointer, that's why isWrapped is set to YES. - CommonComponentAccessibility *newChild = [CommonComponentAccessibility createWithParent:self - accessible:self->fAccessible - role:self->fJavaRole - index:self->fIndex - withEnv:[ThreadUtilities getJNIEnv] - withView:self->fView - isWrapped:YES]; - return [NSArray arrayWithObject:newChild]; - } else { - return children; - } -} - - (NSInteger)accessibilityIndex { return [[self accessibilityParent] accessibilityIndexOfChild:self]; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.h new file mode 100644 index 0000000000000000000000000000000000000000..65e127aceed343f615df4cacb23ee3125bde3cfe --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "CommonComponentAccessibility.h" +#import "GroupAccessibility.h" + +#import + +@interface MenuAccessibility : GroupAccessibility { + +}; +- (NSAccessibilityRole _Nonnull)accessibilityRole; +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m new file mode 100644 index 0000000000000000000000000000000000000000..6dc4d050db2190be4f2b0236e38ad14cecd29d03 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "MenuAccessibility.h" + +/* + * Implementing a protocol that represents menus both as submenu and as a + * MenuBar components + */ +@implementation MenuAccessibility +- (NSAccessibilityRole _Nonnull)accessibilityRole +{ + return [[[self parent] javaRole] isEqualToString:@"combobox"] + ? NSAccessibilityPopUpButtonRole + : NSAccessibilityMenuRole; +} + +- (BOOL)isAccessibilityElement +{ + return YES; +} + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.h new file mode 100644 index 0000000000000000000000000000000000000000..3a69dd40c457ab414f2d2e9cd49c4064e1177dee --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "CommonComponentAccessibility.h" + +#import + +@interface MenuBarAccessibility : CommonComponentAccessibility { + +}; +- (NSAccessibilityRole _Nonnull)accessibilityRole; +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.m new file mode 100644 index 0000000000000000000000000000000000000000..d21bf5318daea87f2b9fb48d8137b4e2cedad998 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuBarAccessibility.m @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "MenuBarAccessibility.h" +#import "JNIUtilities.h" +#import "ThreadUtilities.h" +#import "sun_lwawt_macosx_CAccessibility.h" + +/* + * This is the protocol for the Menu Bar component + */ +@implementation MenuBarAccessibility +- (NSAccessibilityRole _Nonnull)accessibilityRole +{ + return NSAccessibilityMenuBarRole; +} + +- (BOOL)isAccessibilityElement +{ + return YES; +} + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.h new file mode 100644 index 0000000000000000000000000000000000000000..19a1cc71a694a5806a3e46664c1d5a8fc302a9f7 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "CommonComponentAccessibility.h" +#import "ButtonAccessibility.h" + +#import + +@interface MenuItemAccessibility : ButtonAccessibility { + +}; +- (NSAccessibilityRole _Nonnull)accessibilityRole; +- (void)handleAction:(NSMenuItem * _Nonnull)sender; +@end diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AnnotationTypeOptionalMemberWriter.java b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.m similarity index 57% rename from src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AnnotationTypeOptionalMemberWriter.java rename to src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.m index 60eb2ac9bdfe5da410fa82f7a5ddb786d94219f7..945e50975ebb1df0cd78b5a426573f6fff21da13 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AnnotationTypeOptionalMemberWriter.java +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuItemAccessibility.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,27 +23,40 @@ * questions. */ -package jdk.javadoc.internal.doclets.toolkit; +#import "MenuItemAccessibility.h" -import javax.lang.model.element.Element; - -/** - * The interface for writing annotation type optional member output. - * - *

      This is NOT part of any supported API. - * If you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. +/* + * This is the protocol for the MenuItem component. */ +@implementation MenuItemAccessibility +- (NSAccessibilityRole _Nonnull)accessibilityRole +{ + return NSAccessibilityMenuItemRole; +} + +- (BOOL)isAccessibilityElement +{ + return YES; +} -public interface AnnotationTypeOptionalMemberWriter extends - AnnotationTypeRequiredMemberWriter { +- (BOOL)accessibilityPerformPick +{ + return [self performAccessibleAction:0]; +} + +- (BOOL)accessibilityPerformPress +{ + return [self performAccessibleAction:0]; +} - /** - * Add the the default value documentation. - * - * @param member the member being documented - * @param annotationDocTree content tree to which the default value will be added - */ - void addDefaultValueInfo(Element member, Content annotationDocTree); +- (NSString * _Nullable)accessibilityLabel +{ + return [super accessibilityLabel]; } + +- (id _Nullable)accessibilityValue +{ + return [super accessibilityValue]; +} + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m index a2bce0bf70152f365d92b1989eb455f49d4a5370..e4d7e66027d9609dce2ec94c2e5854167d103542 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/OutlineRowAccessibility.m @@ -72,14 +72,7 @@ static jclass sjc_CAccessible = NULL; return children; } } - - return [NSArray arrayWithObject:[CommonComponentAccessibility createWithParent:self - accessible:self->fAccessible - role:self->fJavaRole - index:self->fIndex - withEnv:env - withView:self->fView - isWrapped:YES]]; + return [super accessibilityChildren]; } - (NSInteger)accessibilityDisclosureLevel diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.h new file mode 100644 index 0000000000000000000000000000000000000000..e5b58ea3f8b6b0c59ae896911f0870ad406aef5c --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "JavaComponentAccessibility.h" +#import "GroupAccessibility.h" + +#import + +@interface ProgressIndicatorAccessibility : GroupAccessibility { + +}; +- (NSAccessibilityRole _Nonnull)accessibilityRole; +- (NSString * _Nullable)accessibilityValue; +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.m new file mode 100644 index 0000000000000000000000000000000000000000..13ba383f166df8f78ba3a2b2bd08b25b1715eb98 --- /dev/null +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/ProgressIndicatorAccessibility.m @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#import "ProgressIndicatorAccessibility.h" + +/* + * Implementation of the accessibility peer for the NSProgressIndicator role. + * Main usage is JProgressBar + */ +@implementation ProgressIndicatorAccessibility + +- (NSAccessibilityRole _Nonnull)accessibilityRole +{ + return NSAccessibilityProgressIndicatorRole; +} + +- (NSString * _Nullable)accessibilityValue +{ + return [super accessibilityValue]; +} + +@end diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.h b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.h index 4f746706f5c53c35928165b40896b97bb4628572..5fe04aa257f61376c355d53f57ccb09052a3af29 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.h @@ -25,6 +25,9 @@ #import "CommonComponentAccessibility.h" @interface TableAccessibility : CommonComponentAccessibility +{ + NSMutableDictionary *rowCache; +} - (BOOL)isAccessibleChildSelectedFromIndex:(int)index; - (int) accessibleRowAtIndex:(int)index; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m index b3c73a38c95b7a1d9759a3a1edd1cf6c8fae5fba..d6382822e1e52a95a6a43691724e35a8175449a3 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableAccessibility.m @@ -33,6 +33,7 @@ #import "JNIUtilities.h" #import "CellAccessibility.h" #import "sun_lwawt_macosx_CAccessibility.h" +#import "sun_lwawt_macosx_CAccessible.h" static jclass sjc_CAccessibility = NULL; @@ -124,22 +125,23 @@ static jmethodID sjm_getAccessibleName = NULL; - (TableRowAccessibility *)createRowWithIndex:(NSUInteger)index { - return [[TableRowAccessibility alloc] initWithParent:self - withEnv:[ThreadUtilities getJNIEnv] - withAccessible:NULL - withIndex:index - withView:[self view] - withJavaRole:JavaAccessibilityIgnore]; -} + if (rowCache == nil) { + int rowCount = [self accessibilityRowCount]; + rowCache = [[NSMutableDictionary dictionaryWithCapacity:rowCount] retain]; + } -- (ColumnAccessibility *)createColumnWithIndex:(NSUInteger)index -{ - return [[ColumnAccessibility alloc] initWithParent:self - withEnv:[ThreadUtilities getJNIEnv] - withAccessible:NULL - withIndex:index - withView:self->fView - withJavaRole:JavaAccessibilityIgnore]; + id row = [rowCache objectForKey:[NSNumber numberWithUnsignedInteger:index]]; + if (row == nil) { + row = [[TableRowAccessibility alloc] initWithParent:self + withEnv:[ThreadUtilities getJNIEnv] + withAccessible:NULL + withIndex:index + withView:[self view] + withJavaRole:JavaAccessibilityIgnore]; + [rowCache setObject:row forKey:[NSNumber numberWithUnsignedInteger:index]]; + } + + return row; } // NSAccessibilityElement protocol methods @@ -189,26 +191,6 @@ static jmethodID sjm_getAccessibleName = NULL; return [super accessibilityParent]; } -- (nullable NSArray *)accessibilityColumns -{ - int colCount = [self accessibilityColumnCount]; - NSMutableArray *columns = [NSMutableArray arrayWithCapacity:colCount]; - for (int i = 0; i < colCount; i++) { - [columns addObject:[self createColumnWithIndex:i]]; - } - return [NSArray arrayWithArray:columns]; -} - -- (nullable NSArray *)accessibilitySelectedColumns -{ - NSArray *indexes = [self getTableSelectedInfo:sun_lwawt_macosx_CAccessibility_JAVA_AX_COLS]; - NSMutableArray *columns = [NSMutableArray arrayWithCapacity:[indexes count]]; - for (NSNumber *i in indexes) { - [columns addObject:[self createColumnWithIndex:i.unsignedIntValue]]; - } - return [NSArray arrayWithArray:columns]; -} - - (NSInteger)accessibilityRowCount { return [[self getTableInfo:sun_lwawt_macosx_CAccessibility_JAVA_AX_ROWS] integerValue]; @@ -238,4 +220,28 @@ static jmethodID sjm_getAccessibleName = NULL; return [NSArray arrayWithArray:selectedCells]; } +- (void)clearCache { + for (NSNumber *key in [rowCache allKeys]) { + [[rowCache objectForKey:key] release]; + } + [rowCache release]; + rowCache = nil; +} + @end + +/* + * Class: sun_lwawt_macosx_CAccessible + * Method: tableContentIndexDestroy + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CAccessible_tableContentCacheClear + (JNIEnv *env, jclass class, jlong element) +{ + JNI_COCOA_ENTER(env); + [ThreadUtilities performOnMainThread:@selector(clearCache) + on:(CommonComponentAccessibility *)jlong_to_ptr(element) + withObject:nil + waitUntilDone:NO]; + JNI_COCOA_EXIT(env); +} diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m index 4327d05ffad19dda49003db35da356327f61d272..31636dd99bb4acdfd08aaeda34aee3db6e1d6276 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/TableRowAccessibility.m @@ -33,12 +33,6 @@ static jclass sjc_CAccessibility = NULL; -static jmethodID jm_getChildrenAndRoles = NULL; -#define GET_CHILDRENANDROLES_METHOD_RETURN(ret) \ - GET_CACCESSIBILITY_CLASS_RETURN(ret); \ - GET_STATIC_METHOD_RETURN(jm_getChildrenAndRoles, sjc_CAccessibility, "getChildrenAndRoles",\ - "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZ)[Ljava/lang/Object;", ret); - @implementation TableRowAccessibility // NSAccessibilityElement protocol methods @@ -55,25 +49,28 @@ static jmethodID jm_getChildrenAndRoles = NULL; - (NSArray *)accessibilityChildren { - NSArray *children = [super accessibilityChildren]; + NSMutableArray *children = [super accessibilityChildren]; if (children == nil) { JNIEnv *env = [ThreadUtilities getJNIEnv]; CommonComponentAccessibility *parent = [self accessibilityParent]; if (parent->fAccessible == NULL) return nil; - GET_CHILDRENANDROLES_METHOD_RETURN(nil); - jobjectArray jchildrenAndRoles = (jobjectArray)(*env)->CallStaticObjectMethod(env, sjc_CAccessibility, jm_getChildrenAndRoles, - parent->fAccessible, parent->fComponent, sun_lwawt_macosx_CAccessibility_JAVA_AX_ALL_CHILDREN, NO); + + GET_CACCESSIBILITY_CLASS_RETURN(nil); + DECLARE_STATIC_METHOD_RETURN(jm_getTableRowChildrenAndRoles, sjc_CAccessibility, "getTableRowChildrenAndRoles",\ + "(Ljavax/accessibility/Accessible;Ljava/awt/Component;IZI)[Ljava/lang/Object;", nil); + + jobjectArray jchildrenAndRoles = (jobjectArray)(*env)->CallStaticObjectMethod( + env, sjc_CAccessibility, jm_getTableRowChildrenAndRoles, parent->fAccessible, parent->fComponent, + sun_lwawt_macosx_CAccessibility_JAVA_AX_ALL_CHILDREN, NO, [self rowNumberInTable]); CHECK_EXCEPTION(); + if (jchildrenAndRoles == NULL) return nil; jsize arrayLen = (*env)->GetArrayLength(env, jchildrenAndRoles); - NSMutableArray *childrenCells = [NSMutableArray arrayWithCapacity:arrayLen/2]; + children = [NSMutableArray arrayWithCapacity:arrayLen / 2]; + int childIndex = [self rowNumberInTable] * [(TableAccessibility *)parent accessibilityColumnCount]; - NSUInteger childIndex = fIndex * [(TableAccessibility *)parent accessibilityColumnCount]; - NSInteger i = childIndex * 2; - NSInteger n = (fIndex + 1) * [(TableAccessibility *)parent accessibilityColumnCount] * 2; - for(i; i < n; i+=2) - { + for (NSInteger i = 0; i < arrayLen; i += 2) { jobject /* Accessible */ jchild = (*env)->GetObjectArrayElement(env, jchildrenAndRoles, i); jobject /* String */ jchildJavaRole = (*env)->GetObjectArrayElement(env, jchildrenAndRoles, i+1); @@ -87,13 +84,15 @@ static jmethodID jm_getChildrenAndRoles = NULL; (*env)->DeleteLocalRef(env, jkey); } - CellAccessibility *child = [[CellAccessibility alloc] initWithParent:self - withEnv:env - withAccessible:jchild - withIndex:childIndex - withView:self->fView - withJavaRole:childJavaRole]; - [childrenCells addObject:[[child retain] autorelease]]; + CellAccessibility *child = (CellAccessibility *) + [CommonComponentAccessibility createWithParent:self + withClass:[CellAccessibility class] + accessible:jchild + role:childJavaRole + index:childIndex + withEnv:env + withView:self->fView]; + [children addObject:child]; (*env)->DeleteLocalRef(env, jchild); (*env)->DeleteLocalRef(env, jchildJavaRole); @@ -101,10 +100,12 @@ static jmethodID jm_getChildrenAndRoles = NULL; childIndex++; } (*env)->DeleteLocalRef(env, jchildrenAndRoles); - return childrenCells; - } else { - return children; } + return children; +} + +- (NSUInteger)rowNumberInTable { + return self->fIndex; } - (NSInteger)accessibilityIndex diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/EncoderManager.m b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/EncoderManager.m index 0fb18c3f4c314e29eeae50141aa885160a121398..95374d2c93e53f1d4af0bd960b70e9b7be584bee 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/EncoderManager.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/EncoderManager.m @@ -41,11 +41,9 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; - (void)dealloc; - (void)reset:(id)destination - isDstOpaque:(jboolean)isDstOpaque - isDstPremultiplied:(jboolean)isDstPremultiplied - isAA:(jboolean)isAA - isText:(jboolean)isText - isLCD:(jboolean)isLCD; + isAA:(jboolean)isAA + isText:(jboolean)isText + isLCD:(jboolean)isLCD; - (void)updateEncoder:(id)encoder context:(MTLContext *)mtlc @@ -64,7 +62,6 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; // Persistent encoder properties id _destination; - SurfaceRasterFlags _dstFlags; jboolean _isAA; jboolean _isText; @@ -123,14 +120,10 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; } - (void)reset:(id)destination - isDstOpaque:(jboolean)isDstOpaque - isDstPremultiplied:(jboolean)isDstPremultiplied - isAA:(jboolean)isAA - isText:(jboolean)isText - isLCD:(jboolean)isLCD { + isAA:(jboolean)isAA + isText:(jboolean)isText + isLCD:(jboolean)isLCD { _destination = destination; - _dstFlags.isOpaque = isDstOpaque; - _dstFlags.isPremultiplied = isDstPremultiplied; _isAA = isAA; _isText = isText; _isLCD = isLCD; @@ -288,20 +281,20 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; - (id _Nonnull)getAARenderEncoder:(const BMTLSDOps * _Nonnull)dstOps { id dstTxt = dstOps->pTexture; - RenderOptions roptions = {JNI_FALSE, JNI_TRUE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, {dstOps->isOpaque, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; + RenderOptions roptions = {JNI_FALSE, JNI_TRUE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, JNI_FALSE, JNI_FALSE, JNI_FALSE}; return [self getEncoder:dstTxt renderOptions:&roptions]; } - (id _Nonnull)getAAShaderRenderEncoder:(const BMTLSDOps * _Nonnull)dstOps { - RenderOptions roptions = {JNI_FALSE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, {dstOps->isOpaque, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_TRUE}; + RenderOptions roptions = {JNI_FALSE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, JNI_FALSE, JNI_FALSE, JNI_TRUE}; return [self getEncoder:dstOps->pTexture renderOptions:&roptions]; } - (id _Nonnull)getRenderEncoder:(id _Nonnull)dest isDstOpaque:(bool)isOpaque { - RenderOptions roptions = {JNI_FALSE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, {isOpaque, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; + RenderOptions roptions = {JNI_FALSE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, defaultRasterFlags, JNI_FALSE, JNI_FALSE, JNI_FALSE}; return [self getEncoder:dest renderOptions:&roptions]; } @@ -329,7 +322,7 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; isSrcOpaque:(bool)isSrcOpaque isDstOpaque:(bool)isDstOpaque { - RenderOptions roptions = {JNI_TRUE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, {isSrcOpaque, JNI_TRUE }, {isDstOpaque, JNI_TRUE}, JNI_FALSE, JNI_TRUE, JNI_FALSE}; + RenderOptions roptions = {JNI_TRUE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, {isSrcOpaque, JNI_TRUE }, JNI_FALSE, JNI_TRUE, JNI_FALSE}; return [self getEncoder:dest renderOptions:&roptions]; } @@ -339,7 +332,7 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; interpolation:(int)interpolation isAA:(jboolean)isAA { - RenderOptions roptions = {JNI_TRUE, isAA, interpolation, { isSrcOpaque, JNI_TRUE }, {isDstOpaque, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; + RenderOptions roptions = {JNI_TRUE, isAA, interpolation, { isSrcOpaque, JNI_TRUE }, JNI_FALSE, JNI_FALSE, JNI_FALSE}; return [self getEncoder:dest renderOptions:&roptions]; } @@ -354,7 +347,8 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; - (id _Nonnull) getTextEncoder:(const BMTLSDOps * _Nonnull)dstOps isSrcOpaque:(bool)isSrcOpaque { - RenderOptions roptions = {JNI_TRUE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, { isSrcOpaque, JNI_TRUE }, {dstOps->isOpaque, JNI_TRUE}, JNI_TRUE, JNI_FALSE, JNI_FALSE}; + RenderOptions roptions = {JNI_TRUE, JNI_FALSE, INTERPOLATION_NEAREST_NEIGHBOR, { isSrcOpaque, JNI_TRUE }, + JNI_TRUE, JNI_FALSE, JNI_FALSE}; return [self getEncoder:dstOps->pTexture renderOptions:&roptions]; } @@ -437,11 +431,9 @@ const SurfaceRasterFlags defaultRasterFlags = { JNI_FALSE, JNI_TRUE }; _encoder = [[cbw getCommandBuffer] renderCommandEncoderWithDescriptor:rpd]; [_encoderStates reset:dest - isDstOpaque:renderOptions->dstFlags.isOpaque - isDstPremultiplied:YES - isAA:renderOptions->isAA - isText:renderOptions->isText - isLCD:renderOptions->isLCD]; + isAA:renderOptions->isAA + isText:renderOptions->isText + isLCD:renderOptions->isLCD]; } // diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLBlitLoops.m b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLBlitLoops.m index bf55d8c8976d0454cd1e1f43bf895b917ac72b45..47571a5e7ae4a98862c92d59fa8aa5de880efaa0 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLBlitLoops.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLBlitLoops.m @@ -595,8 +595,9 @@ MTLBlitLoops_Blit(JNIEnv *env, } #ifdef TRACE_BLIT - J2dTraceImpl(J2D_TRACE_VERBOSE, JNI_FALSE, - "MTLBlitLoops_Blit [tx=%d, xf=%d, AC=%s]: bdst=%s, src=%p (%dx%d) O=%d premul=%d | (%d, %d, %d, %d)->(%1.2f, %1.2f, %1.2f, %1.2f)", + J2dTraceImpl(J2D_TRACE_VERBOSE, JNI_TRUE, + "MTLBlitLoops_Blit srctype=%d [tx=%d, xf=%d, AC=%s]: bdst=%s, src=%p (%dx%d) O=%d premul=%d | (%d, " + "%d, %d, %d)->(%1.2f, %1.2f, %1.2f, %1.2f)", srctype, texture, xform, [mtlc getCompositeDescription].cString, getSurfaceDescription(dstOps).cString, srcOps, sx2 - sx1, sy2 - sy1, diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLClip.m b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLClip.m index 35d8ba624c9bd00f85a1e3bea6ea0a291b50c3de..effe7aebae6f89a71e2c5c98dea19ebac98bb18d 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLClip.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLClip.m @@ -58,7 +58,6 @@ static void initTemplatePipelineDescriptors() { BMTLSDOps* _dstOps; BOOL _stencilMaskGenerationInProgress; BOOL _stencilMaskGenerationStarted; - BOOL _clipReady; MTLOrigin _clipShapeOrigin; MTLSize _clipShapeSize; } @@ -73,7 +72,6 @@ static void initTemplatePipelineDescriptors() { _dstOps = NULL; _stencilMaskGenerationInProgress = NO; _stencilMaskGenerationStarted = NO; - _clipReady = NO; } return self; } @@ -189,7 +187,6 @@ static void initTemplatePipelineDescriptors() { _stencilMaskGenerationStarted = NO; _dstOps = dstOps; _clipType = SHAPE_CLIP; - _clipReady = NO; } - (void)setMaskGenerationPipelineState:(id)encoder diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPaints.m b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPaints.m index a3b1254bf13745882cac470186788b5ada3151a3..5686449a295602e900b46342ccdc819484475993 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPaints.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPaints.m @@ -56,7 +56,7 @@ static MTLRenderPipelineDescriptor * templateLCDPipelineDesc = nil; static MTLRenderPipelineDescriptor * templateAAPipelineDesc = nil; static void setTxtUniforms(MTLContext *mtlc, int color, id encoder, int interpolation, bool repeat, - jfloat extraAlpha, const SurfaceRasterFlags *srcFlags, const SurfaceRasterFlags *dstFlags, int mode); + jfloat extraAlpha, const SurfaceRasterFlags *srcFlags, int mode); static void initTemplatePipelineDescriptors() { if (templateRenderPipelineDesc != nil && templateTexturePipelineDesc != nil && @@ -228,8 +228,8 @@ jint _color; rpDesc = [[templateLCDPipelineDesc copy] autorelease]; } setTxtUniforms(mtlc, _color, encoder, - renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], &renderOptions->srcFlags, - &renderOptions->dstFlags, 1); + renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], + &renderOptions->srcFlags, 1); } else if (renderOptions->isAAShader) { vertShader = @"vert_col_aa"; fragShader = @"frag_col_aa"; @@ -270,7 +270,7 @@ jint _color; setTxtUniforms(mtlc, col, encoder, renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], - &renderOptions->srcFlags, &renderOptions->dstFlags, 1); + &renderOptions->srcFlags, 1); [encoder setFragmentBytes:&xorColor length:sizeof(xorColor) atIndex:0]; [encoder setFragmentTexture:dstOps->pTexture atIndex:1]; @@ -809,9 +809,8 @@ jint _color; [encoder setFragmentTexture:_paintTexture atIndex:0]; } const SurfaceRasterFlags srcFlags = {_isOpaque, renderOptions->srcFlags.isPremultiplied}; - setTxtUniforms(mtlc, 0, encoder, - renderOptions->interpolation, YES, [mtlc.composite getExtraAlpha], - &srcFlags, &renderOptions->dstFlags, 0); + setTxtUniforms(mtlc, 0, encoder, renderOptions->interpolation, YES, [mtlc.composite getExtraAlpha], + &srcFlags, 0); id pipelineState = [pipelineStateStorage getPipelineState:rpDesc vertexShaderId:vertShader @@ -893,8 +892,8 @@ jint _color; static void setTxtUniforms(MTLContext *mtlc, int color, id encoder, int interpolation, bool repeat, - jfloat extraAlpha, const SurfaceRasterFlags *srcFlags, const SurfaceRasterFlags *dstFlags, int mode) { - struct TxtFrameUniforms uf = {RGBA_TO_V4(color), mode, srcFlags->isOpaque, dstFlags->isOpaque, extraAlpha}; + jfloat extraAlpha, const SurfaceRasterFlags *srcFlags, int mode) { + struct TxtFrameUniforms uf = {RGBA_TO_V4(color), mode, srcFlags->isOpaque, extraAlpha}; [encoder setFragmentBytes:&uf length:sizeof(uf) atIndex:FrameUniformBuffer]; [mtlc.samplerManager setSamplerWithEncoder:encoder interpolation:interpolation repeat:repeat]; } @@ -956,8 +955,7 @@ setTxtUniforms(MTLContext *mtlc, int color, id encoder } else { setTxtUniforms(mtlc, 0, encoder, renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], - &renderOptions->srcFlags, - &renderOptions->dstFlags, 0); + &renderOptions->srcFlags, 0); } id pipelineState = [pipelineStateStorage getPipelineState:rpDesc @@ -998,7 +996,7 @@ setTxtUniforms(MTLContext *mtlc, int color, id encoder const int col = 0 ^ xorColor; setTxtUniforms(mtlc, col, encoder, renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], - &renderOptions->srcFlags, &renderOptions->dstFlags, 0); + &renderOptions->srcFlags, 0); [encoder setFragmentBytes:&xorColor length:sizeof(xorColor) atIndex: 0]; BMTLSDOps *dstOps = MTLRenderQueue_GetCurrentDestination(); @@ -1006,8 +1004,7 @@ setTxtUniforms(MTLContext *mtlc, int color, id encoder setTxtUniforms(mtlc, 0, encoder, renderOptions->interpolation, NO, [mtlc.composite getExtraAlpha], - &renderOptions->srcFlags, - &renderOptions->dstFlags, 0); + &renderOptions->srcFlags, 0); id pipelineState = [pipelineStateStorage getPipelineState:rpDesc vertexShaderId:vertShader diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPipelineStatesStorage.m b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPipelineStatesStorage.m index 0928f12d426958d74803eff3e1353a40ecad5b89..9a7862e8c263044cd1a1c9c8977add83640a3587 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPipelineStatesStorage.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/MTLPipelineStatesStorage.m @@ -84,7 +84,7 @@ static void setBlendingFactors( vertexShaderId:(NSString *)vertexShaderId fragmentShaderId:(NSString *)fragmentShaderId { - RenderOptions defaultOptions = {JNI_FALSE, JNI_FALSE, 0/*unused*/, {JNI_FALSE, JNI_TRUE}, {JNI_FALSE, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; + RenderOptions defaultOptions = {JNI_FALSE, JNI_FALSE, 0/*unused*/, {JNI_FALSE, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; return [self getPipelineState:pipelineDescriptor vertexShaderId:vertexShaderId fragmentShaderId:fragmentShaderId @@ -98,7 +98,7 @@ static void setBlendingFactors( fragmentShaderId:(NSString *)fragmentShaderId stencilNeeded:(bool)stencilNeeded { - RenderOptions defaultOptions = {JNI_FALSE, JNI_FALSE, 0/*unused*/, {JNI_FALSE, JNI_TRUE}, {JNI_FALSE, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; + RenderOptions defaultOptions = {JNI_FALSE, JNI_FALSE, 0/*unused*/, {JNI_FALSE, JNI_TRUE}, JNI_FALSE, JNI_FALSE, JNI_FALSE}; return [self getPipelineState:pipelineDescriptor vertexShaderId:vertexShaderId fragmentShaderId:fragmentShaderId @@ -107,6 +107,19 @@ static void setBlendingFactors( stencilNeeded:stencilNeeded]; } +// Pipeline state index +union StateIndex { + uint32_t value; + struct { + uint32_t srcPremultiplied : 1, + srcOpaque : 1, + stencil : 1, + aa : 1, + extAlpha : 1, + compositeRule : 27; + } bits; +}; + // Base method to obtain MTLRenderPipelineState. // NOTE: parameters compositeRule, srcFlags, dstFlags are used to set MTLRenderPipelineColorAttachmentDescriptor multipliers - (id) getPipelineState:(MTLRenderPipelineDescriptor *) pipelineDescriptor @@ -123,45 +136,31 @@ static void setBlendingFactors( // Calculate index by flags and compositeRule // TODO: reimplement, use map with convenient key (calculated by all arguments) - int subIndex = 0; + union StateIndex index; + index.value = 0; if (useXorComposite) { // compositeRule value is already XOR_COMPOSITE_RULE } else { if (useComposite) { - if (!renderOptions->srcFlags.isPremultiplied) - subIndex |= 1; - if (renderOptions->srcFlags.isOpaque) - subIndex |= 1 << 1; - if (!renderOptions->dstFlags.isPremultiplied) - subIndex |= 1 << 2; - if (renderOptions->dstFlags.isOpaque) - subIndex |= 1 << 3; + index.bits.srcPremultiplied = renderOptions->srcFlags.isPremultiplied; + index.bits.srcOpaque = renderOptions->srcFlags.isOpaque; } else compositeRule = RULE_Src; } - if (stencilNeeded) { - subIndex |= 1 << 4; - } - - if (renderOptions->isAA) { - subIndex |= 1 << 5; - } - - if ((composite != nil && FLT_LT([composite getExtraAlpha], 1.0f))) { - subIndex |= 1 << 6; - } - - int index = compositeRule*128 + subIndex; + index.bits.stencil = stencilNeeded; + index.bits.aa = renderOptions->isAA; + index.bits.extAlpha = composite != nil && FLT_LT([composite getExtraAlpha], 1.0f); + index.bits.compositeRule = compositeRule; NSPointerArray * subStates = [self getSubStates:vertexShaderId fragmentShader:fragmentShaderId]; - if (index >= subStates.count) { - subStates.count = (NSUInteger) (index + 1); + if (index.value >= subStates.count) { + subStates.count = index.value + 1; } - id result = [subStates pointerAtIndex:index]; + id result = [subStates pointerAtIndex:index.value]; if (result == nil) { @autoreleasepool { id vertexShader = [self getShader:vertexShaderId]; @@ -222,7 +221,7 @@ static void setBlendingFactors( exit(0); } - [subStates insertPointer:result atIndex:index]; + [subStates replacePointerAtIndex:index.value withPointer:result]; } } diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/RenderOptions.h b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/RenderOptions.h index 46521ca5b09a93d389cb96c6eb10d4131671d87f..f24f131631af88b6106e617a8032f2afa980172a 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/RenderOptions.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/RenderOptions.h @@ -35,7 +35,6 @@ typedef struct { jboolean isAA; int interpolation; SurfaceRasterFlags srcFlags; - SurfaceRasterFlags dstFlags; jboolean isText; jboolean isLCD; jboolean isAAShader; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/common.h b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/common.h index 556bbf5d88ef4ded24a60900a1806f8baab6cf4a..70218f7e849c56a711d4771dd21278b20a40a263 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/common.h +++ b/src/java.desktop/macosx/native/libawt_lwawt/java2d/metal/common.h @@ -114,7 +114,6 @@ struct TxtFrameUniforms { vector_float4 color; int mode; // NOTE: consider to use bit fields int isSrcOpaque; - int isDstOpaque; float extraAlpha; }; diff --git a/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java b/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java index dd67059287dee944de88c10249e20b76060b62ec..2e4fbe5b217b3b477f09c0b66446efbc1a70fcae 100644 --- a/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java +++ b/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java @@ -199,8 +199,8 @@ public final class DocumentHandler extends DefaultHandler { * Indicates whether the variable with specified identifier is defined. * * @param id the identifier - * @return @{code true} if the variable is defined; - * @{code false} otherwise + * @return {@code true} if the variable is defined; + * {@code false} otherwise */ public boolean hasVariable(String id) { return this.environment.containsKey(id); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java index 6a020ae934354f4e8766b6f10e98122cdd9f7888..56c21e18548b539aec9b07fb908f58cc0b456eba 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -210,10 +210,8 @@ public class BMPImageWriter extends ImageWriter implements BMPConstants { IIOMetadata imageMetadata = image.getMetadata(); BMPMetadata bmpImageMetadata = null; - if (imageMetadata != null - && imageMetadata instanceof BMPMetadata) - { - bmpImageMetadata = (BMPMetadata)imageMetadata; + if (imageMetadata instanceof BMPMetadata bmp) { + bmpImageMetadata = bmp; } else { ImageTypeSpecifier imageType = new ImageTypeSpecifier(colorModel, sampleModel); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java index 95c4d9ec5970f045470e84ce1efbd5694ac0ef23..75586561598ad0cb7048647f6565df7867036640 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SimpleCMYKColorSpace.java @@ -59,7 +59,7 @@ public final class SimpleCMYKColorSpace extends ColorSpace { } public boolean equals(Object o) { - return o != null && o instanceof SimpleCMYKColorSpace; + return o instanceof SimpleCMYKColorSpace; } public int hashCode() { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SubImageInputStream.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SubImageInputStream.java index 8ddffc522f1873a8689e14a19ca0667d174d71e4..10211c6636c90bb572937f71794925fdbc21cff1 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SubImageInputStream.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/common/SubImageInputStream.java @@ -72,7 +72,7 @@ public final class SubImageInputStream extends ImageInputStreamImpl { streamPos = pos; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer (for improved performance; no need to call // super.finalize() in this case) diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java index 8566d45f6a482dd62f64b6622f6d2905ea6d652a..a3e8a769490b7822efab8e63814930b01a1f8bce 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java @@ -248,8 +248,7 @@ class GIFWritableImageMetadata extends GIFImageMetadata { Object applicationExtensionData = applicationExtension.getUserObject(); - if (applicationExtensionData == null || - !(applicationExtensionData instanceof byte[])) { + if (!(applicationExtensionData instanceof byte[])) { fatal(applicationExtension, "Bad user object in ApplicationExtension!"); } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java index 34eca627d97dd4276ff5c03cb1f38d9743c6ffa7..c14402522db4173af05dbbbafbe84f28259e7441 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java @@ -138,7 +138,7 @@ class DHTMarkerSegment extends MarkerSegment { /** * A Huffman table within a DHT marker segment. */ - class Htable implements Cloneable { + static class Htable implements Cloneable { int tableClass; // 0 == DC, 1 == AC int tableID; // 0 - 4 private static final int NUM_LENGTHS = 16; diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java index be11577f0e342b34b18b41bd01ce2720a628e4d6..8b983afc24545d8c219df220391df90cf6fa5824 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java @@ -171,7 +171,7 @@ class DQTMarkerSegment extends MarkerSegment { /** * A quantization table within a DQT marker segment. */ - class Qtable implements Cloneable { + static class Qtable implements Cloneable { int elementPrecision; int tableID; final int QTABLE_SIZE = 64; diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java index e03ceecd3934472e12472ed91110104c0869e317..8b95d8adc65fec021e1402c1ce709304d2a53f60 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java @@ -552,7 +552,7 @@ class JFIFMarkerSegment extends MarkerSegment { // Could put reason codes in here to be parsed in writeJFXXSegment // in order to provide more meaningful warnings. @SuppressWarnings("serial") // JDK-implementation class - private class IllegalThumbException extends Exception {} + private static class IllegalThumbException extends Exception {} /** * Writes out a new JFXX extension segment, without saving it. @@ -794,7 +794,7 @@ class JFIFMarkerSegment extends MarkerSegment { * A superclass for the varieties of thumbnails that can * be stored in a JFIF extension marker segment. */ - abstract class JFIFThumb implements Cloneable { + abstract static class JFIFThumb implements Cloneable { long streamPos = -1L; // Save the thumbnail pos when reading abstract int getLength(); // When writing abstract int getWidth(); @@ -1111,7 +1111,7 @@ class JFIFMarkerSegment extends MarkerSegment { * to clip these, but the entire image must fit into a * single JFXX marker segment. */ - class JFIFThumbJPEG extends JFIFThumb { + static class JFIFThumbJPEG extends JFIFThumb { JPEGMetadata thumbMetadata = null; byte [] data = null; // Compressed image data, for writing private static final int PREAMBLE_SIZE = 6; @@ -1234,7 +1234,7 @@ class JFIFMarkerSegment extends MarkerSegment { return retval; } - private class ThumbnailReadListener + private static class ThumbnailReadListener implements IIOReadProgressListener { JPEGImageReader reader = null; ThumbnailReadListener (JPEGImageReader reader) { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java index ece1df86fcf50984241eab5c36666f7b67d498ae..a2fe287bc3dbef9dee20c63017d3873eddf07bad 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java @@ -371,8 +371,8 @@ public class JPEGMetadata extends IIOMetadata implements Cloneable { JPEGImageWriteParam jparam = null; - if ((param != null) && (param instanceof JPEGImageWriteParam)) { - jparam = (JPEGImageWriteParam) param; + if (param instanceof JPEGImageWriteParam p) { + jparam = p; if (!jparam.areTablesSet()) { jparam = null; } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOFMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOFMarkerSegment.java index 8cc1813a23e618e7a865aa96d42469b7b35811b7..e5b7e8619243839b2dcc145c7bdcef8c647ff80f 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOFMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOFMarkerSegment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -199,7 +199,7 @@ class SOFMarkerSegment extends MarkerSegment { /** * A component spec within an SOF marker segment. */ - class ComponentSpec implements Cloneable { + static class ComponentSpec implements Cloneable { int componentId; int HsamplingFactor; int VsamplingFactor; diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOSMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOSMarkerSegment.java index c8f223190fd9b8792863c342585b47298915282c..f40acdd0375821d59c6fc7d0d0242bf2fb3e049a 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOSMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/SOSMarkerSegment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,6 @@ package com.sun.imageio.plugins.jpeg; -//import javax.imageio.IIOException; import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageOutputStream; @@ -181,7 +180,7 @@ class SOSMarkerSegment extends MarkerSegment { /** * A scan component spec within an SOS marker segment. */ - class ScanComponentSpec implements Cloneable { + static class ScanComponentSpec implements Cloneable { int componentSelector; int dcHuffTable; int acHuffTable; diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java index fc731506af37c0a758735c935161525dcc89b72b..bd06a4da600de9d40f95b698bdcc393f93c4d7c6 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java @@ -669,18 +669,9 @@ public class PNGImageReader extends ImageReader { private static byte[] inflate(byte[] b) throws IOException { InputStream bais = new ByteArrayInputStream(b); - InputStream iis = new InflaterInputStream(bais); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int c; - try { - while ((c = iis.read()) != -1) { - baos.write(c); - } - } finally { - iis.close(); + try (InputStream iis = new InflaterInputStream(bais)) { + return iis.readAllBytes(); } - return baos.toByteArray(); } private void parse_zTXt_chunk(int chunkLength) throws IOException { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java index 449661b8c91800b48d8c835dc52ff946a3a58866..ce6f771ecdceb539a4bc27562fbda1167cb429d0 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java @@ -147,7 +147,7 @@ final class ChunkStream extends ImageOutputStreamImpl { } @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer (for improved performance; no need to call // super.finalize() in this case) @@ -284,7 +284,7 @@ final class IDATOutputStream extends ImageOutputStreamImpl { } @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer (for improved performance; no need to call // super.finalize() in this case) diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFBaseJPEGCompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFBaseJPEGCompressor.java index d78cb1cbdd9cc4c415cb89be01a7f9187c88e477..dba8d87816953a71c6cd094e663196dd9ffd65f2 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFBaseJPEGCompressor.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFBaseJPEGCompressor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -274,8 +274,8 @@ public abstract class TIFFBaseJPEGCompressor extends TIFFCompressor { // Initialize the ImageWriteParam. if(this.JPEGParam == null) { - if(param != null && param instanceof JPEGImageWriteParam) { - JPEGParam = (JPEGImageWriteParam)param; + if (param instanceof JPEGImageWriteParam p) { + JPEGParam = p; } else { JPEGParam = new JPEGImageWriteParam(writer != null ? @@ -435,7 +435,7 @@ public abstract class TIFFBaseJPEGCompressor extends TIFFCompressor { return compDataLength; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { super.finalize(); if(JPEGWriter != null) { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java index 1d2cff4231105a04ed3239d8f604c54f6faeac22..07186c0deb5a24e33f837bf1e83ccdfab889424a 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java @@ -2895,7 +2895,7 @@ public class TIFFImageWriter extends ImageWriter { int numThumbs = thumbnails.size(); for(int i = 0; i < numThumbs; i++) { Object thumb = thumbnails.get(i); - if(thumb == null || !(thumb instanceof BufferedImage)) { + if (!(thumb instanceof BufferedImage)) { throw new IllegalArgumentException ("thumbnails contains null references or objects other than BufferedImages!"); } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFJPEGDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFJPEGDecompressor.java index 384687f8344b104ac1d93287f7732f5927c77d8f..0b21835901b44621456e41188e3a2c8d256eb59e 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFJPEGDecompressor.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFJPEGDecompressor.java @@ -139,7 +139,7 @@ public class TIFFJPEGDecompressor extends TIFFDecompressor { JPEGReader.read(0, JPEGParam); } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { super.finalize(); JPEGReader.dispose(); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java index 67dd60f8a79a4480a8c4cf99b288f920e0cf0582..3cd89b396ccc007beec977d0db210194bc1ba53b 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFOldJPEGDecompressor.java @@ -610,7 +610,7 @@ public class TIFFOldJPEGDecompressor extends TIFFJPEGDecompressor { JPEGReader.read(0, JPEGParam); } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { super.finalize(); JPEGReader.dispose(); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java index 5676733e65f33fe13b0e342b15091ec09e512f82..ac62269b2d9b6456aeb8332a21d52fd4e6cdfb8d 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -244,8 +244,8 @@ public class WBMPImageReader extends ImageReader { } // If noTransform is necessary, read the data. - iis.read(((DataBufferByte)tile.getDataBuffer()).getData(), - 0, height*sm.getScanlineStride()); + iis.readFully(((DataBufferByte)tile.getDataBuffer()).getData(), + 0, height*sm.getScanlineStride()); processImageUpdate(bi, 0, 0, width, height, 1, 1, @@ -280,7 +280,7 @@ public class WBMPImageReader extends ImageReader { if (abortRequested()) break; - iis.read(buf, 0, len); + iis.readFully(buf, 0, len); for (int i = 0; i < destinationRegion.width; i++) { //get the bit and assign to the data buffer of the raster int v = (buf[srcPos[i]] >> srcOff[i]) & 1; diff --git a/src/java.desktop/share/classes/com/sun/imageio/stream/StreamFinalizer.java b/src/java.desktop/share/classes/com/sun/imageio/stream/StreamFinalizer.java index be1e659ee6e7784e1131d48f22a4d1846642c3c1..012d7e106459823b25b62310c06bd48296e370ea 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/stream/StreamFinalizer.java +++ b/src/java.desktop/share/classes/com/sun/imageio/stream/StreamFinalizer.java @@ -60,7 +60,7 @@ public class StreamFinalizer { this.stream = stream; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { try { stream.close(); diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java index 77c0e65dabc388856d5049d7af82874677a0e39f..78fa1e9663545bc374ed4832482fff7882b64296 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1298,7 +1298,7 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class OpaqueLabel extends JLabel { + private static class OpaqueLabel extends JLabel { public boolean isOpaque() { return true; } diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index 134cdd9a2dc6cadaa8194f5ecd671c0e3422e725..d2388fa6b04e639019d6090d0b5d7fc102e77e5d 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -583,15 +583,16 @@ class Metacity implements SynthConstants { URL url = new URL(new File(userHome).toURI().toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); // Pending: verify character encoding spec for gconf - Reader reader = new InputStreamReader(url.openStream(), - ISO_8859_1); - char[] buf = new char[1024]; StringBuilder sb = new StringBuilder(); - int n; - while ((n = reader.read(buf)) >= 0) { - sb.append(buf, 0, n); + try (InputStream in = url.openStream(); + Reader reader = new InputStreamReader(in, ISO_8859_1)) + { + char[] buf = new char[1024]; + int n; + while ((n = reader.read(buf)) >= 0) { + sb.append(buf, 0, n); + } } - reader.close(); String str = sb.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopPaneUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopPaneUI.java index 60552b8c780ba9a39f5d902782e50fe71fa91f5c..d25188dc07722c7a7981db063d8a602afbda0e5a 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopPaneUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,7 +74,7 @@ public class MotifDesktopPaneUI extends javax.swing.plaf.basic.BasicDesktopPaneU /// DragPane class //////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("serial") // Superclass is not serializable across versions - private class DragPane extends JComponent { + private static class DragPane extends JComponent { public void paint(Graphics g) { g.setColor(Color.darkGray); g.drawRect(0, 0, getWidth()-1, getHeight()-1); @@ -85,7 +85,7 @@ public class MotifDesktopPaneUI extends javax.swing.plaf.basic.BasicDesktopPaneU /// MotifDesktopManager class //////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("serial") // JDK-implementation class - private class MotifDesktopManager extends DefaultDesktopManager implements Serializable, UIResource { + private static class MotifDesktopManager extends DefaultDesktopManager implements Serializable, UIResource { JComponent dragPane; boolean usingDragPane = false; private transient JLayeredPane layeredPaneForDragPane; diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java index fcb9e724febc603974d113416c3dee647af85d0a..847fbf4117d4cda0caa99fbc1f1f00660f1bd3e1 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -787,8 +787,8 @@ public class MotifFileChooserUI extends BasicFileChooserUI { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value != null && value instanceof FileFilter) { - setText(((FileFilter)value).getDescription()); + if (value instanceof FileFilter fileFilter) { + setText(fileFilter.getDescription()); } return this; diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifMenuUI.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifMenuUI.java index eaeb5b2ab662e1aea28429a2b89bb618229a9aec..bcee2e666fa682df552602a44850b555003773bd 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifMenuUI.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -110,10 +110,10 @@ public class MotifMenuUI extends BasicMenuUI manager.clearSelectedPath(); } else { Container cnt = menu.getParent(); - if(cnt != null && cnt instanceof JMenuBar) { + if (cnt instanceof JMenuBar menuBar) { MenuElement[] me = new MenuElement[2]; - me[0]=(MenuElement)cnt; - me[1]=menu; + me[0] = menuBar; + me[1] = menu; manager.setSelectedPath(me); } } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/AbstractMidiDevice.java b/src/java.desktop/share/classes/com/sun/media/sound/AbstractMidiDevice.java index 52588387a788120a248781a38bdeb23ab8ad5005..3ba4ce2ed366b13eb76709bcf4f8eb4bd707fd3e 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/AbstractMidiDevice.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/AbstractMidiDevice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -425,7 +425,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice * close this device if discarded by the garbage collector. */ @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected final void finalize() { close(); } @@ -576,11 +576,9 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice if (midiOutReceiver == oldR) { midiOutReceiver = null; } - if (newR != null) { - if ((newR instanceof MidiOutDevice.MidiOutReceiver) + if ((newR instanceof MidiOutDevice.MidiOutReceiver newReceiver) && (midiOutReceiver == null)) { - midiOutReceiver = ((MidiOutDevice.MidiOutReceiver) newR); - } + midiOutReceiver = newReceiver; } optimizedReceiverCount = ((midiOutReceiver!=null)?1:0); diff --git a/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java b/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java index de9d124753fcaea58a47348752e20d56c4dcd7cd..32b06d47bd2965dce4375fd3a1ee9526d1527086 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,10 +48,8 @@ public final class AudioFileSoundbankReader extends SoundbankReader { @Override public Soundbank getSoundbank(URL url) throws InvalidMidiDataException, IOException { - try { - AudioInputStream ais = AudioSystem.getAudioInputStream(url); + try (AudioInputStream ais = AudioSystem.getAudioInputStream(url)) { Soundbank sbk = getSoundbank(ais); - ais.close(); return sbk; } catch (UnsupportedAudioFileException e) { return null; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java b/src/java.desktop/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java index 6dbbb3384506580f36947d8de7e8c247f5a48ccc..cb0dcf9df7e0eca50f661358c4b302446d25dcca 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -293,8 +293,7 @@ public final class AudioFloatFormatConverter extends FormatConversionProvider { format.getSampleRate(), sourceFormat.isBigEndian()); nrofchannels = targetFormat.getChannels(); Object interpolation = format.getProperty("interpolation"); - if (interpolation != null && (interpolation instanceof String)) { - String resamplerType = (String) interpolation; + if (interpolation instanceof String resamplerType) { if (resamplerType.equalsIgnoreCase("point")) this.resampler = new SoftPointResampler(); if (resamplerType.equalsIgnoreCase("linear")) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java b/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java index 3d62b3ae5a63074180f5dda2828a69978dc668e9..ba25dcacd20b92a990c5d6686adb98f340808809 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java @@ -191,22 +191,16 @@ public final class DLSSoundbank implements Soundbank { } public DLSSoundbank(URL url) throws IOException { - InputStream is = url.openStream(); - try { + try (InputStream is = url.openStream()) { readSoundbank(is); - } finally { - is.close(); } } public DLSSoundbank(File file) throws IOException { largeFormat = true; sampleFile = file; - InputStream is = new FileInputStream(file); - try { + try (InputStream is = new FileInputStream(file)) { readSoundbank(is); - } finally { - is.close(); } } @@ -875,15 +869,21 @@ public final class DLSSoundbank implements Soundbank { } public void save(String name) throws IOException { - writeSoundbank(new RIFFWriter(name, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(name, "DLS ")) { + writeSoundbank(writer); + } } public void save(File file) throws IOException { - writeSoundbank(new RIFFWriter(file, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(file, "DLS ")) { + writeSoundbank(writer); + } } public void save(OutputStream out) throws IOException { - writeSoundbank(new RIFFWriter(out, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(out, "DLS ")) { + writeSoundbank(writer); + } } private void writeSoundbank(RIFFWriter writer) throws IOException { @@ -923,8 +923,6 @@ public final class DLSSoundbank implements Soundbank { writer.seek(bak); writeInfo(writer.writeList("INFO"), info); - - writer.close(); } private void writeSample(RIFFWriter writer, DLSSample sample) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/EventDispatcher.java b/src/java.desktop/share/classes/com/sun/media/sound/EventDispatcher.java index 4b5027b12d2d598e4a998abfb712f52b67ef7058..1d66df87f1d7a7259607239fb3c30d6326933c98 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/EventDispatcher.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/EventDispatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -350,7 +350,7 @@ final class EventDispatcher implements Runnable { /** * Container for an event and a set of listeners to deliver it to. */ - private class EventInfo { + private static class EventInfo { private final Object event; private final Object[] listeners; @@ -383,7 +383,7 @@ final class EventDispatcher implements Runnable { /** * Container for a clip with its expiration time. */ - private class ClipInfo { + private static class ClipInfo { private final AutoClosingClip clip; private final long expiration; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java index e01bc10cf3912b013deb4247378caa1b2ae6c6b6..967d35d31dc35caf2720cd7214c029d9665dcf56 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,8 +51,7 @@ public final class JARSoundbankReader extends SoundbankReader { private static boolean isZIP(URL url) { boolean ok = false; try { - InputStream stream = url.openStream(); - try { + try (InputStream stream = url.openStream()) { byte[] buff = new byte[4]; ok = stream.read(buff) == 4; if (ok) { @@ -61,8 +60,6 @@ public final class JARSoundbankReader extends SoundbankReader { && buff[2] == 0x03 && buff[3] == 0x04); } - } finally { - stream.close(); } } catch (IOException e) { } @@ -81,8 +78,7 @@ public final class JARSoundbankReader extends SoundbankReader { "META-INF/services/javax.sound.midi.Soundbank"); if (stream == null) return null; - try - { + try (stream) { BufferedReader r = new BufferedReader(new InputStreamReader(stream)); String line = r.readLine(); while (line != null) { @@ -100,10 +96,6 @@ public final class JARSoundbankReader extends SoundbankReader { line = r.readLine(); } } - finally - { - stream.close(); - } if (soundbanks.size() == 0) return null; if (soundbanks.size() == 1) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java b/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java index bc2f87fe33f04797bbde82e52870dd0ea6e1d4dc..c804a0e49c225ff1a0b852c54479d9dd71d41df7 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java @@ -283,6 +283,7 @@ public final class JavaSoundAudioClip implements AudioClip, MetaEventListener, L } @Override + @SuppressWarnings("removal") protected void finalize() { if (clip != null) { diff --git a/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java b/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java index 13cbf54fe6d27708e6f45a5ac557c813f1454ccd..2476ff09bbcc7d18c816fd04b4c8670a7449c852 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java @@ -315,11 +315,13 @@ public final class ModelByteBuffer { "No file associated with this ByteBuffer!"); } - DataInputStream is = new DataInputStream(getInputStream()); - buffer = new byte[(int) capacity()]; - offset = 0; - is.readFully(buffer); - is.close(); + try (InputStream is = getInputStream(); + DataInputStream dis = new DataInputStream(is)) + { + buffer = new byte[(int) capacity()]; + offset = 0; + dis.readFully(buffer); + } } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java b/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java index 45fa29542117d0e2b470bd6327908c2a60060e50..bc8829d288c6fe7620d6190a831c2d8abf542290 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -182,18 +182,12 @@ public final class ModelByteBufferWavetable implements ModelWavetable { if (format == null) { if (buffer == null) return null; - InputStream is = buffer.getInputStream(); AudioFormat format = null; - try { + try (InputStream is = buffer.getInputStream()) { format = AudioSystem.getAudioFileFormat(is).getFormat(); } catch (Exception e) { //e.printStackTrace(); } - try { - is.close(); - } catch (IOException e) { - //e.printStackTrace(); - } return format; } return format; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/PortMixer.java b/src/java.desktop/share/classes/com/sun/media/sound/PortMixer.java index 5f2c24788d399a40953a3984248c506604ec3279..099067f3ad62ee9d54ce6ead5e42b67753e719fe 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/PortMixer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/PortMixer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -115,7 +115,7 @@ final class PortMixer extends AbstractMixer { public Line getLine(Line.Info info) throws LineUnavailableException { Line.Info fullInfo = getLineInfo(info); - if ((fullInfo != null) && (fullInfo instanceof Port.Info)) { + if (fullInfo instanceof Port.Info) { for (int i = 0; i < portInfos.length; i++) { if (fullInfo.equals(portInfos[i])) { return getPort(i); diff --git a/src/java.desktop/share/classes/com/sun/media/sound/RealTimeSequencer.java b/src/java.desktop/share/classes/com/sun/media/sound/RealTimeSequencer.java index b0239d33995553289ecf7f9f85d0e0a8b246a898..6fa6fa59c5cdf76d7909a4d8c898d67bfad949ce 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/RealTimeSequencer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/RealTimeSequencer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1024,7 +1024,7 @@ final class RealTimeSequencer extends AbstractMidiDevice } } // class Info - private class ControllerListElement { + private static class ControllerListElement { // $$jb: using an array for controllers b/c its // easier to deal with than turning all the diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java b/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java index ccade6b1a2e5abba6e3f49537b3888ea9d2e8176..831423664e69c68b14ad761a4a552be636876943 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java @@ -92,23 +92,16 @@ public final class SF2Soundbank implements Soundbank { } public SF2Soundbank(URL url) throws IOException { - - InputStream is = url.openStream(); - try { + try (InputStream is = url.openStream()) { readSoundbank(is); - } finally { - is.close(); } } public SF2Soundbank(File file) throws IOException { largeFormat = true; sampleFile = file; - InputStream is = new FileInputStream(file); - try { + try (InputStream is = new FileInputStream(file)) { readSoundbank(is); - } finally { - is.close(); } } @@ -517,22 +510,27 @@ public final class SF2Soundbank implements Soundbank { } public void save(String name) throws IOException { - writeSoundbank(new RIFFWriter(name, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(name, "sfbk")) { + writeSoundbank(writer); + } } public void save(File file) throws IOException { - writeSoundbank(new RIFFWriter(file, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(file, "sfbk")) { + writeSoundbank(writer); + } } public void save(OutputStream out) throws IOException { - writeSoundbank(new RIFFWriter(out, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(out, "sfbk")) { + writeSoundbank(writer); + } } private void writeSoundbank(RIFFWriter writer) throws IOException { writeInfo(writer.writeList("INFO")); writeSdtaChunk(writer.writeList("sdta")); writePdtaChunk(writer.writeList("pdta")); - writer.close(); } private void writeInfoStringChunk(RIFFWriter writer, String name, diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java index f603375f3b51d25de3201f16e58f72754f7e7367..34ebd3900ae443aeadeedd3f55039b396e2376b7 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,8 +48,7 @@ public final class SoftMainMixer { // A private class thats contains a ModelChannelMixer and it's private buffers. // This becomes necessary when we want to have separate delay buffers for each channel mixer. - private class SoftChannelMixerContainer - { + private static class SoftChannelMixerContainer { ModelChannelMixer mixer; SoftAudioBuffer[] buffers; } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftMixingDataLine.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftMixingDataLine.java index 99962841c8fe117078ae628b8f9a4ee2b6e73b1d..4ba5e61487489a5de915cd97d43a95990d190fef 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftMixingDataLine.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftMixingDataLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,8 +102,7 @@ public abstract class SoftMixingDataLine implements DataLine { format.getSampleRate(), sourceFormat.isBigEndian()); nrofchannels = targetFormat.getChannels(); Object interpolation = format.getProperty("interpolation"); - if (interpolation != null && (interpolation instanceof String)) { - String resamplerType = (String) interpolation; + if (interpolation instanceof String resamplerType) { if (resamplerType.equalsIgnoreCase("point")) this.resampler = new SoftPointResampler(); if (resamplerType.equalsIgnoreCase("linear")) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java index 9d73c68e6ade115101cbc63175f1f93d9cf3ad60..d614fbc10e5fb447e69e54a19d3537cf5e49c61c 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -574,25 +574,25 @@ public final class SoftSynthesizer implements AudioSynthesizer, @Override public boolean loadInstrument(Instrument instrument) { - if (instrument == null || (!(instrument instanceof ModelInstrument))) { + if (!(instrument instanceof ModelInstrument modelInstrument)) { throw new IllegalArgumentException("Unsupported instrument: " + instrument); } List instruments = new ArrayList<>(); - instruments.add((ModelInstrument)instrument); + instruments.add(modelInstrument); return loadInstruments(instruments); } @Override public void unloadInstrument(Instrument instrument) { - if (instrument == null || (!(instrument instanceof ModelInstrument))) { + if (!(instrument instanceof ModelInstrument modelInstrument)) { throw new IllegalArgumentException("Unsupported instrument: " + instrument); } if (!isOpen()) return; - String pat = patchToString(instrument.getPatch()); + String pat = patchToString(modelInstrument.getPatch()); synchronized (control_mutex) { for (SoftChannel c: channels) c.current_instrument = null; @@ -755,10 +755,8 @@ public final class SoftSynthesizer implements AudioSynthesizer, InputStream is = AccessController.doPrivileged(action); if(is == null) continue; Soundbank sbk; - try { + try (is) { sbk = MidiSystem.getSoundbank(new BufferedInputStream(is)); - } finally { - is.close(); } if (sbk != null) { defaultSoundBank = sbk; @@ -802,9 +800,8 @@ public final class SoftSynthesizer implements AudioSynthesizer, return null; }); if (out != null) { - try { + try (out) { ((SF2Soundbank) defaultSoundBank).save(out); - out.close(); } catch (final IOException ignored) { } } @@ -841,11 +838,11 @@ public final class SoftSynthesizer implements AudioSynthesizer, public boolean loadAllInstruments(Soundbank soundbank) { List instruments = new ArrayList<>(); for (Instrument ins: soundbank.getInstruments()) { - if (ins == null || !(ins instanceof ModelInstrument)) { + if (!(ins instanceof ModelInstrument modelInstrument)) { throw new IllegalArgumentException( "Unsupported instrument: " + ins); } - instruments.add((ModelInstrument)ins); + instruments.add(modelInstrument); } return loadInstruments(instruments); } @@ -870,11 +867,11 @@ public final class SoftSynthesizer implements AudioSynthesizer, List instruments = new ArrayList<>(); for (Patch patch: patchList) { Instrument ins = soundbank.getInstrument(patch); - if (ins == null || !(ins instanceof ModelInstrument)) { + if (!(ins instanceof ModelInstrument modelInstrument)) { throw new IllegalArgumentException( "Unsupported instrument: " + ins); } - instruments.add((ModelInstrument)ins); + instruments.add(modelInstrument); } return loadInstruments(instruments); } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java index e13bae6ce92d6c924be2076e64f3e05962aceaef..2dc904945714701cb833e48bbf34ff00c1b3601d 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -146,34 +146,27 @@ public final class StandardMidiFileReader extends MidiFileReader { @Override public MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException { - InputStream urlStream = url.openStream(); // throws IOException - BufferedInputStream bis = new BufferedInputStream( urlStream, bisBufferSize ); - MidiFileFormat fileFormat = null; - try { - fileFormat = getMidiFileFormat( bis ); // throws InvalidMidiDataException - } finally { - bis.close(); + try (InputStream urlStream = url.openStream(); // throws IOException + BufferedInputStream bis = new BufferedInputStream(urlStream, bisBufferSize)) + { + MidiFileFormat fileFormat = getMidiFileFormat(bis); // throws InvalidMidiDataException + return fileFormat; } - return fileFormat; } @Override public MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException { - FileInputStream fis = new FileInputStream(file); // throws IOException - BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize); - - // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length - long length = file.length(); - if (length > Integer.MAX_VALUE) { - length = MidiFileFormat.UNKNOWN_LENGTH; - } - MidiFileFormat fileFormat = null; - try { - fileFormat = getMidiFileFormatFromStream(bis, (int) length, null); - } finally { - bis.close(); + try (FileInputStream fis = new FileInputStream(file); // throws IOException + BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize)) + { + // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length + long length = file.length(); + if (length > Integer.MAX_VALUE) { + length = MidiFileFormat.UNKNOWN_LENGTH; + } + MidiFileFormat fileFormat = getMidiFileFormatFromStream(bis, (int) length, null); + return fileFormat; } - return fileFormat; } @Override @@ -204,28 +197,22 @@ public final class StandardMidiFileReader extends MidiFileReader { @Override public Sequence getSequence(URL url) throws InvalidMidiDataException, IOException { - InputStream is = url.openStream(); // throws IOException - is = new BufferedInputStream(is, bisBufferSize); - Sequence seq = null; - try { - seq = getSequence(is); - } finally { - is.close(); + try (InputStream is = url.openStream(); // throws IOException + BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize)) + { + Sequence seq = getSequence(bis); + return seq; } - return seq; } @Override public Sequence getSequence(File file) throws InvalidMidiDataException, IOException { - InputStream is = new FileInputStream(file); // throws IOException - is = new BufferedInputStream(is, bisBufferSize); - Sequence seq = null; - try { - seq = getSequence(is); - } finally { - is.close(); + try (InputStream is = new FileInputStream(file); // throws IOException + BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize)) + { + Sequence seq = getSequence(bis); + return seq; } - return seq; } } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java index a46a2e4e46783e6c0ba748d3e32cb26c5c96aac7..7d96bfaebfc3dade1f61ca449686a20e1bf72473 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java @@ -129,10 +129,10 @@ public final class StandardMidiFileWriter extends MidiFileWriter { @Override public int write(Sequence in, int type, File out) throws IOException { Objects.requireNonNull(in); - FileOutputStream fos = new FileOutputStream(out); // throws IOException - int bytesWritten = write( in, type, fos ); - fos.close(); - return bytesWritten; + try (FileOutputStream fos = new FileOutputStream(out)) { // throws IOException + int bytesWritten = write(in, type, fos); + return bytesWritten; + } } //================================================================================= diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SunFileWriter.java b/src/java.desktop/share/classes/com/sun/media/sound/SunFileWriter.java index 538c547cef511772996f114e1c1e992ff0b19ad8..1d54bcfe91c0c60294c037f43c1827b2a40071ed 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SunFileWriter.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SunFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -151,7 +151,7 @@ abstract class SunFileWriter extends AudioFileWriter { * The class is usefull for use with SequenceInputStream to prevent * closing of the source input streams. */ - final class NoCloseInputStream extends InputStream { + static final class NoCloseInputStream extends InputStream { private final InputStream in; NoCloseInputStream(InputStream in) { diff --git a/src/java.desktop/share/classes/java/awt/AWTEvent.java b/src/java.desktop/share/classes/java/awt/AWTEvent.java index 404a4fb221ba88d51c39ca2e77d76cddf461bdab..93def2fadc9fdf69cdb05bd762341f9e769424d4 100644 --- a/src/java.desktop/share/classes/java/awt/AWTEvent.java +++ b/src/java.desktop/share/classes/java/awt/AWTEvent.java @@ -355,8 +355,7 @@ public abstract class AWTEvent extends EventObject { Component comp = null; if (newSource instanceof Component) { comp = (Component)newSource; - while (comp != null && comp.peer != null && - (comp.peer instanceof LightweightPeer)) { + while (comp != null && (comp.peer instanceof LightweightPeer)) { comp = comp.parent; } } diff --git a/src/java.desktop/share/classes/java/awt/BufferCapabilities.java b/src/java.desktop/share/classes/java/awt/BufferCapabilities.java index 18c3d725b369eda5ab3c13ec54a254e8a6bc4466..8d2288023b54272084dd6072ce9ab134dfc187bd 100644 --- a/src/java.desktop/share/classes/java/awt/BufferCapabilities.java +++ b/src/java.desktop/share/classes/java/awt/BufferCapabilities.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,6 +33,7 @@ package java.awt; * @author Michael Martak * @since 1.4 */ +@SuppressWarnings("doclint:missing") public class BufferCapabilities implements Cloneable { private ImageCapabilities frontCaps; diff --git a/src/java.desktop/share/classes/java/awt/CardLayout.java b/src/java.desktop/share/classes/java/awt/CardLayout.java index f7ea3a0ba761ec405d9c9cb8ae5c0ed5a7bdfccb..d53c86a9d454ab14e9a85849256d40373c8bf335 100644 --- a/src/java.desktop/share/classes/java/awt/CardLayout.java +++ b/src/java.desktop/share/classes/java/awt/CardLayout.java @@ -74,7 +74,7 @@ public class CardLayout implements LayoutManager2, /** * A pair of component and string that represents its name. */ - class Card implements Serializable { + static class Card implements Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. diff --git a/src/java.desktop/share/classes/java/awt/Component.java b/src/java.desktop/share/classes/java/awt/Component.java index d7c2340c564d79ed4f216de9dd0bf9aac286296b..2378588b03385c21d568c613f44fa3d0aec4ccac 100644 --- a/src/java.desktop/share/classes/java/awt/Component.java +++ b/src/java.desktop/share/classes/java/awt/Component.java @@ -214,6 +214,7 @@ import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.VSYNC_ON; * @author Arthur van Hoff * @author Sami Shaio */ +@SuppressWarnings("doclint:missing") public abstract class Component implements ImageObserver, MenuContainer, Serializable { @@ -3177,17 +3178,6 @@ public abstract class Component implements ImageObserver, MenuContainer, * @since 1.0 */ public FontMetrics getFontMetrics(Font font) { - // This is an unsupported hack, but left in for a customer. - // Do not remove. - FontManager fm = FontManagerFactory.getInstance(); - if (fm instanceof SunFontManager - && ((SunFontManager) fm).usePlatformFontMetrics()) { - - if (peer != null && - !(peer instanceof LightweightPeer)) { - return peer.getFontMetrics(font); - } - } return sun.font.FontDesignMetrics.getMetrics(font); } @@ -3942,7 +3932,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * * @see sun.java2d.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer) */ - private class ProxyCapabilities extends ExtendedBufferCapabilities { + private static class ProxyCapabilities extends ExtendedBufferCapabilities { private BufferCapabilities orig; private ProxyCapabilities(BufferCapabilities orig) { super(orig.getFrontBufferCapabilities(), @@ -4955,8 +4945,8 @@ public abstract class Component implements ImageObserver, MenuContainer, // the active/passive/peered clients loose focus. if (id == FocusEvent.FOCUS_GAINED) { InputContext inputContext = getInputContext(); - if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) { - ((sun.awt.im.InputContext)inputContext).disableNativeIM(); + if (inputContext instanceof sun.awt.im.InputContext ctx) { + ctx.disableNativeIM(); } } } diff --git a/src/java.desktop/share/classes/java/awt/Container.java b/src/java.desktop/share/classes/java/awt/Container.java index 68270d35adae69e00ca9043e2d5fa06a86abdc38..5b4489f3cac037367281592b11af7f29702c7b2c 100644 --- a/src/java.desktop/share/classes/java/awt/Container.java +++ b/src/java.desktop/share/classes/java/awt/Container.java @@ -3891,18 +3891,18 @@ public class Container extends Component { public void componentAdded(ContainerEvent e) { Component c = e.getChild(); - if (c != null && c instanceof Accessible) { + if (c instanceof Accessible accessible) { AccessibleAWTContainer.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, - null, ((Accessible) c).getAccessibleContext()); + null, accessible.getAccessibleContext()); } } public void componentRemoved(ContainerEvent e) { Component c = e.getChild(); - if (c != null && c instanceof Accessible) { + if (c instanceof Accessible accessible) { AccessibleAWTContainer.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, - ((Accessible) c).getAccessibleContext(), null); + accessible.getAccessibleContext(), null); } } } diff --git a/src/java.desktop/share/classes/java/awt/Font.java b/src/java.desktop/share/classes/java/awt/Font.java index 95087864d2a0e9bc663c86228055bfbd83a68d72..020bd95b3b37c95b45dd37535491384a525f9ba3 100644 --- a/src/java.desktop/share/classes/java/awt/Font.java +++ b/src/java.desktop/share/classes/java/awt/Font.java @@ -1131,7 +1131,7 @@ public class Font implements java.io.Serializable if (tracker != null) { tracker.set(tFile, outStream); } - try { + try (outStream) { /* don't close the input stream */ byte[] buf = new byte[8192]; for (;;) { int bytesRead = fontStream.read(buf); @@ -1152,9 +1152,6 @@ public class Font implements java.io.Serializable } outStream.write(buf, 0, bytesRead); } - /* don't close the input stream */ - } finally { - outStream.close(); } /* After all references to a Font2D are dropped, the file * will be removed. To support long-lived AppContexts, diff --git a/src/java.desktop/share/classes/java/awt/Graphics.java b/src/java.desktop/share/classes/java/awt/Graphics.java index 51cdd6a88da30d1f732fb09f58d621897c5e8d28..5ed31aeadb0565e5d14cbf539843c07f0d4ac1d8 100644 --- a/src/java.desktop/share/classes/java/awt/Graphics.java +++ b/src/java.desktop/share/classes/java/awt/Graphics.java @@ -1162,17 +1162,14 @@ public abstract class Graphics { /** * Disposes of this graphics context once it is no longer referenced. * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. + * * @see #dispose */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") public void finalize() { dispose(); } diff --git a/src/java.desktop/share/classes/java/awt/MenuComponent.java b/src/java.desktop/share/classes/java/awt/MenuComponent.java index e66b5867b239825f45f8b788edbb223e9689aca9..0e7ab46cedf0391c0dfd0c1d77f4c673116db5d3 100644 --- a/src/java.desktop/share/classes/java/awt/MenuComponent.java +++ b/src/java.desktop/share/classes/java/awt/MenuComponent.java @@ -373,8 +373,7 @@ public abstract class MenuComponent implements java.io.Serializable { Toolkit.getDefaultToolkit().notifyAWTEventListeners(e); if (newEventsOnly || - (parent != null && parent instanceof MenuComponent && - ((MenuComponent)parent).newEventsOnly)) { + (parent instanceof MenuComponent mc && mc.newEventsOnly)) { if (eventEnabled(e)) { processEvent(e); } else if (e instanceof ActionEvent && parent != null) { diff --git a/src/java.desktop/share/classes/java/awt/Polygon.java b/src/java.desktop/share/classes/java/awt/Polygon.java index ed6f24a91c24998e3b6c96f111cb525b0097fa61..64f049cd1c7f7a95362c8c38c5bba02ea1dff420 100644 --- a/src/java.desktop/share/classes/java/awt/Polygon.java +++ b/src/java.desktop/share/classes/java/awt/Polygon.java @@ -575,7 +575,7 @@ public class Polygon implements Shape, java.io.Serializable { return getPathIterator(at); } - class PolygonPathIterator implements PathIterator { + static class PolygonPathIterator implements PathIterator { Polygon poly; AffineTransform transform; int index; diff --git a/src/java.desktop/share/classes/java/awt/PrintJob.java b/src/java.desktop/share/classes/java/awt/PrintJob.java index a9e2bd8bea29aa1fb9eabf8962117548349e17e8..f4ea24efd97b383dd3d054320c8db8de5259f5a4 100644 --- a/src/java.desktop/share/classes/java/awt/PrintJob.java +++ b/src/java.desktop/share/classes/java/awt/PrintJob.java @@ -85,17 +85,14 @@ public abstract class PrintJob { /** * Ends this print job once it is no longer referenced. * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. + * * @see #end */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") public void finalize() { end(); } diff --git a/src/java.desktop/share/classes/java/awt/ScrollPane.java b/src/java.desktop/share/classes/java/awt/ScrollPane.java index 05ffe6130f8c793fe27fcedea2b3c3f8c410c777..2b51bb671a34880089dcb52a29672158d8a1a156 100644 --- a/src/java.desktop/share/classes/java/awt/ScrollPane.java +++ b/src/java.desktop/share/classes/java/awt/ScrollPane.java @@ -740,8 +740,7 @@ public class ScrollPane extends Container implements Accessible { /** * Invoked when the value of the adjustable has changed. */ - class PeerFixer implements AdjustmentListener, java.io.Serializable - { + static class PeerFixer implements AdjustmentListener, java.io.Serializable { /** * Use serialVersionUID from JDK 1.1.1 for interoperability. */ diff --git a/src/java.desktop/share/classes/java/awt/Toolkit.java b/src/java.desktop/share/classes/java/awt/Toolkit.java index 354b5b3f3f3a3efb11e37473f4c115d37812882e..f3f4bcbb5c83041723e4d10ae329ab77dbcd2362 100644 --- a/src/java.desktop/share/classes/java/awt/Toolkit.java +++ b/src/java.desktop/share/classes/java/awt/Toolkit.java @@ -413,12 +413,10 @@ public abstract class Toolkit { File propsFile = new File( System.getProperty("user.home") + sep + ".accessibility.properties"); - FileInputStream in = - new FileInputStream(propsFile); - - // Inputstream has been buffered in Properties class - properties.load(in); - in.close(); + try (FileInputStream in = new FileInputStream(propsFile)) { + // Inputstream has been buffered in Properties class + properties.load(in); + } } catch (Exception e) { // Per-user accessibility properties file does not exist } @@ -431,12 +429,10 @@ public abstract class Toolkit { File propsFile = new File( System.getProperty("java.home") + sep + "conf" + sep + "accessibility.properties"); - FileInputStream in = - new FileInputStream(propsFile); - - // Inputstream has been buffered in Properties class - properties.load(in); - in.close(); + try (FileInputStream in = new FileInputStream(propsFile)) { + // Inputstream has been buffered in Properties class + properties.load(in); + } } catch (Exception e) { // System-wide accessibility properties file does // not exist; @@ -2090,7 +2086,7 @@ public abstract class Toolkit { } } - private class SelectiveAWTEventListener implements AWTEventListener { + private static class SelectiveAWTEventListener implements AWTEventListener { AWTEventListener listener; private long eventMask; // This array contains the number of times to call the eventlistener diff --git a/src/java.desktop/share/classes/java/awt/dnd/DropTarget.java b/src/java.desktop/share/classes/java/awt/dnd/DropTarget.java index a05dbdebad26f72fb3d7aa2f0bed5fa9d2dd2fe8..7ba9c9711da065fa8a1950c3663d0fd71bdfa921 100644 --- a/src/java.desktop/share/classes/java/awt/dnd/DropTarget.java +++ b/src/java.desktop/share/classes/java/awt/dnd/DropTarget.java @@ -793,7 +793,7 @@ public class DropTarget implements DropTargetListener, Serializable { */ protected void initializeAutoscrolling(Point p) { - if (component == null || !(component instanceof Autoscroll)) return; + if (!(component instanceof Autoscroll)) return; autoScroller = createDropTargetAutoScroller(component, p); } diff --git a/src/java.desktop/share/classes/java/awt/event/KeyEvent.java b/src/java.desktop/share/classes/java/awt/event/KeyEvent.java index 53b3bf9c9f1838120fb930c7788ee470fee97fb4..f416719fd2ec9498c65658e83212d9299e83eb88 100644 --- a/src/java.desktop/share/classes/java/awt/event/KeyEvent.java +++ b/src/java.desktop/share/classes/java/awt/event/KeyEvent.java @@ -151,6 +151,7 @@ import sun.awt.AWTAccessor; * * @since 1.1 */ +@SuppressWarnings("doclint:missing") public class KeyEvent extends InputEvent { /** diff --git a/src/java.desktop/share/classes/java/awt/font/NumericShaper.java b/src/java.desktop/share/classes/java/awt/font/NumericShaper.java index da21e8fce236c2a959f97e9f172c573445ff85ba..c12d63e995151708845f08b6dcb85400e6d89365 100644 --- a/src/java.desktop/share/classes/java/awt/font/NumericShaper.java +++ b/src/java.desktop/share/classes/java/awt/font/NumericShaper.java @@ -119,21 +119,20 @@ import jdk.internal.access.SharedSecrets; * * * Arabic - * {@link NumericShaper#ARABIC NumericShaper.ARABIC} + * {@link NumericShaper#ARABIC NumericShaper.ARABIC} *
      * {@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC} * {@link NumericShaper#EASTERN_ARABIC NumericShaper.EASTERN_ARABIC} - * * - * {@link NumericShaper.Range#ARABIC} + * {@link NumericShaper.Range#ARABIC} *
      * {@link NumericShaper.Range#EASTERN_ARABIC} * {@link NumericShaper.Range#EASTERN_ARABIC} * * * - * Tai Tham - * {@link NumericShaper.Range#TAI_THAM_HORA} + * Tai Tham + * {@link NumericShaper.Range#TAI_THAM_HORA} *
      * {@link NumericShaper.Range#TAI_THAM_THAM} * {@link NumericShaper.Range#TAI_THAM_THAM} @@ -1534,12 +1533,7 @@ public final class NumericShaper implements java.io.Serializable { rangeArray = rangeSet.toArray(new Range[rangeSet.size()]); if (rangeArray.length > BSEARCH_THRESHOLD) { // sort rangeArray for binary search - Arrays.sort(rangeArray, - new Comparator() { - public int compare(Range s1, Range s2) { - return s1.base > s2.base ? 1 : s1.base == s2.base ? 0 : -1; - } - }); + Arrays.sort(rangeArray, Comparator.comparingInt(s -> s.base)); } } diff --git a/src/java.desktop/share/classes/java/awt/image/AreaAveragingScaleFilter.java b/src/java.desktop/share/classes/java/awt/image/AreaAveragingScaleFilter.java index decfeb33622fdddb2f332cae245a13753f76e5ba..9e3434d4eed06d4ba13f9983c47d97f905d0afe1 100644 --- a/src/java.desktop/share/classes/java/awt/image/AreaAveragingScaleFilter.java +++ b/src/java.desktop/share/classes/java/awt/image/AreaAveragingScaleFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -105,7 +105,7 @@ public class AreaAveragingScaleFilter extends ReplicateScaleFilter { private int[] calcRow() { float origmult = ((float) srcWidth) * srcHeight; - if (outpixbuf == null || !(outpixbuf instanceof int[])) { + if (!(outpixbuf instanceof int[])) { outpixbuf = new int[destWidth]; } int[] outpix = (int[]) outpixbuf; diff --git a/src/java.desktop/share/classes/java/awt/image/ComponentSampleModel.java b/src/java.desktop/share/classes/java/awt/image/ComponentSampleModel.java index f8f6ffff56ea945c2772996e43f9c85f68dfa89a..9e0a8548eb04e9715855fc1d5886f9bbdea56a71 100644 --- a/src/java.desktop/share/classes/java/awt/image/ComponentSampleModel.java +++ b/src/java.desktop/share/classes/java/awt/image/ComponentSampleModel.java @@ -1185,11 +1185,10 @@ public class ComponentSampleModel extends SampleModel } public boolean equals(Object o) { - if ((o == null) || !(o instanceof ComponentSampleModel)) { + if (!(o instanceof ComponentSampleModel that)) { return false; } - ComponentSampleModel that = (ComponentSampleModel)o; return this.width == that.width && this.height == that.height && this.numBands == that.numBands && diff --git a/src/java.desktop/share/classes/java/awt/image/MultiPixelPackedSampleModel.java b/src/java.desktop/share/classes/java/awt/image/MultiPixelPackedSampleModel.java index 6a4aff4a39bff252a8f1f5861edcda9072a73064..dcec78fb34833e0ff4c308c6c1487922ebf58227 100644 --- a/src/java.desktop/share/classes/java/awt/image/MultiPixelPackedSampleModel.java +++ b/src/java.desktop/share/classes/java/awt/image/MultiPixelPackedSampleModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -655,11 +655,10 @@ public class MultiPixelPackedSampleModel extends SampleModel } public boolean equals(Object o) { - if ((o == null) || !(o instanceof MultiPixelPackedSampleModel)) { + if (!(o instanceof MultiPixelPackedSampleModel that)) { return false; } - MultiPixelPackedSampleModel that = (MultiPixelPackedSampleModel)o; return this.width == that.width && this.height == that.height && this.numBands == that.numBands && diff --git a/src/java.desktop/share/classes/java/awt/image/ReplicateScaleFilter.java b/src/java.desktop/share/classes/java/awt/image/ReplicateScaleFilter.java index 10ba0842772b36e36995f1b0eedcf5d2dc7db9df..a92a77e422ef2a4f6c89a1b398596c6f7f139790 100644 --- a/src/java.desktop/share/classes/java/awt/image/ReplicateScaleFilter.java +++ b/src/java.desktop/share/classes/java/awt/image/ReplicateScaleFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -126,8 +126,8 @@ public class ReplicateScaleFilter extends ImageFilter { String key = "rescale"; String val = destWidth + "x" + destHeight; Object o = p.get(key); - if (o != null && o instanceof String) { - val = ((String) o) + ", " + val; + if (o instanceof String s) { + val = s + ", " + val; } p.put(key, val); super.setProperties(p); @@ -194,8 +194,8 @@ public class ReplicateScaleFilter extends ImageFilter { int dx1 = (2 * x * destWidth + srcWidth - 1) / (2 * srcWidth); int dy1 = (2 * y * destHeight + srcHeight - 1) / (2 * srcHeight); byte[] outpix; - if (outpixbuf != null && outpixbuf instanceof byte[]) { - outpix = (byte[]) outpixbuf; + if (outpixbuf instanceof byte[] outbytes) { + outpix = outbytes; } else { outpix = new byte[destWidth]; outpixbuf = outpix; @@ -235,8 +235,8 @@ public class ReplicateScaleFilter extends ImageFilter { int dx1 = (2 * x * destWidth + srcWidth - 1) / (2 * srcWidth); int dy1 = (2 * y * destHeight + srcHeight - 1) / (2 * srcHeight); int[] outpix; - if (outpixbuf != null && outpixbuf instanceof int[]) { - outpix = (int[]) outpixbuf; + if (outpixbuf instanceof int[] outints) { + outpix = outints; } else { outpix = new int[destWidth]; outpixbuf = outpix; diff --git a/src/java.desktop/share/classes/java/awt/image/SinglePixelPackedSampleModel.java b/src/java.desktop/share/classes/java/awt/image/SinglePixelPackedSampleModel.java index dd9b898e46faab8fc08f4ef9a96d813fdcd6c718..864ed00cf7617590c71d9de8fc59c50c219d1b1e 100644 --- a/src/java.desktop/share/classes/java/awt/image/SinglePixelPackedSampleModel.java +++ b/src/java.desktop/share/classes/java/awt/image/SinglePixelPackedSampleModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -754,11 +754,10 @@ public class SinglePixelPackedSampleModel extends SampleModel } public boolean equals(Object o) { - if ((o == null) || !(o instanceof SinglePixelPackedSampleModel)) { + if (!(o instanceof SinglePixelPackedSampleModel that)) { return false; } - SinglePixelPackedSampleModel that = (SinglePixelPackedSampleModel)o; return this.width == that.width && this.height == that.height && this.numBands == that.numBands && diff --git a/src/java.desktop/share/classes/java/awt/print/Book.java b/src/java.desktop/share/classes/java/awt/print/Book.java index 3e67109b3408acf4fc840d167e99ac42a4097d9a..bc3e11d02380d5e3c2896c7d67a025f50840b978 100644 --- a/src/java.desktop/share/classes/java/awt/print/Book.java +++ b/src/java.desktop/share/classes/java/awt/print/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -174,7 +174,7 @@ public class Book implements Pageable { * The BookPage inner class describes an individual * page in a Book through a PageFormat-Printable pair. */ - private class BookPage { + private static class BookPage { /** * The size and orientation of the page. */ diff --git a/src/java.desktop/share/classes/java/beans/Beans.java b/src/java.desktop/share/classes/java/beans/Beans.java index 3be687b10e5cb901a71a2cc7ded2bc2013d077c5..dbe678b70927e881cc8446bb0e3758bd9f19c8e6 100644 --- a/src/java.desktop/share/classes/java/beans/Beans.java +++ b/src/java.desktop/share/classes/java/beans/Beans.java @@ -201,7 +201,7 @@ public class Beans { else ins = cls.getResourceAsStream(serName); if (ins != null) { - try { + try (ins) { if (cls == null) { oins = new ObjectInputStream(ins); } else { @@ -211,13 +211,9 @@ public class Beans { serialized = true; oins.close(); } catch (IOException ex) { - ins.close(); // Drop through and try opening the class. But remember // the exception in case we can't find the class either. serex = ex; - } catch (ClassNotFoundException ex) { - ins.close(); - throw ex; } } diff --git a/src/java.desktop/share/classes/java/beans/IndexedPropertyDescriptor.java b/src/java.desktop/share/classes/java/beans/IndexedPropertyDescriptor.java index ebeff6c443887a8c8322aae96e3f4b2666469ce2..b49b1cb07a950673185fe6fcfca011f347fa5a16 100644 --- a/src/java.desktop/share/classes/java/beans/IndexedPropertyDescriptor.java +++ b/src/java.desktop/share/classes/java/beans/IndexedPropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -407,8 +407,7 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { return true; } - if (obj != null && obj instanceof IndexedPropertyDescriptor) { - IndexedPropertyDescriptor other = (IndexedPropertyDescriptor)obj; + if (obj instanceof IndexedPropertyDescriptor other) { Method otherIndexedReadMethod = other.getIndexedReadMethod(); Method otherIndexedWriteMethod = other.getIndexedWriteMethod(); diff --git a/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java b/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java index 373b7ad6fff44c428e054a82840421b1cc786957..d63c446f37375e8b9af3f28fc9167998cdc99290 100644 --- a/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java +++ b/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -503,8 +503,7 @@ public class PropertyDescriptor extends FeatureDescriptor { if (this == obj) { return true; } - if (obj != null && obj instanceof PropertyDescriptor) { - PropertyDescriptor other = (PropertyDescriptor)obj; + if (obj instanceof PropertyDescriptor other) { Method otherReadMethod = other.getReadMethod(); Method otherWriteMethod = other.getWriteMethod(); diff --git a/src/java.desktop/share/classes/java/beans/XMLEncoder.java b/src/java.desktop/share/classes/java/beans/XMLEncoder.java index 7deaea30622c91d935f20f54764c6cb599fca2c4..646b777e7f7e68bef5a74cb61a2a11424bd879d6 100644 --- a/src/java.desktop/share/classes/java/beans/XMLEncoder.java +++ b/src/java.desktop/share/classes/java/beans/XMLEncoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -218,7 +218,7 @@ public class XMLEncoder extends Encoder implements AutoCloseable { private boolean preambleWritten = false; private NameGenerator nameGenerator; - private class ValueData { + private static class ValueData { public int refs = 0; public boolean marked = false; // Marked -> refs > 0 unless ref was a target. public String name = null; diff --git a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServicesSupport.java b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServicesSupport.java index 878c489e0f6fe0d84fdc55bccd4af7653466c491..d3e6c6ea87a485715b543b57846e4e0156d97290 100644 --- a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServicesSupport.java +++ b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextServicesSupport.java @@ -54,7 +54,7 @@ import java.util.TooManyListenersException; * @author Laurence P. G. Cable * @since 1.2 */ - +@SuppressWarnings("doclint:missing") public class BeanContextServicesSupport extends BeanContextSupport implements BeanContextServices { diff --git a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextSupport.java b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextSupport.java index 58e05f7708410bd013ad9b83b6ee017065da87c9..e5e53db3dfe6edfd8de96fb43eb86afc15f0b511 100644 --- a/src/java.desktop/share/classes/java/beans/beancontext/BeanContextSupport.java +++ b/src/java.desktop/share/classes/java/beans/beancontext/BeanContextSupport.java @@ -59,6 +59,7 @@ import java.util.Map; * @author Laurence P. G. Cable * @since 1.2 */ +@SuppressWarnings("doclint:missing") public class BeanContextSupport extends BeanContextChildSupport implements BeanContext, Serializable, diff --git a/src/java.desktop/share/classes/javax/imageio/ImageIO.java b/src/java.desktop/share/classes/javax/imageio/ImageIO.java index 04793b6f46498ef3888db5f925a8416b2014004d..8c62ef92b116bd11546fe61dc90740bf909170e9 100644 --- a/src/java.desktop/share/classes/javax/imageio/ImageIO.java +++ b/src/java.desktop/share/classes/javax/imageio/ImageIO.java @@ -39,8 +39,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Set; import javax.imageio.spi.IIORegistry; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderWriterSpi; @@ -1402,7 +1400,7 @@ public final class ImageIO { throw new IllegalArgumentException("input == null!"); } - InputStream istream = null; + InputStream istream; try { istream = input.openStream(); } catch (IOException e) { @@ -1418,13 +1416,11 @@ public final class ImageIO { throw new IIOException("Can't create an ImageInputStream!"); } BufferedImage bi; - try { + try (istream) { bi = read(stream); if (bi == null) { stream.close(); } - } finally { - istream.close(); } return bi; } @@ -1466,11 +1462,10 @@ public final class ImageIO { ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(stream, true, true); BufferedImage bi; - try { + try (stream) { bi = reader.read(0, param); } finally { reader.dispose(); - stream.close(); } return bi; } @@ -1552,10 +1547,8 @@ public final class ImageIO { if (stream == null) { throw new IIOException("Can't create an ImageOutputStream!"); } - try { + try (stream) { return doWrite(im, writer, stream); - } finally { - stream.close(); } } @@ -1592,10 +1585,8 @@ public final class ImageIO { if (stream == null) { throw new IIOException("Can't create an ImageOutputStream!"); } - try { + try (stream) { return doWrite(im, getWriter(im, formatName), stream); - } finally { - stream.close(); } } diff --git a/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java b/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java index e50958f17572f95658965e969fcdb18777290ccc..e328d7499bcd28be7794db995a9c1cfc5116a9d0 100644 --- a/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java +++ b/src/java.desktop/share/classes/javax/imageio/ImageTypeSpecifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -328,14 +328,10 @@ public class ImageTypeSpecifier { } public boolean equals(Object o) { - if ((o == null) || - !(o instanceof ImageTypeSpecifier.Interleaved)) { + if (!(o instanceof Interleaved that)) { return false; } - ImageTypeSpecifier.Interleaved that = - (ImageTypeSpecifier.Interleaved)o; - if ((!(this.colorSpace.equals(that.colorSpace))) || (this.dataType != that.dataType) || (this.hasAlpha != that.hasAlpha) || @@ -472,14 +468,10 @@ public class ImageTypeSpecifier { } public boolean equals(Object o) { - if ((o == null) || - !(o instanceof ImageTypeSpecifier.Banded)) { + if (!(o instanceof Banded that)) { return false; } - ImageTypeSpecifier.Banded that = - (ImageTypeSpecifier.Banded)o; - if ((!(this.colorSpace.equals(that.colorSpace))) || (this.dataType != that.dataType) || (this.hasAlpha != that.hasAlpha) || @@ -1095,11 +1087,10 @@ public class ImageTypeSpecifier { * {@code ImageTypeSpecifier}. */ public boolean equals(Object o) { - if ((o == null) || !(o instanceof ImageTypeSpecifier)) { + if (!(o instanceof ImageTypeSpecifier that)) { return false; } - ImageTypeSpecifier that = (ImageTypeSpecifier)o; return (colorModel.equals(that.colorModel)) && (sampleModel.equals(that.sampleModel)); } diff --git a/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java b/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java index c9afb13a79dc83a10a3c3a2e1913a9ccc46307f6..8b5de4089efb912f3fc255a6361651db6fd075d0 100644 --- a/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java +++ b/src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,7 @@ package javax.imageio.metadata; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -92,7 +90,7 @@ public abstract class IIOMetadataFormatImpl implements IIOMetadataFormat { // Element name (String) -> Element private HashMap elementMap = new HashMap<>(); - class Element { + static class Element { String elementName; int childPolicy; @@ -113,7 +111,7 @@ public abstract class IIOMetadataFormatImpl implements IIOMetadataFormat { ObjectValue objectValue; } - class Attribute { + static class Attribute { String attrName; int valueType = VALUE_ARBITRARY; @@ -133,7 +131,7 @@ public abstract class IIOMetadataFormatImpl implements IIOMetadataFormat { int listMaxLength; } - class ObjectValue { + static class ObjectValue { int valueType = VALUE_NONE; // ? extends T So that ObjectValue can take Class Class classType = null; diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/BaselineTIFFTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/BaselineTIFFTagSet.java index 0932b4c2c89e2e2c005f4343ee0f5e64838661ad..340fe2aee77f897aadea4708825ed1acec83f93e 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/BaselineTIFFTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/BaselineTIFFTagSet.java @@ -2173,7 +2173,7 @@ public final class BaselineTIFFTagSet extends TIFFTagSet { * * @return a {@code BaselineTIFFTagSet} instance. */ - public synchronized static BaselineTIFFTagSet getInstance() { + public static synchronized BaselineTIFFTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new BaselineTIFFTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifGPSTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifGPSTagSet.java index 9b67e609fc3fb0212bcfcb5b54c54e7de810e706..503ad4b6d68116eab8779dec2e1d6b97dfa4050f 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifGPSTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifGPSTagSet.java @@ -713,7 +713,7 @@ public final class ExifGPSTagSet extends TIFFTagSet { * * @return an {@code ExifGPSTagSet} instance. */ - public synchronized static ExifGPSTagSet getInstance() { + public static synchronized ExifGPSTagSet getInstance() { if (theInstance == null) { theInstance = new ExifGPSTagSet(); } diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifInteroperabilityTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifInteroperabilityTagSet.java index 140b66779bd78cb6f1e26363238b90353ed5d57c..ab9c85c81e474059f2b3f35d9a98672416fc5f54 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifInteroperabilityTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifInteroperabilityTagSet.java @@ -92,7 +92,7 @@ public final class ExifInteroperabilityTagSet extends TIFFTagSet { * * @return the {@code ExifInteroperabilityTagSet} instance. */ - public synchronized static ExifInteroperabilityTagSet getInstance() { + public static synchronized ExifInteroperabilityTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new ExifInteroperabilityTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifParentTIFFTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifParentTIFFTagSet.java index 194416b4a81bf106da46f832dd6fcf0d6f6ec052..3a546b417ba640963fb40a9011317dbede85b612 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifParentTIFFTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifParentTIFFTagSet.java @@ -84,7 +84,7 @@ public final class ExifParentTIFFTagSet extends TIFFTagSet { * * @return an {@code ExifParentTIFFTagSet} instance. */ - public synchronized static ExifParentTIFFTagSet getInstance() { + public static synchronized ExifParentTIFFTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new ExifParentTIFFTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifTIFFTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifTIFFTagSet.java index 3b274b8d97833c0aefe166401275b4f6dba99986..443465ec59c6c083ae320e04e140023ff0844639 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifTIFFTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/ExifTIFFTagSet.java @@ -1992,7 +1992,7 @@ public final class ExifTIFFTagSet extends TIFFTagSet { * * @return an {@code ExifTIFFTagSet} instance. */ - public synchronized static ExifTIFFTagSet getInstance() { + public static synchronized ExifTIFFTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new ExifTIFFTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/FaxTIFFTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/FaxTIFFTagSet.java index 078884355887e57f7942162c9eeb5c44888c2f99..f31663bfa6382772d97c166910364c607ab3d1d2 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/FaxTIFFTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/FaxTIFFTagSet.java @@ -135,7 +135,7 @@ public final class FaxTIFFTagSet extends TIFFTagSet { * * @return a {@code FaxTIFFTagSet} instance. */ - public synchronized static FaxTIFFTagSet getInstance() { + public static synchronized FaxTIFFTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new FaxTIFFTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java index 18962ed3816140a698238c8bbceae4762c833095..214a17df6e21d7c5b0a36091e0f05828ca15346d 100644 --- a/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java +++ b/src/java.desktop/share/classes/javax/imageio/plugins/tiff/GeoTIFFTagSet.java @@ -138,7 +138,7 @@ public final class GeoTIFFTagSet extends TIFFTagSet { * * @return a {@code GeoTIFFTagSet} instance. */ - public synchronized static GeoTIFFTagSet getInstance() { + public static synchronized GeoTIFFTagSet getInstance() { if (theInstance == null) { initTags(); theInstance = new GeoTIFFTagSet(); diff --git a/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java b/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java index 741ca55c5010efa9dbae99e6ec7c6e7b19387a72..4a43ca8133a5b7d14f12d270021441896dca8c21 100644 --- a/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java +++ b/src/java.desktop/share/classes/javax/imageio/spi/ServiceRegistry.java @@ -680,16 +680,12 @@ public class ServiceRegistry { * @exception Throwable if an error occurs during superclass * finalization. * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") public void finalize() throws Throwable { deregisterAll(); super.finalize(); @@ -842,7 +838,7 @@ class SubRegistry { accMap.clear(); } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public synchronized void finalize() { clear(); } diff --git a/src/java.desktop/share/classes/javax/imageio/stream/FileCacheImageInputStream.java b/src/java.desktop/share/classes/javax/imageio/stream/FileCacheImageInputStream.java index e597490016123cfb7de02b451ca375e131d96c9f..6bf14838b7fc42d0e4ee853e9ff9f710033ec228 100644 --- a/src/java.desktop/share/classes/javax/imageio/stream/FileCacheImageInputStream.java +++ b/src/java.desktop/share/classes/javax/imageio/stream/FileCacheImageInputStream.java @@ -261,16 +261,12 @@ public class FileCacheImageInputStream extends ImageInputStreamImpl { /** * {@inheritDoc} * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer: for performance reasons we instead use the // Disposer mechanism for ensuring that the underlying diff --git a/src/java.desktop/share/classes/javax/imageio/stream/FileImageInputStream.java b/src/java.desktop/share/classes/javax/imageio/stream/FileImageInputStream.java index 7ecc28767a0284881d37335ea094e0548604ed61..b1cce6fae4cc64bd98db88d535e8cb088b9478f6 100644 --- a/src/java.desktop/share/classes/javax/imageio/stream/FileImageInputStream.java +++ b/src/java.desktop/share/classes/javax/imageio/stream/FileImageInputStream.java @@ -156,16 +156,12 @@ public class FileImageInputStream extends ImageInputStreamImpl { /** * {@inheritDoc} * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer: for performance reasons we instead use the // Disposer mechanism for ensuring that the underlying diff --git a/src/java.desktop/share/classes/javax/imageio/stream/FileImageOutputStream.java b/src/java.desktop/share/classes/javax/imageio/stream/FileImageOutputStream.java index e75c40396d8157a1957f75e27ffd887f06c006a7..715b43f40fb764aa4b3df57941cef1959c7029d6 100644 --- a/src/java.desktop/share/classes/javax/imageio/stream/FileImageOutputStream.java +++ b/src/java.desktop/share/classes/javax/imageio/stream/FileImageOutputStream.java @@ -164,16 +164,12 @@ public class FileImageOutputStream extends ImageOutputStreamImpl { /** * {@inheritDoc} * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer: for performance reasons we instead use the // Disposer mechanism for ensuring that the underlying diff --git a/src/java.desktop/share/classes/javax/imageio/stream/ImageInputStreamImpl.java b/src/java.desktop/share/classes/javax/imageio/stream/ImageInputStreamImpl.java index c7cdc47cdafc3698312db86ea154b65573f78a68..053bbf7491826e852d0b0f466f68edf37841e0f7 100644 --- a/src/java.desktop/share/classes/javax/imageio/stream/ImageInputStreamImpl.java +++ b/src/java.desktop/share/classes/javax/imageio/stream/ImageInputStreamImpl.java @@ -868,16 +868,12 @@ public abstract class ImageInputStreamImpl implements ImageInputStream { * @exception Throwable if an error occurs during superclass * finalization. * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") protected void finalize() throws Throwable { if (!isClosed) { try { diff --git a/src/java.desktop/share/classes/javax/imageio/stream/MemoryCacheImageInputStream.java b/src/java.desktop/share/classes/javax/imageio/stream/MemoryCacheImageInputStream.java index 4fcb0f40b8171a3e136bc30bfe5fc6abf0670af8..44b9d8cd5fbf9c0b3ce2130da8ed12b1bb9dd9f8 100644 --- a/src/java.desktop/share/classes/javax/imageio/stream/MemoryCacheImageInputStream.java +++ b/src/java.desktop/share/classes/javax/imageio/stream/MemoryCacheImageInputStream.java @@ -179,16 +179,12 @@ public class MemoryCacheImageInputStream extends ImageInputStreamImpl { /** * {@inheritDoc} * - * @deprecated The {@code finalize} method has been deprecated. - * Subclasses that override {@code finalize} in order to perform cleanup - * should be modified to use alternative cleanup mechanisms and - * to remove the overriding {@code finalize} method. - * When overriding the {@code finalize} method, its implementation must explicitly - * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. - * See the specification for {@link Object#finalize()} for further - * information about migration options. + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for background information and details + * about migration options. */ - @Deprecated(since="9") + @Deprecated(since="9", forRemoval=true) + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Empty finalizer: for performance reasons we instead use the // Disposer mechanism for ensuring that the underlying diff --git a/src/java.desktop/share/classes/javax/print/DocFlavor.java b/src/java.desktop/share/classes/javax/print/DocFlavor.java index 557a1799a241fe64f9fc37f4bada5761b59945b1..0e04dfb471c86206dbd2550b879bf0d41dae4f91 100644 --- a/src/java.desktop/share/classes/javax/print/DocFlavor.java +++ b/src/java.desktop/share/classes/javax/print/DocFlavor.java @@ -537,10 +537,8 @@ public class DocFlavor implements Serializable, Cloneable { * {@code false} otherwise */ public boolean equals(Object obj) { - return - obj != null && - obj instanceof DocFlavor && - getStringValue().equals (((DocFlavor) obj).getStringValue()); + return obj instanceof DocFlavor other && + getStringValue().equals(other.getStringValue()); } /** diff --git a/src/java.desktop/share/classes/javax/print/MimeType.java b/src/java.desktop/share/classes/javax/print/MimeType.java index b2967428a2a6aebcfdc1799937ca124851f25cb4..4e3acdb99fa6c05b7c73ded164799428ae2a00ac 100644 --- a/src/java.desktop/share/classes/javax/print/MimeType.java +++ b/src/java.desktop/share/classes/javax/print/MimeType.java @@ -141,10 +141,9 @@ class MimeType implements Serializable, Cloneable { throw new UnsupportedOperationException(); } public boolean equals(Object o) { - return (o != null && - o instanceof Map.Entry && - getKey().equals (((Map.Entry) o).getKey()) && - getValue().equals(((Map.Entry) o).getValue())); + return o instanceof Map.Entry entry && + getKey().equals(entry.getKey()) && + getValue().equals(entry.getValue()); } public int hashCode() { return getKey().hashCode() ^ getValue().hashCode(); @@ -290,9 +289,8 @@ class MimeType implements Serializable, Cloneable { * {@code false} otherwise */ public boolean equals (Object obj) { - return(obj != null && - obj instanceof MimeType && - getStringValue().equals(((MimeType) obj).getStringValue())); + return obj instanceof MimeType mimeType && + getStringValue().equals(mimeType.getStringValue()); } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/DateTimeSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/DateTimeSyntax.java index 769177ed82b0aa8828c50b295085ee496dfb7029..2f0eafb9f791899044c8c0e4f1f29c95bf6b67e8 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/DateTimeSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/DateTimeSyntax.java @@ -115,9 +115,8 @@ public abstract class DateTimeSyntax implements Serializable, Cloneable { * attribute, {@code false} otherwise */ public boolean equals(Object object) { - return (object != null && - object instanceof DateTimeSyntax && - value.equals(((DateTimeSyntax) object).value)); + return object instanceof DateTimeSyntax other && + value.equals(other.value); } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/HashAttributeSet.java b/src/java.desktop/share/classes/javax/print/attribute/HashAttributeSet.java index aaeef91954c6437d2b55f8e774d48868f950434b..4ad4c8634aa0e6ad387865a8f74b41a54541d1c7 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/HashAttributeSet.java +++ b/src/java.desktop/share/classes/javax/print/attribute/HashAttributeSet.java @@ -345,10 +345,8 @@ public class HashAttributeSet implements AttributeSet, Serializable { * value */ public boolean containsValue(Attribute attribute) { - return - attribute != null && - attribute instanceof Attribute && - attribute.equals(attrMap.get(attribute.getCategory())); + return attribute != null && + attribute.equals(attrMap.get(attribute.getCategory())); } /** @@ -441,11 +439,10 @@ public class HashAttributeSet implements AttributeSet, Serializable { * set */ public boolean equals(Object object) { - if (object == null || !(object instanceof AttributeSet)) { + if (!(object instanceof AttributeSet aset)) { return false; } - AttributeSet aset = (AttributeSet)object; if (aset.size() != size()) { return false; } diff --git a/src/java.desktop/share/classes/javax/print/attribute/IntegerSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/IntegerSyntax.java index c67eff7ebb82bc1054504c91d4d75ddef0b524af..f6dbee3aa5a62aceecfc92cb36f9ec8d2d6f20d7 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/IntegerSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/IntegerSyntax.java @@ -108,9 +108,8 @@ public abstract class IntegerSyntax implements Serializable, Cloneable { * attribute, {@code false} otherwise */ public boolean equals(Object object) { - - return (object != null && object instanceof IntegerSyntax && - value == ((IntegerSyntax) object).value); + return object instanceof IntegerSyntax other && + value == other.value; } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/ResolutionSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/ResolutionSyntax.java index d3eb94956a9bd33d1905cd8b3cf784e317edf4c8..8ffae65a0d239a39743072bfaaa8cfab674a1e40 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/ResolutionSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/ResolutionSyntax.java @@ -267,13 +267,9 @@ public abstract class ResolutionSyntax implements Serializable, Cloneable { * attribute, {@code false} otherwise */ public boolean equals(Object object) { - - return(object != null && - object instanceof ResolutionSyntax && - this.crossFeedResolution == - ((ResolutionSyntax) object).crossFeedResolution && - this.feedResolution == - ((ResolutionSyntax) object).feedResolution); + return object instanceof ResolutionSyntax other && + this.crossFeedResolution == other.crossFeedResolution && + this.feedResolution == other.feedResolution; } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/SetOfIntegerSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/SetOfIntegerSyntax.java index 0fac430e29aa0d511443c236b2ffe6fb24b55aa8..6df67ef90ca4df25f13da6279054321c1a0ff800 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/SetOfIntegerSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/SetOfIntegerSyntax.java @@ -483,9 +483,9 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { * set-of-integer attribute, {@code false} otherwise */ public boolean equals(Object object) { - if (object != null && object instanceof SetOfIntegerSyntax) { + if (object instanceof SetOfIntegerSyntax other) { int[][] myMembers = this.members; - int[][] otherMembers = ((SetOfIntegerSyntax) object).members; + int[][] otherMembers = other.members; int m = myMembers.length; int n = otherMembers.length; if (m == n) { diff --git a/src/java.desktop/share/classes/javax/print/attribute/Size2DSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/Size2DSyntax.java index 8adc51b8ff5faad4106b97564e2cc0e8a01e1f70..9ff772bc30d6925b73d75d92296c6b56e6055d4f 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/Size2DSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/Size2DSyntax.java @@ -264,10 +264,9 @@ public abstract class Size2DSyntax implements Serializable, Cloneable { * two-dimensional size attribute, {@code false} otherwise */ public boolean equals(Object object) { - return(object != null && - object instanceof Size2DSyntax && - this.x == ((Size2DSyntax) object).x && - this.y == ((Size2DSyntax) object).y); + return object instanceof Size2DSyntax size2DSyntax && + this.x == size2DSyntax.x && + this.y == size2DSyntax.y; } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/TextSyntax.java b/src/java.desktop/share/classes/javax/print/attribute/TextSyntax.java index 40fd3171e7a7e4c295cce3543b6ef5b0eed11548..9a343bc8af2c7fa836c8b068247d2c68ec31f05f 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/TextSyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/TextSyntax.java @@ -132,10 +132,9 @@ public abstract class TextSyntax implements Serializable, Cloneable { * attribute, {@code false} otherwise */ public boolean equals(Object object) { - return(object != null && - object instanceof TextSyntax && - this.value.equals (((TextSyntax) object).value) && - this.locale.equals (((TextSyntax) object).locale)); + return object instanceof TextSyntax other && + this.value.equals(other.value) && + this.locale.equals(other.locale); } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/URISyntax.java b/src/java.desktop/share/classes/javax/print/attribute/URISyntax.java index e5f4f57f138c6a7ddc0c66780bb58d1d37cb3eba..10545df71fd4430ed320e0896582f75f0612da22 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/URISyntax.java +++ b/src/java.desktop/share/classes/javax/print/attribute/URISyntax.java @@ -101,9 +101,8 @@ public abstract class URISyntax implements Serializable, Cloneable { * attribute, {@code false} otherwise */ public boolean equals(Object object) { - return(object != null && - object instanceof URISyntax && - this.uri.equals (((URISyntax) object).uri)); + return object instanceof URISyntax other && + this.uri.equals(other.uri); } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/Media.java b/src/java.desktop/share/classes/javax/print/attribute/standard/Media.java index 6e42547d95525aabc0cd5e0ef0a11f22f82ea703..6b62f1dbecdc042690d3e673ef2975d05e8cf337 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/Media.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/Media.java @@ -90,9 +90,9 @@ public abstract class Media extends EnumSyntax * attribute, {@code false} otherwise */ public boolean equals(Object object) { - return(object != null && object instanceof Media && - object.getClass() == this.getClass() && - ((Media)object).getValue() == this.getValue()); + return object instanceof Media other && + object.getClass() == this.getClass() && + other.getValue() == this.getValue(); } /** diff --git a/src/java.desktop/share/classes/javax/print/attribute/standard/PrinterStateReasons.java b/src/java.desktop/share/classes/javax/print/attribute/standard/PrinterStateReasons.java index ecc4d3c44d7cfd0faf799bcbf2a46d49d64629b8..8e46b1456512461f949b7b68966f50277c6735ef 100644 --- a/src/java.desktop/share/classes/javax/print/attribute/standard/PrinterStateReasons.java +++ b/src/java.desktop/share/classes/javax/print/attribute/standard/PrinterStateReasons.java @@ -227,7 +227,7 @@ public final class PrinterStateReasons return new PrinterStateReasonSet (severity, entrySet()); } - private class PrinterStateReasonSet + private static class PrinterStateReasonSet extends AbstractSet { private Severity mySeverity; @@ -254,7 +254,7 @@ public final class PrinterStateReasons } } - private class PrinterStateReasonSetIterator implements Iterator { + private static class PrinterStateReasonSetIterator implements Iterator { private Severity mySeverity; private Iterator> myIterator; private Map.Entry myEntry; diff --git a/src/java.desktop/share/classes/javax/sound/sampled/AudioInputStream.java b/src/java.desktop/share/classes/javax/sound/sampled/AudioInputStream.java index 6061ec94c6a13bb54782ddc05b8765c114c425cd..7a5a10e657a6ce03c5ef7cde8e2cec7b98a9ba14 100644 --- a/src/java.desktop/share/classes/javax/sound/sampled/AudioInputStream.java +++ b/src/java.desktop/share/classes/javax/sound/sampled/AudioInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -474,7 +474,7 @@ public class AudioInputStream extends InputStream { /** * Private inner class that makes a TargetDataLine look like an InputStream. */ - private class TargetDataLineInputStream extends InputStream { + private static class TargetDataLineInputStream extends InputStream { /** * The TargetDataLine on which this TargetDataLineInputStream is based. diff --git a/src/java.desktop/share/classes/javax/swing/AbstractAction.java b/src/java.desktop/share/classes/javax/swing/AbstractAction.java index d56821c0424d859cb06c45c1b938c500ea35399f..6a22a985d69b7e477ddc4e1b9524eff4f85d2318 100644 --- a/src/java.desktop/share/classes/javax/swing/AbstractAction.java +++ b/src/java.desktop/share/classes/javax/swing/AbstractAction.java @@ -193,7 +193,7 @@ public abstract class AbstractAction implements Action, Cloneable, Serializable // to change enabled, it would be possible for stack // overflow in the case where a developer implemented setEnabled // in terms of putValue. - if (newValue == null || !(newValue instanceof Boolean)) { + if (!(newValue instanceof Boolean)) { newValue = false; } oldValue = enabled; diff --git a/src/java.desktop/share/classes/javax/swing/AbstractButton.java b/src/java.desktop/share/classes/javax/swing/AbstractButton.java index 56ff09c2c4907beac8ea3489f281fe8e006f1bec..8a2936cd4990e1dc2965c2f729ccba751195937f 100644 --- a/src/java.desktop/share/classes/javax/swing/AbstractButton.java +++ b/src/java.desktop/share/classes/javax/swing/AbstractButton.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -2394,8 +2394,8 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl if (defaultIcon instanceof Accessible) { AccessibleContext ac = ((Accessible)defaultIcon).getAccessibleContext(); - if (ac != null && ac instanceof AccessibleIcon) { - return new AccessibleIcon[] { (AccessibleIcon)ac }; + if (ac instanceof AccessibleIcon ai) { + return new AccessibleIcon[] { ai }; } } return null; @@ -2441,8 +2441,8 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl if (!relationSet.contains(AccessibleRelation.MEMBER_OF)) { // get the members of the button group if one exists ButtonModel model = getModel(); - if (model != null && model instanceof DefaultButtonModel) { - ButtonGroup group = ((DefaultButtonModel)model).getGroup(); + if (model instanceof DefaultButtonModel defaultModel) { + ButtonGroup group = defaultModel.getGroup(); if (group != null) { // set the target of the MEMBER_OF relation to be // the members of the button group. diff --git a/src/java.desktop/share/classes/javax/swing/DebugGraphics.java b/src/java.desktop/share/classes/javax/swing/DebugGraphics.java index 5cd8c69dfacf0c35517b11aaf26219a430d9f8b5..102f7e35dd5a2735999fb601db80578c93bb68f9 100644 --- a/src/java.desktop/share/classes/javax/swing/DebugGraphics.java +++ b/src/java.desktop/share/classes/javax/swing/DebugGraphics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1417,8 +1417,8 @@ public class DebugGraphics extends Graphics { Container container = (Container)component; int debugOptions = 0; - while (container != null && (container instanceof JComponent)) { - debugOptions |= info.getDebugOptions((JComponent)container); + while (container instanceof JComponent jc) { + debugOptions |= info.getDebugOptions(jc); container = container.getParent(); } diff --git a/src/java.desktop/share/classes/javax/swing/DefaultListSelectionModel.java b/src/java.desktop/share/classes/javax/swing/DefaultListSelectionModel.java index 25e47c8b90b29fd23c8a41ed91534c97885a87ab..1924df3123e2ad703da27accfc6e230cbe0b4c74 100644 --- a/src/java.desktop/share/classes/javax/swing/DefaultListSelectionModel.java +++ b/src/java.desktop/share/classes/javax/swing/DefaultListSelectionModel.java @@ -50,7 +50,8 @@ import javax.swing.event.*; * @see ListSelectionModel * @since 1.2 */ -@SuppressWarnings("serial") // Same-version serialization only +@SuppressWarnings({"serial", // Same-version serialization only + "doclint:missing"}) public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable { private static final int MIN = -1; diff --git a/src/java.desktop/share/classes/javax/swing/GroupLayout.java b/src/java.desktop/share/classes/javax/swing/GroupLayout.java index 61ed76bd5362a44df48cdfddc4471ea02d2b9864..3f85678361e5b3b1cc8237a1c552980ecdfc09ed 100644 --- a/src/java.desktop/share/classes/javax/swing/GroupLayout.java +++ b/src/java.desktop/share/classes/javax/swing/GroupLayout.java @@ -1267,7 +1267,7 @@ public class GroupLayout implements LayoutManager2 { * min/max/pref. If the min/pref/max has internally changes, or needs * to be updated you must invoke clear. */ - private abstract class Spring { + private abstract static class Spring { private int size; private int min; private int max; @@ -3167,7 +3167,7 @@ public class GroupLayout implements LayoutManager2 { /** * Spring represented a certain amount of space. */ - private class GapSpring extends Spring { + private static class GapSpring extends Spring { private final int min; private final int pref; private final int max; diff --git a/src/java.desktop/share/classes/javax/swing/JApplet.java b/src/java.desktop/share/classes/javax/swing/JApplet.java index d15fac15f66ccabb6f0488aebc5367d13f54e68b..a1ba64dcf0dd76ef00a15e0583a0e9776baa427c 100644 --- a/src/java.desktop/share/classes/javax/swing/JApplet.java +++ b/src/java.desktop/share/classes/javax/swing/JApplet.java @@ -99,7 +99,8 @@ import javax.accessibility.AccessibleContext; @Deprecated(since = "9", forRemoval = true) @JavaBean(defaultProperty = "JMenuBar", description = "Swing's Applet subclass.") @SwingContainer(delegate = "getContentPane") -@SuppressWarnings({"serial", "removal"}) // Same-version serialization only +@SuppressWarnings({"serial", "removal", // Same-version serialization only + "doclint:missing"}) public class JApplet extends Applet implements Accessible, RootPaneContainer, TransferHandler.HasGetTransferHandler diff --git a/src/java.desktop/share/classes/javax/swing/JComboBox.java b/src/java.desktop/share/classes/javax/swing/JComboBox.java index 13fc319f1a7b2df6103465199c91001c3d5bfc65..fdbbdc686575f26e01f8e0cce1c4ab61071bf07b 100644 --- a/src/java.desktop/share/classes/javax/swing/JComboBox.java +++ b/src/java.desktop/share/classes/javax/swing/JComboBox.java @@ -1555,7 +1555,7 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { int selectionForKey(char aKey,ComboBoxModel aModel); } - class DefaultKeySelectionManager implements KeySelectionManager, Serializable { + static class DefaultKeySelectionManager implements KeySelectionManager, Serializable { public int selectionForKey(char aKey,ComboBoxModel aModel) { int i,c; int currentSelection = -1; @@ -2000,11 +2000,10 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { // Get the popup Accessible a = JComboBox.this.getUI().getAccessibleChild(JComboBox.this, 0); - if (a != null && - a instanceof javax.swing.plaf.basic.ComboPopup) { + if (a instanceof javax.swing.plaf.basic.ComboPopup popup) { // get the popup list - JList list = ((javax.swing.plaf.basic.ComboPopup)a).getList(); + JList list = popup.getList(); // return the i-th selection in the popup list AccessibleContext ac = list.getAccessibleContext(); diff --git a/src/java.desktop/share/classes/javax/swing/JComponent.java b/src/java.desktop/share/classes/javax/swing/JComponent.java index d028c00b98b005f48f60481ae513375bace083e6..c572a12ebb465e801d948c43fea0a45cf050efa5 100644 --- a/src/java.desktop/share/classes/javax/swing/JComponent.java +++ b/src/java.desktop/share/classes/javax/swing/JComponent.java @@ -878,8 +878,7 @@ public abstract class JComponent extends Container implements Serializable, } // If we are only to paint to a specific child, determine // its index. - if (paintingChild != null && - (paintingChild instanceof JComponent) && + if ((paintingChild instanceof JComponent) && paintingChild.isOpaque()) { for (; i >= 0; i--) { if (getComponent(i) == paintingChild){ @@ -3448,7 +3447,7 @@ public abstract class JComponent extends Container implements Serializable, * ActionListeners that are * added via registerKeyboardAction. */ - final class ActionStandin implements Action { + static final class ActionStandin implements Action { private final ActionListener actionListener; private final String command; // This will be non-null if actionListener is an Action. @@ -3636,20 +3635,18 @@ public abstract class JComponent extends Container implements Serializable, boolean temporary, boolean focusedWindowChangeAllowed, FocusEvent.Cause cause) { - if ((to == null) || !(to instanceof JComponent)) { + if (!(to instanceof JComponent target)) { return true; } - if ((from == null) || !(from instanceof JComponent)) { + if (!(from instanceof JComponent jFocusOwner)) { return true; } - JComponent target = (JComponent) to; if (!target.getVerifyInputWhenFocusTarget()) { return true; } - JComponent jFocusOwner = (JComponent)from; InputVerifier iv = jFocusOwner.getInputVerifier(); if (iv == null) { @@ -3774,7 +3771,7 @@ public abstract class JComponent extends Container implements Serializable, protected AccessibleContainerHandler() {} public void componentAdded(ContainerEvent e) { Component c = e.getChild(); - if (c != null && c instanceof Accessible) { + if (c instanceof Accessible) { AccessibleJComponent.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, null, c.getAccessibleContext()); @@ -3782,7 +3779,7 @@ public abstract class JComponent extends Container implements Serializable, } public void componentRemoved(ContainerEvent e) { Component c = e.getChild(); - if (c != null && c instanceof Accessible) { + if (c instanceof Accessible) { AccessibleJComponent.this.firePropertyChange( AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, c.getAccessibleContext(), null); @@ -5501,8 +5498,7 @@ public abstract class JComponent extends Container implements Serializable, * @see java.io.ObjectInputStream#registerValidation * @see SwingUtilities#updateComponentTreeUI */ - private class ReadObjectCallback implements ObjectInputValidation - { + private static class ReadObjectCallback implements ObjectInputValidation { private final Vector roots = new Vector(1); private final ObjectInputStream inputStream; diff --git a/src/java.desktop/share/classes/javax/swing/JDialog.java b/src/java.desktop/share/classes/javax/swing/JDialog.java index 522c8dae0a005635d7c3c1c6c389d02a9775a1ac..97013e59a6b298e670a706fd26435cf4f039033b 100644 --- a/src/java.desktop/share/classes/javax/swing/JDialog.java +++ b/src/java.desktop/share/classes/javax/swing/JDialog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -95,7 +95,8 @@ import javax.accessibility.*; */ @JavaBean(defaultProperty = "JMenuBar", description = "A toplevel window for creating dialog boxes.") @SwingContainer(delegate = "getContentPane") -@SuppressWarnings("serial") // Same-version serialization only +@SuppressWarnings({"serial", // Same-version serialization only + "doclint:missing"}) public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer, diff --git a/src/java.desktop/share/classes/javax/swing/JEditorPane.java b/src/java.desktop/share/classes/javax/swing/JEditorPane.java index 6d708f1b8b8d9e32491f6bcefee24ed90cd237b5..6b9189d550d584c851e9e7a1c93127bc92a9e6f1 100644 --- a/src/java.desktop/share/classes/javax/swing/JEditorPane.java +++ b/src/java.desktop/share/classes/javax/swing/JEditorPane.java @@ -41,6 +41,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; +import java.io.OutputStream; import java.io.Reader; import java.io.Serial; import java.io.StringReader; @@ -852,16 +853,12 @@ public class JEditorPane extends JTextComponent { private void handlePostData(HttpURLConnection conn, Object postData) throws IOException { conn.setDoOutput(true); - DataOutputStream os = null; - try { - conn.setRequestProperty("Content-Type", - "application/x-www-form-urlencoded"); - os = new DataOutputStream(conn.getOutputStream()); - os.writeBytes((String) postData); - } finally { - if (os != null) { - os.close(); - } + conn.setRequestProperty("Content-Type", + "application/x-www-form-urlencoded"); + try (OutputStream os = conn.getOutputStream(); + DataOutputStream dos = new DataOutputStream(os)) + { + dos.writeBytes((String)postData); } } diff --git a/src/java.desktop/share/classes/javax/swing/JInternalFrame.java b/src/java.desktop/share/classes/javax/swing/JInternalFrame.java index 17b0fecde0826c0456d8c4b2e64c8b377a9ac650..62efd03c0db844aad94f0065eab55a3c4330fba7 100644 --- a/src/java.desktop/share/classes/javax/swing/JInternalFrame.java +++ b/src/java.desktop/share/classes/javax/swing/JInternalFrame.java @@ -1233,10 +1233,9 @@ public class JInternalFrame extends JComponent implements @BeanProperty(bound = false, expert = true, description = "Specifies what desktop layer is used.") public void setLayer(Integer layer) { - if(getParent() != null && getParent() instanceof JLayeredPane) { + if (getParent() instanceof JLayeredPane p) { // Normally we want to do this, as it causes the LayeredPane // to draw properly. - JLayeredPane p = (JLayeredPane)getParent(); p.setLayer(this, layer.intValue(), p.getPosition(this)); } else { // Try to do the right thing diff --git a/src/java.desktop/share/classes/javax/swing/JLabel.java b/src/java.desktop/share/classes/javax/swing/JLabel.java index e7678d79374dc72d4468e22be0c7fcc6871ef788..8dff4a8fd25b3ba8eacd741730138d189071d537 100644 --- a/src/java.desktop/share/classes/javax/swing/JLabel.java +++ b/src/java.desktop/share/classes/javax/swing/JLabel.java @@ -1075,6 +1075,10 @@ public class JLabel extends JComponent implements SwingConstants, Accessible * @see AccessibleContext#setAccessibleName */ public String getAccessibleName() { + return getAccessibleNameCheckIcon(getAccessibleNameImpl()); + } + + private String getAccessibleNameImpl() { String name = accessibleName; if (name == null) { @@ -1089,6 +1093,19 @@ public class JLabel extends JComponent implements SwingConstants, Accessible return name; } + private String getAccessibleNameCheckIcon(String name) { + if (((name == null) || name.isEmpty()) && + (JLabel.this.getIcon() != null)) { + if (JLabel.this.getIcon() instanceof Accessible) { + AccessibleContext ac = ((Accessible) JLabel.this.getIcon()).getAccessibleContext(); + if (ac != null) { + name = ac.getAccessibleName(); + } + } + } + return name; + } + /** * Get the role of this object. * @@ -1097,6 +1114,11 @@ public class JLabel extends JComponent implements SwingConstants, Accessible * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { + String name = getAccessibleNameImpl(); + if (((name == null) || name.isEmpty()) && + (JLabel.this.getIcon() != null)) { + return AccessibleRole.ICON; + } return AccessibleRole.LABEL; } @@ -1110,8 +1132,8 @@ public class JLabel extends JComponent implements SwingConstants, Accessible if (icon instanceof Accessible) { AccessibleContext ac = ((Accessible)icon).getAccessibleContext(); - if (ac != null && ac instanceof AccessibleIcon) { - return new AccessibleIcon[] { (AccessibleIcon)ac }; + if (ac instanceof AccessibleIcon ai) { + return new AccessibleIcon[] { ai }; } } return null; diff --git a/src/java.desktop/share/classes/javax/swing/JList.java b/src/java.desktop/share/classes/javax/swing/JList.java index 7932209974bcc4a32c3cd02fd56ccf24a96f36d8..ac4a1e3fe3a6ff67d6b3b0047c3cab8734502b77 100644 --- a/src/java.desktop/share/classes/javax/swing/JList.java +++ b/src/java.desktop/share/classes/javax/swing/JList.java @@ -2949,21 +2949,21 @@ public class JList extends JComponent implements Scrollable, Accessible // re-set listData listeners if (name.equals("model")) { - if (oldValue != null && oldValue instanceof ListModel) { - ((ListModel) oldValue).removeListDataListener(this); + if (oldValue instanceof ListModel oldModel) { + oldModel.removeListDataListener(this); } - if (newValue != null && newValue instanceof ListModel) { - ((ListModel) newValue).addListDataListener(this); + if (newValue instanceof ListModel newModel) { + newModel.addListDataListener(this); } // re-set listSelectionModel listeners } else if (name.equals("selectionModel")) { - if (oldValue != null && oldValue instanceof ListSelectionModel) { - ((ListSelectionModel) oldValue).removeListSelectionListener(this); + if (oldValue instanceof ListSelectionModel oldModel) { + oldModel.removeListSelectionListener(this); } - if (newValue != null && newValue instanceof ListSelectionModel) { - ((ListSelectionModel) newValue).addListSelectionListener(this); + if (newValue instanceof ListSelectionModel newModel) { + newModel.addListSelectionListener(this); } firePropertyChange( diff --git a/src/java.desktop/share/classes/javax/swing/JMenu.java b/src/java.desktop/share/classes/javax/swing/JMenu.java index 5e54131d3ed2bdcfa4413ac86d100090d1b05de7..dbac4812ca821e3470adee0ae7b829e45f69fe72 100644 --- a/src/java.desktop/share/classes/javax/swing/JMenu.java +++ b/src/java.desktop/share/classes/javax/swing/JMenu.java @@ -1598,7 +1598,7 @@ public class JMenu extends JMenuItem implements Accessible,MenuElement return; } JMenuItem mi = getItem(i); - if (mi != null && mi instanceof JMenu) { + if (mi instanceof JMenu) { if (mi.isSelected()) { MenuElement[] old = MenuSelectionManager.defaultManager().getSelectedPath(); diff --git a/src/java.desktop/share/classes/javax/swing/JMenuBar.java b/src/java.desktop/share/classes/javax/swing/JMenuBar.java index cedaf9d25adbc0b141f39505bfacc56068e2ebe5..b94585702788d92a38eac4842072205fd8b02409 100644 --- a/src/java.desktop/share/classes/javax/swing/JMenuBar.java +++ b/src/java.desktop/share/classes/javax/swing/JMenuBar.java @@ -706,9 +706,7 @@ public class JMenuBar extends JComponent implements Accessible,MenuElement return false; } - if (c != null && c instanceof JComponent && - ((JComponent)c).processKeyBinding(ks, e, condition, pressed)) { - + if (c instanceof JComponent jc && jc.processKeyBinding(ks, e, condition, pressed)) { return true; } diff --git a/src/java.desktop/share/classes/javax/swing/JOptionPane.java b/src/java.desktop/share/classes/javax/swing/JOptionPane.java index 51dcd81d146d2d3499222bcd6865153080f1aed3..99eee90347ba2e2b8ad21258e1e2dfb5bc3d13bd 100644 --- a/src/java.desktop/share/classes/javax/swing/JOptionPane.java +++ b/src/java.desktop/share/classes/javax/swing/JOptionPane.java @@ -2330,17 +2330,17 @@ public class JOptionPane extends JComponent implements Accessible Vector values = new Vector(); s.defaultWriteObject(); - // Save the icon, if its Serializable. - if(icon != null && icon instanceof Serializable) { + // Save the icon, if it's Serializable. + if (icon instanceof Serializable) { values.addElement("icon"); values.addElement(icon); } - // Save the message, if its Serializable. - if(message != null && message instanceof Serializable) { + // Save the message, if it's Serializable. + if (message instanceof Serializable) { values.addElement("message"); values.addElement(message); } - // Save the treeModel, if its Serializable. + // Save the treeModel, if it's Serializable. if(options != null) { ArrayList serOptions = new ArrayList(); @@ -2354,17 +2354,17 @@ public class JOptionPane extends JComponent implements Accessible values.addElement(arrayOptions); } } - // Save the initialValue, if its Serializable. - if(initialValue != null && initialValue instanceof Serializable) { + // Save the initialValue, if it's Serializable. + if (initialValue instanceof Serializable) { values.addElement("initialValue"); values.addElement(initialValue); } - // Save the value, if its Serializable. - if(value != null && value instanceof Serializable) { + // Save the value, if it's Serializable. + if (value instanceof Serializable) { values.addElement("value"); values.addElement(value); } - // Save the selectionValues, if its Serializable. + // Save the selectionValues, if it's Serializable. if(selectionValues != null) { boolean serialize = true; @@ -2381,14 +2381,13 @@ public class JOptionPane extends JComponent implements Accessible values.addElement(selectionValues); } } - // Save the inputValue, if its Serializable. - if(inputValue != null && inputValue instanceof Serializable) { + // Save the inputValue, if it's Serializable. + if (inputValue instanceof Serializable) { values.addElement("inputValue"); values.addElement(inputValue); } - // Save the initialSelectionValue, if its Serializable. - if(initialSelectionValue != null && - initialSelectionValue instanceof Serializable) { + // Save the initialSelectionValue, if it's Serializable. + if (initialSelectionValue instanceof Serializable) { values.addElement("initialSelectionValue"); values.addElement(initialSelectionValue); } diff --git a/src/java.desktop/share/classes/javax/swing/JPopupMenu.java b/src/java.desktop/share/classes/javax/swing/JPopupMenu.java index 17afba6ec4b1c7748c59450d13b1d46f41d2e246..ef9ad42ef81d1f1978b1b6c7dbf49fd430009e07 100644 --- a/src/java.desktop/share/classes/javax/swing/JPopupMenu.java +++ b/src/java.desktop/share/classes/javax/swing/JPopupMenu.java @@ -988,10 +988,9 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { JPopupMenu mp = this; while((mp!=null) && (mp.isPopupMenu()!=true) && (mp.getInvoker() != null) && - (mp.getInvoker().getParent() != null) && - (mp.getInvoker().getParent() instanceof JPopupMenu) + (mp.getInvoker().getParent() instanceof JPopupMenu popupMenu) ) { - mp = (JPopupMenu) mp.getInvoker().getParent(); + mp = popupMenu; } return mp; } @@ -1330,13 +1329,13 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { Vector values = new Vector(); s.defaultWriteObject(); - // Save the invoker, if its Serializable. - if(invoker != null && invoker instanceof Serializable) { + // Save the invoker if != null, (Component implements Serializable) + if (invoker != null) { values.addElement("invoker"); values.addElement(invoker); } - // Save the popup, if its Serializable. - if(popup != null && popup instanceof Serializable) { + // Save the popup, if it's Serializable. + if (popup instanceof Serializable) { values.addElement("popup"); values.addElement(popup); } diff --git a/src/java.desktop/share/classes/javax/swing/JScrollBar.java b/src/java.desktop/share/classes/javax/swing/JScrollBar.java index df6e3e23b68ea71f89890916ac4692972e2a8363..25cdb0886a9867236ba796712658a152de4f97d0 100644 --- a/src/java.desktop/share/classes/javax/swing/JScrollBar.java +++ b/src/java.desktop/share/classes/javax/swing/JScrollBar.java @@ -83,7 +83,8 @@ import javax.swing.plaf.ScrollBarUI; */ @JavaBean(defaultProperty = "UI", description = "A component that helps determine the visible content range of an area.") @SwingContainer(false) -@SuppressWarnings("serial") // Same-version serialization only +@SuppressWarnings({"serial", // Same-version serialization only + "doclint:missing"}) public class JScrollBar extends JComponent implements Adjustable, Accessible { /** diff --git a/src/java.desktop/share/classes/javax/swing/JSlider.java b/src/java.desktop/share/classes/javax/swing/JSlider.java index 6310e69fd4c79656f13c5116eddee9afd1fca2fa..0d826fe7e49e1f910d4a6c1a623a62c06b1df8c9 100644 --- a/src/java.desktop/share/classes/javax/swing/JSlider.java +++ b/src/java.desktop/share/classes/javax/swing/JSlider.java @@ -1018,8 +1018,8 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { @SuppressWarnings("rawtypes") Dictionary labelTable = getLabelTable(); - if (labelTable != null && (labelTable instanceof PropertyChangeListener)) { - removePropertyChangeListener((PropertyChangeListener) labelTable); + if (labelTable instanceof PropertyChangeListener listener) { + removePropertyChangeListener(listener); } addPropertyChangeListener( table ); diff --git a/src/java.desktop/share/classes/javax/swing/JTable.java b/src/java.desktop/share/classes/javax/swing/JTable.java index 4b3e02f860f0cd91e49279f4a3ee8e946a9a6ab1..9af6a1ba616415e08121bf8c8b418a1960cabc8e 100644 --- a/src/java.desktop/share/classes/javax/swing/JTable.java +++ b/src/java.desktop/share/classes/javax/swing/JTable.java @@ -6579,7 +6579,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * A Printable implementation that wraps another * Printable, making it safe for printing on another thread. */ - private class ThreadSafePrintable implements Printable { + private static class ThreadSafePrintable implements Printable { /** The delegate Printable. */ private Printable printDelegate; @@ -6758,11 +6758,11 @@ public class JTable extends JComponent implements TableModelListener, Scrollable // re-set tableModel listeners if (name.equals("model")) { - if (oldValue != null && oldValue instanceof TableModel) { - ((TableModel) oldValue).removeTableModelListener(this); + if (oldValue instanceof TableModel oldModel) { + oldModel.removeTableModelListener(this); } - if (newValue != null && newValue instanceof TableModel) { - ((TableModel) newValue).addTableModelListener(this); + if (newValue instanceof TableModel newModel) { + newModel.addTableModelListener(this); } // re-set selectionModel listeners @@ -6771,24 +6771,20 @@ public class JTable extends JComponent implements TableModelListener, Scrollable Object source = e.getSource(); if (source == JTable.this) { // row selection model - if (oldValue != null && - oldValue instanceof ListSelectionModel) { - ((ListSelectionModel) oldValue).removeListSelectionListener(this); + if (oldValue instanceof ListSelectionModel oldModel) { + oldModel.removeListSelectionListener(this); } - if (newValue != null && - newValue instanceof ListSelectionModel) { - ((ListSelectionModel) newValue).addListSelectionListener(this); + if (newValue instanceof ListSelectionModel newModel) { + newModel.addListSelectionListener(this); } } else if (source == JTable.this.getColumnModel()) { - if (oldValue != null && - oldValue instanceof ListSelectionModel) { - ((ListSelectionModel) oldValue).removeListSelectionListener(this); + if (oldValue instanceof ListSelectionModel oldModel) { + oldModel.removeListSelectionListener(this); } - if (newValue != null && - newValue instanceof ListSelectionModel) { - ((ListSelectionModel) newValue).addListSelectionListener(this); + if (newValue instanceof ListSelectionModel newModel) { + newModel.addListSelectionListener(this); } } else { @@ -6799,13 +6795,11 @@ public class JTable extends JComponent implements TableModelListener, Scrollable // and column's selection property listener as well } else if (name.equals("columnModel")) { - if (oldValue != null && oldValue instanceof TableColumnModel) { - TableColumnModel tcm = (TableColumnModel) oldValue; + if (oldValue instanceof TableColumnModel tcm) { tcm.removeColumnModelListener(this); tcm.getSelectionModel().removeListSelectionListener(this); } - if (newValue != null && newValue instanceof TableColumnModel) { - TableColumnModel tcm = (TableColumnModel) newValue; + if (newValue instanceof TableColumnModel tcm) { tcm.addColumnModelListener(this); tcm.getSelectionModel().addListSelectionListener(this); } @@ -6813,11 +6807,11 @@ public class JTable extends JComponent implements TableModelListener, Scrollable // re-se cellEditor listeners } else if (name.equals("tableCellEditor")) { - if (oldValue != null && oldValue instanceof TableCellEditor) { - ((TableCellEditor) oldValue).removeCellEditorListener(this); + if (oldValue instanceof TableCellEditor oldEditor) { + oldEditor.removeCellEditorListener(this); } - if (newValue != null && newValue instanceof TableCellEditor) { - ((TableCellEditor) newValue).addCellEditorListener(this); + if (newValue instanceof TableCellEditor newEditor) { + newEditor.addCellEditorListener(this); } } } diff --git a/src/java.desktop/share/classes/javax/swing/JTree.java b/src/java.desktop/share/classes/javax/swing/JTree.java index e48c1b2933372b361acbd2f0ad2d560c08a3d4ac..ae90ea8be8bec502faf56b15683af34a8d75a161 100644 --- a/src/java.desktop/share/classes/javax/swing/JTree.java +++ b/src/java.desktop/share/classes/javax/swing/JTree.java @@ -3127,23 +3127,23 @@ public class JTree extends JComponent implements Scrollable, Accessible Vector values = new Vector(); s.defaultWriteObject(); - // Save the cellRenderer, if its Serializable. - if(cellRenderer != null && cellRenderer instanceof Serializable) { + // Save the cellRenderer, if it's Serializable. + if (cellRenderer instanceof Serializable) { values.addElement("cellRenderer"); values.addElement(cellRenderer); } - // Save the cellEditor, if its Serializable. - if(cellEditor != null && cellEditor instanceof Serializable) { + // Save the cellEditor, if it's Serializable. + if (cellEditor instanceof Serializable) { values.addElement("cellEditor"); values.addElement(cellEditor); } - // Save the treeModel, if its Serializable. - if(treeModel != null && treeModel instanceof Serializable) { + // Save the treeModel, if it's Serializable. + if (treeModel instanceof Serializable) { values.addElement("treeModel"); values.addElement(treeModel); } - // Save the selectionModel, if its Serializable. - if(selectionModel != null && selectionModel instanceof Serializable) { + // Save the selectionModel, if it's Serializable. + if (selectionModel instanceof Serializable) { values.addElement("selectionModel"); values.addElement(selectionModel); } @@ -3675,7 +3675,7 @@ public class JTree extends JComponent implements Scrollable, Accessible * This will fail if a TreeWillExpandListener vetos it. * * @param path a {@code TreePath} identifying a node - * @param state if {@code true}, all parents of @{code path} and path are marked as expanded. + * @param state if {@code true}, all parents of {@code path} and path are marked as expanded. * Otherwise, all parents of {@code path} are marked EXPANDED, * but {@code path} itself is marked collapsed. */ @@ -5414,14 +5414,12 @@ public class JTree extends JComponent implements Scrollable, Accessible public Rectangle getBounds() { Rectangle r = tree.getPathBounds(path); Accessible parent = getAccessibleParent(); - if (parent != null) { - if (parent instanceof AccessibleJTreeNode) { - Point parentLoc = ((AccessibleJTreeNode) parent).getLocationInJTree(); - if (parentLoc != null && r != null) { - r.translate(-parentLoc.x, -parentLoc.y); - } else { - return null; // not visible! - } + if (parent instanceof AccessibleJTreeNode treeNode) { + Point parentLoc = treeNode.getLocationInJTree(); + if (parentLoc != null && r != null) { + r.translate(-parentLoc.x, -parentLoc.y); + } else { + return null; // not visible! } } return r; diff --git a/src/java.desktop/share/classes/javax/swing/KeyboardManager.java b/src/java.desktop/share/classes/javax/swing/KeyboardManager.java index a2246e7a69bc19a9bb5d8578226ccb16c4370a6b..5b79b0d3d519e976bdf7e0ec1b8cc23c1bb379a8 100644 --- a/src/java.desktop/share/classes/javax/swing/KeyboardManager.java +++ b/src/java.desktop/share/classes/javax/swing/KeyboardManager.java @@ -29,8 +29,6 @@ import java.util.*; import java.awt.*; import java.awt.event.*; import java.applet.*; -import java.beans.*; -import javax.swing.event.*; import sun.awt.EmbeddedFrame; /** @@ -371,7 +369,7 @@ class KeyboardManager { * which looks up topContainers based on component, keystroke pairs * This is used to make unregistering KeyStrokes fast */ - class ComponentKeyStrokePair { + static class ComponentKeyStrokePair { Object component; Object keyStroke; diff --git a/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java b/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java index 25c525a20320d570f41940dffe1bbb4bc5c40b7e..c84a218b8776e4093282b84426fe7caf14470df2 100644 --- a/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java +++ b/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,8 +72,8 @@ public class MenuSelectionManager { // installing additional listener if found in the AppContext Object o = context.get(SwingUtilities2.MENU_SELECTION_MANAGER_LISTENER_KEY); - if (o != null && o instanceof ChangeListener) { - msm.addChangeListener((ChangeListener) o); + if (o instanceof ChangeListener listener) { + msm.addChangeListener(listener); } } diff --git a/src/java.desktop/share/classes/javax/swing/RepaintManager.java b/src/java.desktop/share/classes/javax/swing/RepaintManager.java index 88684226d95dbcb128d81206777f3af35e4f9dfe..fe414fc16afcd5f965ce676b985a691d82edac25 100644 --- a/src/java.desktop/share/classes/javax/swing/RepaintManager.java +++ b/src/java.desktop/share/classes/javax/swing/RepaintManager.java @@ -928,7 +928,7 @@ public class RepaintManager for (int i = roots.size() - 1; i >= index; i--) { Component c = roots.get(i); for(;;) { - if (c == root || c == null || !(c instanceof JComponent)) { + if (c == root || !(c instanceof JComponent)) { break; } c = c.getParent(); @@ -1812,7 +1812,7 @@ public class RepaintManager } } - private class DoubleBufferInfo { + private static class DoubleBufferInfo { public Image image; public Dimension size; public boolean needsReset = false; diff --git a/src/java.desktop/share/classes/javax/swing/SpinnerDateModel.java b/src/java.desktop/share/classes/javax/swing/SpinnerDateModel.java index 9117c93809f1a6456b96169b9a40efe7578400e8..c78bc150c1a1e96f9658ab53dccc8daf303d5585 100644 --- a/src/java.desktop/share/classes/javax/swing/SpinnerDateModel.java +++ b/src/java.desktop/share/classes/javax/swing/SpinnerDateModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -454,11 +454,11 @@ public class SpinnerDateModel extends AbstractSpinnerModel implements Serializab * @see #addChangeListener */ public void setValue(Object value) { - if ((value == null) || !(value instanceof Date)) { + if (!(value instanceof Date date)) { throw new IllegalArgumentException("illegal value"); } - if (!value.equals(this.value.getTime())) { - this.value.setTime((Date)value); + if (!date.equals(this.value.getTime())) { + this.value.setTime(date); fireStateChanged(); } } diff --git a/src/java.desktop/share/classes/javax/swing/SpinnerNumberModel.java b/src/java.desktop/share/classes/javax/swing/SpinnerNumberModel.java index d8db7b3ae0f177f0989cff69d8ebea213e05d63e..d2dd0a9d5f61ec9f817c1d3eb8e8ccf0b1418916 100644 --- a/src/java.desktop/share/classes/javax/swing/SpinnerNumberModel.java +++ b/src/java.desktop/share/classes/javax/swing/SpinnerNumberModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -452,11 +452,11 @@ public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializ * @see SpinnerModel#addChangeListener */ public void setValue(Object value) { - if ((value == null) || !(value instanceof Number)) { + if (!(value instanceof Number number)) { throw new IllegalArgumentException("illegal value"); } - if (!value.equals(this.value)) { - this.value = (Number)value; + if (!number.equals(this.value)) { + this.value = number; fireStateChanged(); } } diff --git a/src/java.desktop/share/classes/javax/swing/SwingUtilities.java b/src/java.desktop/share/classes/javax/swing/SwingUtilities.java index 35260056d7ee62ee682c19750ce97cf5e2186b36..5e3965e69b8edf7601ec495dd0c1aaefe251352a 100644 --- a/src/java.desktop/share/classes/javax/swing/SwingUtilities.java +++ b/src/java.desktop/share/classes/javax/swing/SwingUtilities.java @@ -106,12 +106,12 @@ public class SwingUtilities implements SwingConstants } /** - * Return {@code true} if @{code a} contains {@code b} + * Return {@code true} if {@code a} contains {@code b} * * @param a the first rectangle * @param b the second rectangle * - * @return {@code true} if @{code a} contains {@code b} + * @return {@code true} if {@code a} contains {@code b} */ public static final boolean isRectangleContainingRectangle(Rectangle a,Rectangle b) { return b.x >= a.x && (b.x + b.width) <= (a.x + a.width) && @@ -2054,8 +2054,8 @@ public class SwingUtilities implements SwingConstants * ImageIcon, and the image it contains is the same as image. */ static boolean doesIconReferenceImage(Icon icon, Image image) { - Image iconImage = (icon != null && (icon instanceof ImageIcon)) ? - ((ImageIcon)icon).getImage() : null; + Image iconImage = (icon instanceof ImageIcon i) ? + i.getImage() : null; return (iconImage == image); } diff --git a/src/java.desktop/share/classes/javax/swing/TransferHandler.java b/src/java.desktop/share/classes/javax/swing/TransferHandler.java index b366a283ffa184967be62e3984bef1f782a1f628..f2622880e7fa3e6576df41ee1f9bdc2e354f2444 100644 --- a/src/java.desktop/share/classes/javax/swing/TransferHandler.java +++ b/src/java.desktop/share/classes/javax/swing/TransferHandler.java @@ -1272,9 +1272,9 @@ public class TransferHandler implements Serializable { // If the Drop target is inactive the dragExit will not be dispatched to the dtListener, // so make sure that we clean up the dtListener anyway. DropTargetListener dtListener = getDropTargetListener(); - if (dtListener != null && dtListener instanceof DropHandler) { - ((DropHandler)dtListener).cleanup(false); - } + if (dtListener instanceof DropHandler dropHandler) { + dropHandler.cleanup(false); + } } } diff --git a/src/java.desktop/share/classes/javax/swing/UIManager.java b/src/java.desktop/share/classes/javax/swing/UIManager.java index 570cd6e2f3414c6a6a3c11031840758dc78f8218..309aaa7447e31b4fd762e0139bd2300dab62fff0 100644 --- a/src/java.desktop/share/classes/javax/swing/UIManager.java +++ b/src/java.desktop/share/classes/javax/swing/UIManager.java @@ -57,7 +57,6 @@ import sun.awt.SunToolkit; import sun.awt.OSInfo; import sun.security.action.GetPropertyAction; import sun.swing.SwingUtilities2; -import java.lang.reflect.Method; import java.util.HashMap; import java.util.Objects; import sun.awt.AppContext; @@ -1301,9 +1300,9 @@ public class UIManager implements Serializable if (file.exists()) { // InputStream has been buffered in Properties // class - FileInputStream ins = new FileInputStream(file); - props.load(ins); - ins.close(); + try (FileInputStream ins = new FileInputStream(file)) { + props.load(ins); + } } } catch (Exception e) { diff --git a/src/java.desktop/share/classes/javax/swing/event/EventListenerList.java b/src/java.desktop/share/classes/javax/swing/event/EventListenerList.java index 21dacb1d0df6146a50f269df8910ba0489f4880d..1be0228864c1e84410ef3138cbda74dc407aef99 100644 --- a/src/java.desktop/share/classes/javax/swing/event/EventListenerList.java +++ b/src/java.desktop/share/classes/javax/swing/event/EventListenerList.java @@ -283,7 +283,7 @@ public class EventListenerList implements Serializable { for (int i = 0; i < lList.length; i+=2) { Class t = (Class)lList[i]; EventListener l = (EventListener)lList[i+1]; - if ((l!=null) && (l instanceof Serializable)) { + if (l instanceof Serializable) { s.writeObject(t.getName()); s.writeObject(l); } diff --git a/src/java.desktop/share/classes/javax/swing/event/HyperlinkEvent.java b/src/java.desktop/share/classes/javax/swing/event/HyperlinkEvent.java index 57e11a4fbd850d420685897634c013ffcf65a275..c456f9c4f141c292763734773901c569a5f26ea4 100644 --- a/src/java.desktop/share/classes/javax/swing/event/HyperlinkEvent.java +++ b/src/java.desktop/share/classes/javax/swing/event/HyperlinkEvent.java @@ -175,7 +175,7 @@ public class HyperlinkEvent extends EventObject { /** * Returns the {@code InputEvent} that triggered the hyperlink event. * This will typically be a {@code MouseEvent}. If a constructor is used - * that does not specify an {@code InputEvent}, or @{code null} + * that does not specify an {@code InputEvent}, or {@code null} * was specified as the {@code InputEvent}, this returns {@code null}. * * @return InputEvent that triggered the hyperlink event, or null diff --git a/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java b/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java index 17a3b196b07e40ce61a8a25e617fa22d062b0f86..0f30ef14d88c2de6e46c5ac0f86ebfc95714e9c2 100644 --- a/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java +++ b/src/java.desktop/share/classes/javax/swing/filechooser/FileSystemView.java @@ -65,7 +65,7 @@ import sun.awt.shell.ShellFolder; // PENDING(jeff) - need to provide a specification for // how Mac/OS2/BeOS/etc file systems can modify FileSystemView // to handle their particular type of file system. - +@SuppressWarnings("doclint:missing") public abstract class FileSystemView { static FileSystemView windowsFileSystemView = null; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java index ff3a1596fbdafebc00a53b2dbb71ca7867aa01cb..ccb4272eef4a83ef73b242f544b2be1ed591faa0 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java @@ -95,7 +95,7 @@ public class BasicComboBoxUI extends ComboBoxUI { protected ComboPopup popup; /** - * The Component that the @{code ComboBoxEditor} uses for editing. + * The Component that the {@code ComboBoxEditor} uses for editing. */ protected Component editor; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicDesktopPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicDesktopPaneUI.java index 894e2b07d1a3964ab16452a3a578e0407e0dc946..772ea16c44ec73e5f1dbec4f0150403901205e4d 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicDesktopPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicDesktopPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,11 +31,14 @@ import javax.swing.plaf.*; import java.beans.*; import java.awt.event.*; +import java.awt.Component; +import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; +import java.awt.FocusTraversalPolicy; import java.awt.Graphics; import java.awt.KeyboardFocusManager; -import java.awt.*; +import java.awt.Point; import sun.swing.DefaultLookup; import sun.swing.UIAction; @@ -347,7 +350,7 @@ public class BasicDesktopPaneUI extends DesktopPaneUI { * The default DesktopManager installed by the UI. */ @SuppressWarnings("serial") // JDK-implementation class - private class BasicDesktopManager extends DefaultDesktopManager + private static class BasicDesktopManager extends DefaultDesktopManager implements UIResource { } @@ -566,10 +569,7 @@ public class BasicDesktopPaneUI extends DesktopPaneUI { if (cycleRoot != null) { FocusTraversalPolicy policy = cycleRoot.getFocusTraversalPolicy(); - if (policy != null && policy instanceof - SortingFocusTraversalPolicy) { - SortingFocusTraversalPolicy sPolicy = - (SortingFocusTraversalPolicy)policy; + if (policy instanceof SortingFocusTraversalPolicy sPolicy) { boolean idc = sPolicy.getImplicitDownCycleTraversal(); try { sPolicy.setImplicitDownCycleTraversal(false); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java index 18f94db30406ccaf08ff2dff215d4bc9b261e743..33f42da00f8270734d2f2d52bc82f4a8e476a79f 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,7 +40,6 @@ import java.util.List; import java.util.regex.*; import sun.awt.shell.ShellFolder; import sun.swing.*; -import sun.swing.SwingUtilities2; /** * Basic L&F implementation of a FileChooser. @@ -1204,7 +1203,7 @@ public class BasicFileChooserUI extends FileChooserUI { /* A file filter which accepts file patterns containing * the special wildcards *? on Windows and *?[] on Unix. */ - class GlobFilter extends FileFilter { + static class GlobFilter extends FileFilter { Pattern pattern; String globPattern; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java index 1a21268d74c00a10a4fd1820b4df676c3bf46707..cea618a20e3ce7bb96eeb8bebef33913962d0714 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -968,7 +968,7 @@ public class BasicInternalFrameTitlePane extends JComponent } // end SystemMenuBar - private class NoFocusButton extends JButton { + private static class NoFocusButton extends JButton { private String uiKey; public NoFocusButton(String uiKey, String opacityKey) { setFocusPainted(false); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java index 603dd896fde66992938808aa3fcc1d33cba1e6de..4e2e0fac3052f4bf3c72516d490bcdd667ddb591 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -578,9 +578,8 @@ public class BasicInternalFrameUI extends InternalFrameUI * @param c the new north pane */ public void setNorthPane(JComponent c) { - if (northPane != null && - northPane instanceof BasicInternalFrameTitlePane) { - ((BasicInternalFrameTitlePane)northPane).uninstallListeners(); + if (northPane instanceof BasicInternalFrameTitlePane tp) { + tp.uninstallListeners(); } replacePane(northPane, c); northPane = c; @@ -1614,9 +1613,8 @@ public class BasicInternalFrameUI extends InternalFrameUI // account the title pane since you are allowed to resize // the frames to the point where just the title pane is visible. Dimension result = new Dimension(); - if (getNorthPane() != null && - getNorthPane() instanceof BasicInternalFrameTitlePane) { - result = new Dimension(getNorthPane().getMinimumSize()); + if (getNorthPane() instanceof BasicInternalFrameTitlePane tp) { + result = new Dimension(tp.getMinimumSize()); } Insets i = frame.getInsets(); result.width += i.left + i.right; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java index e2103468ab81a157b8c407a4b465a4b37075abae..fa6a531276715b58591f6b1544670e847f83d5fe 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java @@ -45,6 +45,7 @@ import sun.swing.*; * @author Arnaud Weber * @author Fredrik Lagerblad */ +@SuppressWarnings("doclint:missing") public class BasicMenuItemUI extends MenuItemUI { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java index 33699871a18c8ff59d8f60555f1c3c8891b9c95d..78727a729c4228066672f8b20c3e3a019aafcee5 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,6 +46,7 @@ import java.util.ArrayList; * @author David Karlton * @author Arnaud Weber */ +@SuppressWarnings("doclint:missing") public class BasicMenuUI extends BasicMenuItemUI { /** @@ -297,20 +298,20 @@ public class BasicMenuUI extends BasicMenuItemUI final MenuSelectionManager defaultManager = MenuSelectionManager.defaultManager(); if(force) { Container cnt = menu.getParent(); - if(cnt != null && cnt instanceof JMenuBar) { + if (cnt instanceof JMenuBar menuBar) { MenuElement[] me; MenuElement[] subElements; subElements = menu.getPopupMenu().getSubElements(); if(subElements.length > 0) { me = new MenuElement[4]; - me[0] = (MenuElement) cnt; + me[0] = menuBar; me[1] = menu; me[2] = menu.getPopupMenu(); me[3] = subElements[0]; } else { me = new MenuElement[3]; - me[0] = (MenuElement)cnt; + me[0] = menuBar; me[1] = menu; me[2] = menu.getPopupMenu(); } @@ -512,10 +513,10 @@ public class BasicMenuUI extends BasicMenuItemUI manager.clearSelectedPath(); } else { Container cnt = menu.getParent(); - if(cnt != null && cnt instanceof JMenuBar) { + if (cnt instanceof JMenuBar menuBar) { MenuElement[] me = new MenuElement[2]; - me[0]=(MenuElement)cnt; - me[1]=menu; + me[0] = menuBar; + me[1] = menu; manager.setSelectedPath(me); } } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java index 427823573a6dba054004eb7408041c59c9c744a9..935e028783a170e4d3cbb562b3d98a6cf9dd982c 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -964,13 +964,10 @@ public class BasicOptionPaneUI extends OptionPaneUI { * the look and feel for based on the value in the inputComponent. */ protected void resetInputValue() { - if(inputComponent != null && (inputComponent instanceof JTextField)) { - optionPane.setInputValue(((JTextField)inputComponent).getText()); - - } else if(inputComponent != null && - (inputComponent instanceof JComboBox)) { - optionPane.setInputValue(((JComboBox)inputComponent) - .getSelectedItem()); + if (inputComponent instanceof JTextField textField) { + optionPane.setInputValue(textField.getText()); + } else if (inputComponent instanceof JComboBox comboBox) { + optionPane.setInputValue(comboBox.getSelectedItem()); } else if(inputComponent != null) { optionPane.setInputValue(((JList)inputComponent) .getSelectedValue()); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java index ae652d81fa240597d76909af10042da096be2fbc..70244cd5ff6f21c536f262b8134d1df46478f771 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java @@ -28,26 +28,18 @@ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; -import javax.swing.plaf.basic.*; -import javax.swing.border.*; import java.applet.Applet; import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.*; import java.awt.AWTEvent; import java.awt.Toolkit; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; - import java.util.*; -import sun.swing.DefaultLookup; import sun.swing.UIAction; import sun.awt.AppContext; @@ -294,7 +286,7 @@ public class BasicPopupMenuUI extends PopupMenuUI { * * @since 1.4 */ - private class BasicPopupMenuListener implements PopupMenuListener { + private static class BasicPopupMenuListener implements PopupMenuListener { public void popupMenuCanceled(PopupMenuEvent e) { } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java index 71d0e4b671775105a2b5910459decfd3923a893b..cc6c46318d7a157fb25a3858ed6a5ade41432e34 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -197,8 +197,8 @@ public class BasicSpinnerUI extends SpinnerUI spinner.addChangeListener(getHandler()); } JComponent editor = spinner.getEditor(); - if (editor != null && editor instanceof JSpinner.DefaultEditor) { - JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField(); + if (editor instanceof JSpinner.DefaultEditor defaultEditor) { + JTextField tf = defaultEditor.getTextField(); if (tf != null) { tf.addFocusListener(nextButtonHandler); tf.addFocusListener(previousButtonHandler); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java index 24b2fa873f1c934f05e1fc97e4fda62365cd362f..5fa79a7fa4da7a7b8185142d0a722fb204eb88fa 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -344,7 +344,7 @@ public class BasicSplitPaneUI extends SplitPaneUI Border b = divider.getBorder(); - if (b == null || !(b instanceof UIResource)) { + if (!(b instanceof UIResource)) { divider.setBorder(UIManager.getBorder("SplitPaneDivider.border")); } @@ -2359,8 +2359,7 @@ public class BasicSplitPaneUI extends SplitPaneUI } private Component getFirstAvailableComponent(Component c) { - if (c!=null && c instanceof JSplitPane) { - JSplitPane sp = (JSplitPane)c; + if (c instanceof JSplitPane sp) { Component left = getFirstAvailableComponent(sp.getLeftComponent()); if (left != null) { c = left; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java index 8446354fe142650749fbbfbd1f69567945e1f9e3..c9e5fd51f7fe194eeeb2165141d1174e9eb5830e 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -3945,8 +3945,8 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants { } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class ScrollableTabButton extends BasicArrowButton implements UIResource, - SwingConstants { + private static class ScrollableTabButton extends BasicArrowButton + implements UIResource, SwingConstants { public ScrollableTabButton(int direction) { super(direction, UIManager.getColor("TabbedPane.selected"), diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java index 721fcbda9b705f87494030a847383127ea6c0b42..924458ad2fab972a7881984a6a8def72197cc0e3 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableHeaderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -535,13 +535,11 @@ public class BasicTableHeaderUI extends TableHeaderUI { * to ensure that the newly selected column is visible. */ private void scrollToColumn(int col) { - Container container; JTable table; //Test whether the header is in a scroll pane and has a table. if ((header.getParent() == null) || - ((container = header.getParent().getParent()) == null) || - !(container instanceof JScrollPane) || + !(header.getParent().getParent() instanceof JScrollPane) || ((table = header.getTable()) == null)) { return; } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java index 2ee4f1fa26d9138434f45f301f8fd9f9380ac331..37ebb12823cd71ddd5f1429481a5908fbb06b595 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,16 +27,11 @@ package javax.swing.plaf.basic; import java.awt.*; import java.awt.datatransfer.*; -import java.awt.dnd.*; import java.awt.event.*; import java.util.Enumeration; -import java.util.EventObject; -import java.util.Hashtable; -import java.util.TooManyListenersException; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; -import javax.swing.text.*; import javax.swing.table.*; import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag; import sun.swing.SwingUtilities2; @@ -221,8 +216,8 @@ public class BasicTableUI extends TableUI this.inSelection = true; // look at the sign of dx and dy only - dx = sign(dx); - dy = sign(dy); + dx = Integer.signum(dx); + dy = Integer.signum(dy); // make sure one is zero, but not both assert (dx == 0 || dy == 0) && !(dx == 0 && dy == 0); @@ -250,10 +245,6 @@ public class BasicTableUI extends TableUI leadColumn = clipToRange(leadColumn+dx, 0, table.getColumnCount()); } - private static int sign(int num) { - return (num < 0) ? -1 : ((num == 0) ? 0 : 1); - } - /** * Called to move within the selected range of the given JTable. * This method uses the table's notion of selection, which is @@ -933,24 +924,21 @@ public class BasicTableUI extends TableUI // the table, seems to have no effect. Component editorComp = table.getEditorComponent(); - if (table.isEditing() && editorComp != null) { - if (editorComp instanceof JComponent) { - JComponent component = (JComponent)editorComp; - map = component.getInputMap(JComponent.WHEN_FOCUSED); - Object binding = (map != null) ? map.get(keyStroke) : null; - if (binding == null) { - map = component.getInputMap(JComponent. - WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - binding = (map != null) ? map.get(keyStroke) : null; - } - if (binding != null) { - ActionMap am = component.getActionMap(); - Action action = (am != null) ? am.get(binding) : null; - if (action != null && SwingUtilities. + if (table.isEditing() && editorComp instanceof JComponent component) { + map = component.getInputMap(JComponent.WHEN_FOCUSED); + Object binding = (map != null) ? map.get(keyStroke) : null; + if (binding == null) { + map = component.getInputMap(JComponent. + WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + binding = (map != null) ? map.get(keyStroke) : null; + } + if (binding != null) { + ActionMap am = component.getActionMap(); + Action action = (am != null) ? am.get(binding) : null; + if (action != null && SwingUtilities. notifyAction(action, keyStroke, e, component, - e.getModifiers())) { - e.consume(); - } + e.getModifiers())) { + e.consume(); } } } @@ -1485,8 +1473,8 @@ public class BasicTableUI extends TableUI Container parent = SwingUtilities.getUnwrappedParent(table); // should be viewport if (parent != null) { parent = parent.getParent(); // should be the scrollpane - if (parent != null && parent instanceof JScrollPane) { - LookAndFeel.installBorder((JScrollPane)parent, "Table.scrollPaneBorder"); + if (parent instanceof JScrollPane scrollPane) { + LookAndFeel.installBorder(scrollPane, "Table.scrollPaneBorder"); } } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java index b6d4bc6412bb78f7b81fa718fc7f2ee64fc3cd2c..6e98a57e5c31d266480b29822fe60203cdf961fc 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java @@ -182,8 +182,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory { String prefix = getPropertyPrefix(); Object o = DefaultLookup.get(editor, this, prefix + ".keyBindings"); - if ((o != null) && (o instanceof JTextComponent.KeyBinding[])) { - JTextComponent.KeyBinding[] bindings = (JTextComponent.KeyBinding[]) o; + if (o instanceof JTextComponent.KeyBinding[] bindings) { JTextComponent.loadKeymap(map, bindings, getComponent().getActions()); } } @@ -536,8 +535,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory { * should allow Tab to keyboard - accessibility */ EditorKit editorKit = getEditorKit(editor); - if ( editorKit != null - && editorKit instanceof DefaultEditorKit) { + if (editorKit instanceof DefaultEditorKit) { Set storedForwardTraversalKeys = editor. getFocusTraversalKeys(KeyboardFocusManager. FORWARD_TRAVERSAL_KEYS); @@ -617,9 +615,8 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory { if (getEditorKit(editor) instanceof DefaultEditorKit) { if (map != null) { Object obj = map.get(DefaultEditorKit.insertBreakAction); - if (obj != null - && obj instanceof DefaultEditorKit.InsertBreakAction) { - Action action = new TextActionWrapper((TextAction)obj); + if (obj instanceof DefaultEditorKit.InsertBreakAction breakAction) { + Action action = new TextActionWrapper(breakAction); componentMap.put(action.getValue(Action.NAME),action); } } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java index a1d47aa4408f1da3feb3e4761ab992a155e20f7b..8a13bf119a5d140ca04b99e518b9bf084784ee23 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java @@ -654,8 +654,8 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants Container p; for(p = toolBar.getParent() ; p != null && !(p instanceof Window) ; p = p.getParent()); - if(p != null && p instanceof Window) - frame = (Window) p; + if (p instanceof Window window) + frame = window; } if(floatingToolBar == null) { floatingToolBar = createFloatingWindow(toolBar); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTreeUI.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTreeUI.java index 650048a99734d13b58ecf79de4da19c645cf38b0..2626b1c9585023f3bdc59d378b1d42d53d7afb26 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTreeUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTreeUI.java @@ -1131,10 +1131,8 @@ public class BasicTreeUI extends TreeUI * @return a default cell editor */ protected TreeCellEditor createDefaultCellEditor() { - if(currentCellRenderer != null && - (currentCellRenderer instanceof DefaultTreeCellRenderer)) { - DefaultTreeCellEditor editor = new DefaultTreeCellEditor - (tree, (DefaultTreeCellRenderer)currentCellRenderer); + if (currentCellRenderer instanceof DefaultTreeCellRenderer defaultRenderer) { + DefaultTreeCellEditor editor = new DefaultTreeCellEditor(tree, defaultRenderer); return editor; } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalBorders.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalBorders.java index 56e7cf7a798238329e2701ebe36c462d0c561294..9513b723490f18a03c51cfd4b2272d06dacd0a29 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalBorders.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalBorders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,7 @@ import sun.swing.SwingUtilities2; * Factory object that can vend Borders appropriate for the metal L & F. * @author Steve Wilson */ - +@SuppressWarnings("doclint:missing") public class MetalBorders { /** diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java index 191d63fa30481e19bb6297bf411ee508f1eb226d..4bde085d66a097cb51aeacb2eddbf6164190efa7 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,7 @@ package javax.swing.plaf.metal; import javax.swing.*; import javax.swing.border.*; -import java.io.Serializable; import java.awt.*; -import java.awt.event.*; import javax.swing.plaf.basic.BasicComboBoxEditor; @@ -89,7 +87,7 @@ public class MetalComboBoxEditor extends BasicComboBoxEditor { */ protected static Insets editorBorderInsets = new Insets( 2, 2, 2, 0 ); - class EditorBorder extends AbstractBorder { + static class EditorBorder extends AbstractBorder { public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { g.translate( x, y ); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java index 254393e01afdcfaca21566b4202af32df1257205..997af4983a3a58ac8407eb98ec12b53ad0f731ae 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java @@ -38,8 +38,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.accessibility.*; import sun.awt.shell.ShellFolder; @@ -958,7 +956,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } static final int space = 10; - class IndentIcon implements Icon { + static class IndentIcon implements Icon { Icon icon = null; int depth = 0; @@ -1144,8 +1142,8 @@ public class MetalFileChooserUI extends BasicFileChooserUI { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value != null && value instanceof FileFilter) { - setText(((FileFilter)value).getDescription()); + if (value instanceof FileFilter fileFilter) { + setText(fileFilter.getDescription()); } return this; @@ -1361,7 +1359,7 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class AlignedLabel extends JLabel { + private static class AlignedLabel extends JLabel { private AlignedLabel[] group; private int maxWidth = 0; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalIconFactory.java b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalIconFactory.java index 9df2b625e1862e362d8aae154c648b3a8fdc48e7..a7e24b332a1bf09f6b302be962b378eb34e77d12 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalIconFactory.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalIconFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1621,7 +1621,7 @@ public class MetalIconFactory implements Serializable { Vector images = new Vector(1, 1); ImageGcPair currentImageGcPair; - class ImageGcPair { + static class ImageGcPair { Image image; GraphicsConfiguration gc; ImageGcPair(Image image, GraphicsConfiguration gc) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java b/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java index 03b7fd081ad4fa986e3f1942136da25b51807ecc..495066f066fb7fc08c3c95cc4ba960c144ed9090 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java @@ -495,7 +495,7 @@ public class NimbusLookAndFeel extends SynthLookAndFeel { /** * Simple Symbolic Link style UIDefalts Property */ - private class LinkProperty implements UIDefaults.ActiveValue, UIResource{ + private static class LinkProperty implements UIDefaults.ActiveValue, UIResource{ private String dstPropName; private LinkProperty(String dstPropName) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java b/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java index b2c8fc6e679dce5f72f898287b55d2da8cb3bcb3..1a838d926e75907ae879d78f87e092973b6afd77 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java @@ -1019,7 +1019,7 @@ public final class NimbusStyle extends SynthStyle { * fonts, painters, etc associated with some state for this * style. */ - private final class RuntimeState implements Cloneable { + private static final class RuntimeState implements Cloneable { int state; Painter backgroundPainter; Painter foregroundPainter; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java index 953efdbe42d472ec4b9b1f23952aeaae11ad7536..98fd2d1c4fead874c063d5d672f0bfe3f1692081 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -933,7 +933,7 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI * {@code UIResource}. */ @SuppressWarnings("serial") // Superclass is not serializable across versions - private class SynthScrollableTabButton extends SynthArrowButton implements + private static class SynthScrollableTabButton extends SynthArrowButton implements UIResource { public SynthScrollableTabButton(int direction) { super(direction); diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTableUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTableUI.java index 8a863f41e0006068f1d52478933cd40eb7368bf4..8c007ae05cbc3e5b304bfa6030bbcecb32578229 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTableUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTableUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -713,7 +713,7 @@ public class SynthTableUI extends BasicTableUI * The renderer installed by the UI to render the boolean data. */ @SuppressWarnings("serial") // Superclass is not serializable across versions - private class SynthBooleanTableCellRenderer extends JCheckBox implements + private static class SynthBooleanTableCellRenderer extends JCheckBox implements TableCellRenderer { private boolean isRowSelected; diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 29aacf365f14a3e0d65fd2584e1d4b2ff67a837a..707c438180d5f1b69285776e417131a1e3dc6303 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -147,8 +147,7 @@ public class SynthTextFieldUI extends BasicTextFieldUI implements SynthUI { Caret caret = comp.getCaret(); if (caret instanceof UIResource) { Object o = style.get(context, prefix + ".caretBlinkRate"); - if (o != null && o instanceof Integer) { - Integer rate = (Integer)o; + if (o instanceof Integer rate) { caret.setBlinkRate(rate.intValue()); } } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index d7cf0aa99f88389a83f05174460790427d2e7c8b..ce9ae2813e843aacbca32418d9d08620db40c822 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -203,9 +203,8 @@ public class SynthTreeUI extends BasicTreeUI TreeCellRenderer renderer = tree.getCellRenderer(); DefaultTreeCellEditor editor; - if(renderer != null && (renderer instanceof DefaultTreeCellRenderer)) { - editor = new SynthTreeCellEditor(tree, (DefaultTreeCellRenderer) - renderer); + if (renderer instanceof DefaultTreeCellRenderer defaultRenderer) { + editor = new SynthTreeCellEditor(tree, defaultRenderer); } else { editor = new SynthTreeCellEditor(tree, null); diff --git a/src/java.desktop/share/classes/javax/swing/text/BoxView.java b/src/java.desktop/share/classes/javax/swing/text/BoxView.java index 1988adcad344c2c1c27156997fc02c4baa280a39..afaefacccf5457dcf74c8cfdcf67a4c6e06cf99b 100644 --- a/src/java.desktop/share/classes/javax/swing/text/BoxView.java +++ b/src/java.desktop/share/classes/javax/swing/text/BoxView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1150,9 +1150,9 @@ public class BoxView extends CompositeView { int index = getViewIndexAtPosition(testPos); if(index != -1) { View v = getView(index); - if(v != null && v instanceof CompositeView) { - return ((CompositeView)v).flipEastAndWestAtEnds(position, - bias); + if (v instanceof CompositeView compositeView) { + return compositeView.flipEastAndWestAtEnds(position, + bias); } } } diff --git a/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java b/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java index 790fc977793128ec6783a91bf3e517e0ca5ff4a0..4e874ec1f007433bff147c63cd7ab12889161afb 100644 --- a/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java @@ -509,7 +509,7 @@ public class DefaultHighlighter extends LayeredHighlighter { } - class HighlightInfo implements Highlighter.Highlight { + static class HighlightInfo implements Highlighter.Highlight { public int getStartOffset() { return p0.getOffset(); @@ -533,7 +533,7 @@ public class DefaultHighlighter extends LayeredHighlighter { * LayeredHighlightPainter is used when a drawsLayeredHighlights is * true. It maintains a rectangle of the region to paint. */ - class LayeredHighlightInfo extends HighlightInfo { + static class LayeredHighlightInfo extends HighlightInfo { void union(Shape bounds) { if (bounds == null) diff --git a/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java b/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java index 721421f780c77d41db40c2c7f4b37b4a00c61fa1..f549f522ff2b7513449091c0a64ca8aebe4636ac 100644 --- a/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/src/java.desktop/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -438,11 +438,11 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc */ public void setLogicalStyle(int pos, Style s) { Element paragraph = getParagraphElement(pos); - if ((paragraph != null) && (paragraph instanceof AbstractElement)) { + if (paragraph instanceof AbstractElement abstractElement) { try { writeLock(); - StyleChangeUndoableEdit edit = new StyleChangeUndoableEdit((AbstractElement)paragraph, s); - ((AbstractElement)paragraph).setResolveParent(s); + StyleChangeUndoableEdit edit = new StyleChangeUndoableEdit(abstractElement, s); + abstractElement.setResolveParent(s); int p0 = paragraph.getStartOffset(); int p1 = paragraph.getEndOffset(); DefaultDocumentEvent e = diff --git a/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java b/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java index 8b2714ec9856ced9f9038e4b88b2205849dea2f6..3c9d1c234d8567d4e44bd2eab99526069d0042d9 100644 --- a/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java +++ b/src/java.desktop/share/classes/javax/swing/text/ElementIterator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,7 +78,7 @@ public class ElementIterator implements Cloneable { * vector of children of the element. In this case, the item on the stack * represents the "index"th child of the element. */ - private class StackItem implements Cloneable { + private static class StackItem implements Cloneable { Element item; int childIndex; diff --git a/src/java.desktop/share/classes/javax/swing/text/GapContent.java b/src/java.desktop/share/classes/javax/swing/text/GapContent.java index 0f377c5059a7ff00ff265794f5511e8818742eda..c59c350541b117fad90cd1c992cb4d5fe88d5836 100644 --- a/src/java.desktop/share/classes/javax/swing/text/GapContent.java +++ b/src/java.desktop/share/classes/javax/swing/text/GapContent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -504,13 +504,7 @@ public class GapContent extends GapVector implements AbstractDocument.Content, S * @return < 0 if o1 < o2, 0 if the same, > 0 if o1 > o2 */ final int compare(MarkData o1, MarkData o2) { - if (o1.index < o2.index) { - return -1; - } else if (o1.index > o2.index) { - return 1; - } else { - return 0; - } + return Integer.compare(o1.index, o2.index); } /** diff --git a/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java b/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java index 414fea199c42e431ea247a47d2f7bc54d56e7f7d..cbdd308cc84b81dc0b516a9da0ad7d9d25e5105c 100644 --- a/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java +++ b/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java @@ -52,11 +52,7 @@ import java.awt.font.TextAttribute; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import java.awt.print.Printable; -import java.awt.print.PrinterException; - import javax.print.PrintService; -import javax.print.attribute.PrintRequestAttributeSet; import java.text.*; import java.text.AttributedCharacterIterator.Attribute; @@ -3306,8 +3302,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A // Fixes bug 4487492 Document doc = JTextComponent.this.getDocument(); - if (doc != null && doc instanceof StyledDocument) { - StyledDocument sDoc = (StyledDocument)doc; + if (doc instanceof StyledDocument sDoc) { int offset = startIndex; int length = endIndex - startIndex; sDoc.setCharacterAttributes(offset, length, as, true); @@ -5109,7 +5104,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A // // Runnable class for invokeLater() to set caret position later. // - private class DoSetCaretPosition implements Runnable { + private static class DoSetCaretPosition implements Runnable { JTextComponent host; Position newPos; diff --git a/src/java.desktop/share/classes/javax/swing/text/LayeredHighlighter.java b/src/java.desktop/share/classes/javax/swing/text/LayeredHighlighter.java index 08291e7176933741969b52c3056d9c9ad9c5c517..c50710233fcc561cb0e22844c18e7f84148d3205 100644 --- a/src/java.desktop/share/classes/javax/swing/text/LayeredHighlighter.java +++ b/src/java.desktop/share/classes/javax/swing/text/LayeredHighlighter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,6 +33,7 @@ import java.awt.Shape; * @author Timothy Prinzing * @see Highlighter */ +@SuppressWarnings("doclint:missing") public abstract class LayeredHighlighter implements Highlighter { /** * Constructor for subclasses to call. diff --git a/src/java.desktop/share/classes/javax/swing/text/MaskFormatter.java b/src/java.desktop/share/classes/javax/swing/text/MaskFormatter.java index 017787dd4258185b5ad7fd6737650bad9f13b9d3..0377b328b791d33b403dedbcee50a94938eb0c6a 100644 --- a/src/java.desktop/share/classes/javax/swing/text/MaskFormatter.java +++ b/src/java.desktop/share/classes/javax/swing/text/MaskFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,10 +25,13 @@ package javax.swing.text; -import java.io.*; -import java.text.*; -import java.util.*; -import javax.swing.*; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serial; +import java.text.ParseException; +import java.util.ArrayList; +import javax.swing.JFormattedTextField; +import javax.swing.text.DefaultFormatter; /** * MaskFormatter is used to format and edit strings. The behavior @@ -100,7 +103,7 @@ import javax.swing.*; *
        *   MaskFormatter formatter = new MaskFormatter("###-####");
        *   formatter.setPlaceholderCharacter('_');
      - *   formatter.getDisplayValue(tf, "123");
      + *   System.out.println(formatter.valueToString("123"));
        * 
      *

      * Would result in the string '123-____'. If diff --git a/src/java.desktop/share/classes/javax/swing/text/StringContent.java b/src/java.desktop/share/classes/javax/swing/text/StringContent.java index bef98a5cc2ae3f93bf772e6d611fcd4c90426303..7f154df38edffce7203667f93ff9980c0c6268ba 100644 --- a/src/java.desktop/share/classes/javax/swing/text/StringContent.java +++ b/src/java.desktop/share/classes/javax/swing/text/StringContent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ package javax.swing.text; import java.util.Vector; import java.io.Serializable; import javax.swing.undo.*; -import javax.swing.SwingUtilities; /** * An implementation of the AbstractDocument.Content interface that is @@ -324,7 +323,7 @@ public final class StringContent implements AbstractDocument.Content, Serializab * it.... the update table holds only a reference * to this grungy thing. */ - final class PosRec { + static final class PosRec { PosRec(int offset) { this.offset = offset; @@ -351,7 +350,7 @@ public final class StringContent implements AbstractDocument.Content, Serializab return rec.offset; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { // schedule the record to be removed later // on another thread. @@ -369,7 +368,7 @@ public final class StringContent implements AbstractDocument.Content, Serializab * Used to hold a reference to a Position that is being reset as the * result of removing from the content. */ - final class UndoPosRef { + static final class UndoPosRef { UndoPosRef(PosRec rec) { this.rec = rec; this.undoLocation = rec.offset; diff --git a/src/java.desktop/share/classes/javax/swing/text/StyleContext.java b/src/java.desktop/share/classes/javax/swing/text/StyleContext.java index b43282d1080d9416280634a07ff0c7f76730de2e..9e01aecd3fb6dc3c5cef3abdfdebf0368cf9c77f 100644 --- a/src/java.desktop/share/classes/javax/swing/text/StyleContext.java +++ b/src/java.desktop/share/classes/javax/swing/text/StyleContext.java @@ -1055,7 +1055,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon /** * An enumeration of the keys in a SmallAttributeSet. */ - class KeyEnumeration implements Enumeration { + static class KeyEnumeration implements Enumeration { KeyEnumeration(Object[] attr) { this.attr = attr; @@ -1097,7 +1097,7 @@ public class StyleContext implements Serializable, AbstractDocument.AttributeCon * Sorts the key strings so that they can be very quickly compared * in the attribute set searches. */ - class KeyBuilder { + static class KeyBuilder { public void initialize(AttributeSet a) { if (a instanceof SmallAttributeSet) { diff --git a/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java b/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java index a756cb2a02fbfcf60e5a2d8f45d66ae9ae00be13..ba8465d45704185ab7a86a6afa6973cd6a8eed42 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java @@ -370,8 +370,8 @@ class AccessibleHTML implements Accessible { */ public Accessible getAccessibleChild(int i) { ElementInfo childInfo = elementInfo.getChild(i); - if (childInfo != null && childInfo instanceof Accessible) { - return (Accessible)childInfo; + if (childInfo instanceof Accessible accessibleChild) { + return accessibleChild; } else { return null; } @@ -1212,9 +1212,8 @@ class AccessibleHTML implements Accessible { private String getText(int offset, int length) throws BadLocationException { - if (model != null && model instanceof StyledDocument) { - StyledDocument doc = (StyledDocument)model; - return model.getText(offset, length); + if (model instanceof StyledDocument doc) { + return doc.getText(offset, length); } else { return null; } diff --git a/src/java.desktop/share/classes/javax/swing/text/html/CSS.java b/src/java.desktop/share/classes/javax/swing/text/html/CSS.java index 76ce4ac815f270e5e62ac7668734d6f868e0fd9c..22fa96b615337548703e8e98bedf447b78c6b84b 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/CSS.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/CSS.java @@ -1608,8 +1608,8 @@ public class CSS implements Serializable { if (key instanceof HTML.Tag) { HTML.Tag tag = (HTML.Tag)key; Object o = htmlAttrSet.getAttribute(tag); - if (o != null && o instanceof AttributeSet) { - translateAttributes(tag, (AttributeSet)o, cssAttrSet); + if (o instanceof AttributeSet as) { + translateAttributes(tag, as, cssAttrSet); } } else if (key instanceof CSS.Attribute) { cssAttrSet.addAttribute(key, htmlAttrSet.getAttribute(key)); diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HRuleView.java b/src/java.desktop/share/classes/javax/swing/text/html/HRuleView.java index bacd81d271c4b93f63e3936e6ccbcdeb8bf1bc9f..885f0b7f2c9d63411d4b0210a5d22c957531db11 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HRuleView.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HRuleView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,16 +72,16 @@ class HRuleView extends View { noshade = (String)eAttr.getAttribute(HTML.Attribute.NOSHADE); Object value = eAttr.getAttribute(HTML.Attribute.SIZE); - if (value != null && (value instanceof String)) { + if (value instanceof String s) { try { - size = Integer.parseInt((String)value); + size = Integer.parseInt(s); } catch (NumberFormatException e) { size = 1; } } value = attr.getAttribute(CSS.Attribute.WIDTH); - if (value != null && (value instanceof CSS.LengthValue)) { - widthValue = (CSS.LengthValue)value; + if (value instanceof CSS.LengthValue lv) { + widthValue = lv; } topMargin = getLength(CSS.Attribute.MARGIN_TOP, attr); bottomMargin = getLength(CSS.Attribute.MARGIN_BOTTOM, attr); diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTML.java b/src/java.desktop/share/classes/javax/swing/text/html/HTML.java index d23b2753580e980855683174849683347188b1b1..a27893d9fccbc241289f82fa3ffd2a6d244e91e2 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTML.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTML.java @@ -43,6 +43,7 @@ import javax.swing.text.StyleContext; * @author Sunita Mani * */ +@SuppressWarnings("doclint:missing") public class HTML { /** diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java b/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java index 00272bc1eaae2cf94b3f3eac527dc2ccb4bad9ce..46d84e3cadcc31da718c032f2d172a431dc3501a 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java @@ -901,8 +901,8 @@ public class HTMLDocument extends DefaultStyledDocument { if (name != null) { Object maps = getProperty(MAP_PROPERTY); - if (maps != null && (maps instanceof Hashtable)) { - return (Map)((Hashtable)maps).get(name); + if (maps instanceof Hashtable hashtable) { + return (Map) hashtable.get(name); } } return null; diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java b/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java index b6b0b789eefc387f92c982e84406c2fe14fa1395..fb507ed0aeaf19d9639e6deb3bf601495ec261fe 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java @@ -216,7 +216,8 @@ import static java.nio.charset.StandardCharsets.ISO_8859_1; * * @author Timothy Prinzing */ -@SuppressWarnings("serial") // Same-version serialization only +@SuppressWarnings({"serial", // Same-version serialization only + "doclint:missing"}) public class HTMLEditorKit extends StyledEditorKit implements Accessible { private JEditorPane theEditor; @@ -455,12 +456,11 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { if (defaultStyles == null) { defaultStyles = new StyleSheet(); appContext.put(DEFAULT_STYLES_KEY, defaultStyles); - try { - InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS); - Reader r = new BufferedReader( - new InputStreamReader(is, ISO_8859_1)); + try (InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS); + InputStreamReader isr = new InputStreamReader(is, ISO_8859_1); + Reader r = new BufferedReader(isr)) + { defaultStyles.loadRules(r, null); - r.close(); } catch (Throwable e) { // on error we simply have no styles... the html // will look mighty wrong but still function. @@ -841,8 +841,8 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { Element elem, AttributeSet attr, int offset, int x, int y) { Object useMap = attr.getAttribute(HTML.Attribute.USEMAP); - if (useMap != null && (useMap instanceof String)) { - Map m = hdoc.getMap((String)useMap); + if (useMap instanceof String s) { + Map m = hdoc.getMap(s); if (m != null && offset < hdoc.getLength()) { Rectangle bounds; TextUI ui = html.getUI(); @@ -1467,12 +1467,8 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) { Container container = getContainer(); - Container parentContainer; - if (container != null - && (container instanceof javax.swing.JEditorPane) - && (parentContainer = container.getParent()) != null - && (parentContainer instanceof javax.swing.JViewport)) { - JViewport viewPort = (JViewport)parentContainer; + if ((container instanceof JEditorPane) + && (container.getParent() instanceof JViewport viewPort)) { if (cachedViewPort != null) { JViewport cachedObject = cachedViewPort.get(); if (cachedObject != null) { @@ -2387,9 +2383,9 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { */ private void doObjectAction(JEditorPane editor, Element elem) { View view = getView(editor, elem); - if (view != null && view instanceof ObjectView) { - Component comp = ((ObjectView)view).getComponent(); - if (comp != null && comp instanceof Accessible) { + if (view instanceof ObjectView objectView) { + Component comp = objectView.getComponent(); + if (comp instanceof Accessible) { AccessibleContext ac = comp.getAccessibleContext(); if (ac != null) { AccessibleAction aa = ac.getAccessibleAction(); @@ -2473,10 +2469,9 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { JEditorPane editor = (JEditorPane)c; Document d = editor.getDocument(); - if (d == null || !(d instanceof HTMLDocument)) { + if (!(d instanceof HTMLDocument doc)) { return; } - HTMLDocument doc = (HTMLDocument)d; ElementIterator ei = new ElementIterator(doc); int currentOffset = editor.getCaretPosition(); diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTMLWriter.java b/src/java.desktop/share/classes/javax/swing/text/html/HTMLWriter.java index a166235d4c205faff1cff053b67d5c352a6a8744..c11214d71e3bce696dcef6900888ad0eabf6ce92 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTMLWriter.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTMLWriter.java @@ -308,9 +308,7 @@ public class HTMLWriter extends AbstractWriter { // If an instance of an UNKNOWN Tag, or an instance of a // tag that is only visible during editing // - if (nameTag != null && endTag != null && - (endTag instanceof String) && - endTag.equals("true")) { + if (nameTag != null && "true".equals(endTag)) { outputEndTag = true; } @@ -732,8 +730,8 @@ public class HTMLWriter extends AbstractWriter { write('<'); write(tag.toString()); Object o = attr.getAttribute(tag); - if (o != null && o instanceof AttributeSet) { - writeAttributes((AttributeSet)o); + if (o instanceof AttributeSet as) { + writeAttributes(as); } write('>'); tags.addElement(tag); @@ -813,8 +811,8 @@ public class HTMLWriter extends AbstractWriter { write('<'); write(t.toString()); Object o = tagValues.elementAt(i); - if (o != null && o instanceof AttributeSet) { - writeAttributes((AttributeSet)o); + if (o instanceof AttributeSet as) { + writeAttributes(as); } write('>'); } diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HiddenTagView.java b/src/java.desktop/share/classes/javax/swing/text/html/HiddenTagView.java index 325bec6b8d6da60d0fd38736af0db71e9cf10daf..25406848bf78b8d1a39d98a57bffa7ffd68f41bd 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HiddenTagView.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HiddenTagView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -271,8 +271,7 @@ class HiddenTagView extends EditableView implements DocumentListener { AttributeSet as = getElement().getAttributes(); if (as != null) { Object end = as.getAttribute(HTML.Attribute.ENDTAG); - if (end != null && (end instanceof String) && - ((String)end).equals("true")) { + if ("true".equals(end)) { return true; } } diff --git a/src/java.desktop/share/classes/javax/swing/text/html/ImageView.java b/src/java.desktop/share/classes/javax/swing/text/html/ImageView.java index 7a27edead658d3712476c1872a78b8a19fa53bdd..6f0a7cbdff41431d09ea34caa4183ed216fb074a 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/ImageView.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/ImageView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1056,7 +1056,7 @@ public class ImageView extends View { * the attribute specified an alt attribute. It overriden a handle of * methods as the text is hardcoded and does not come from the document. */ - private class ImageLabelView extends InlineView { + private static class ImageLabelView extends InlineView { private Segment segment; private Color fg; diff --git a/src/java.desktop/share/classes/javax/swing/text/html/Map.java b/src/java.desktop/share/classes/javax/swing/text/html/Map.java index cc79b5aeb3bbbbfbeaf174888a1bd9b8fd14cf74..c88d4e7495bcfca1f12d63ecf7f3111010412a78 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/Map.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/Map.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -181,12 +181,11 @@ class Map implements Serializable { * from trying to parse one of the numbers null is returned. */ protected static int[] extractCoords(Object stringCoords) { - if (stringCoords == null || !(stringCoords instanceof String)) { + if (!(stringCoords instanceof String s)) { return null; } - StringTokenizer st = new StringTokenizer((String)stringCoords, - ", \t\n\r"); + StringTokenizer st = new StringTokenizer(s, ", \t\n\r"); int[] retValue = null; int numCoords = 0; diff --git a/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java b/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java index 3352e0e79f89b00437e0b2dc9548b4631ffb69cf..9ce35f47ee9eb420129ac6aef21a54da87209670 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java @@ -478,15 +478,12 @@ public class StyleSheet extends StyleContext { * @since 1.3 */ public void importStyleSheet(URL url) { - try { - InputStream is; - - is = url.openStream(); - Reader r = new BufferedReader(new InputStreamReader(is)); + try (InputStream is = url.openStream(); + InputStreamReader isr = new InputStreamReader(is); + Reader r = new BufferedReader(isr)) + { CssParser parser = new CssParser(); parser.parse(url, r, false, true); - r.close(); - is.close(); } catch (Throwable e) { // on error we simply have no styles... the html // will look mighty wrong but still function. @@ -2211,10 +2208,9 @@ public class StyleSheet extends StyleContext { retIndex--; } else if (as.isDefined(HTML.Attribute.VALUE)) { Object value = as.getAttribute(HTML.Attribute.VALUE); - if (value != null && - (value instanceof String)) { + if (value instanceof String s) { try { - int iValue = Integer.parseInt((String)value); + int iValue = Integer.parseInt(s); return retIndex - counter + iValue; } catch (NumberFormatException nfe) {} @@ -2744,8 +2740,7 @@ public class StyleSheet extends StyleContext { kind of conditional behaviour in the stylesheet. **/ - if (o != null && o instanceof AttributeSet) { - AttributeSet attr = (AttributeSet)o; + if (o instanceof AttributeSet attr) { if (attr.getAttribute(HTML.Attribute.HREF) == null) { continue; } diff --git a/src/java.desktop/share/classes/javax/swing/text/html/TableView.java b/src/java.desktop/share/classes/javax/swing/text/html/TableView.java index cbcef3bab4a0f975d37219a3ffcbe84f17cfbd58..c088bf0eb9a773ed0b0a280d39402dc6d95da1db 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/TableView.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/TableView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1691,7 +1691,7 @@ import javax.swing.text.*; * Default view of an html table cell. This needs to be moved * somewhere else. */ - class CellView extends BlockView { + static class CellView extends BlockView { /** * Constructs a TableCell for the given element. diff --git a/src/java.desktop/share/classes/javax/swing/text/html/parser/AttributeList.java b/src/java.desktop/share/classes/javax/swing/text/html/parser/AttributeList.java index 898e9367171889bb4ca7ba99d72d26f623105172..f57a7f2a9174a9c41fe3d1c9a4f3517c4fd5a41a 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/parser/AttributeList.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/parser/AttributeList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,8 @@ import java.io.*; * @author Arthur Van Hoff * */ -@SuppressWarnings("serial") // Same-version serialization only +@SuppressWarnings({"serial", // Same-version serialization only + "doclint:missing"}) public final class AttributeList implements DTDConstants, Serializable { diff --git a/src/java.desktop/share/classes/javax/swing/text/html/parser/Parser.java b/src/java.desktop/share/classes/javax/swing/text/html/parser/Parser.java index 2a59e3b2163431801dddedec3028676b9d159855..fc7cac3cdc17f79882e1ea1602c244a73fc24b75 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/parser/Parser.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/parser/Parser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,6 +75,7 @@ import java.net.URL; * @author Arthur van Hoff * @author Sunita Mani */ +@SuppressWarnings("doclint:missing") public class Parser implements DTDConstants { diff --git a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java index 46a7ce7efb98603f1e83db806e9f91a15ca60b1e..82ee2fffb0bfba218301c135502c1bd076d86fb2 100644 --- a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java +++ b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java @@ -391,7 +391,7 @@ public void writeRTFHeader() updateCharacterAttributes(goat, style, false); basis = style.getResolveParent(); - if (basis != null && basis instanceof Style) { + if (basis instanceof Style) { Integer basedOn = styleTable.get(basis); if (basedOn != null) { writeControlWord("sbasedon", basedOn.intValue()); diff --git a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java index add3a86a8918312ab2e455e8a478a071add07468..9128a71ed01e950d1df384d2040a429fc5b059bd 100644 --- a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java +++ b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java @@ -669,8 +669,7 @@ interface Destination { /** This data-sink class is used to implement ignored destinations * (e.g. {\*\blegga blah blah blah} ) * It accepts all keywords and text but does nothing with them. */ -class DiscardingDestination implements Destination -{ +static class DiscardingDestination implements Destination { public void handleBinaryBlob(byte[] data) { /* Discard binary blobs. */ @@ -1071,7 +1070,7 @@ class StylesheetDestination /** Handles the info group. Currently no info keywords are recognized * so this is a subclass of DiscardingDestination. */ -class InfoDestination +static class InfoDestination extends DiscardingDestination implements Destination { diff --git a/src/java.desktop/share/classes/javax/swing/tree/DefaultMutableTreeNode.java b/src/java.desktop/share/classes/javax/swing/tree/DefaultMutableTreeNode.java index 163e0ec784dbcf90b0dca7f08abdfebc3b1585a1..7735895502ecce78574ffbbf314c928975b9ec26 100644 --- a/src/java.desktop/share/classes/javax/swing/tree/DefaultMutableTreeNode.java +++ b/src/java.desktop/share/classes/javax/swing/tree/DefaultMutableTreeNode.java @@ -1297,8 +1297,8 @@ public class DefaultMutableTreeNode implements Cloneable, Object[] tValues; s.defaultWriteObject(); - // Save the userObject, if its Serializable. - if(userObject != null && userObject instanceof Serializable) { + // Save the userObject, if it's Serializable. + if (userObject instanceof Serializable) { tValues = new Object[2]; tValues[0] = "userObject"; tValues[1] = userObject; @@ -1330,7 +1330,7 @@ public class DefaultMutableTreeNode implements Cloneable, userObject = tValues[1]; } - private final class PreorderEnumeration implements Enumeration { + private static final class PreorderEnumeration implements Enumeration { private final Stack> stack = new Stack<>(); public PreorderEnumeration(TreeNode rootNode) { @@ -1362,7 +1362,7 @@ public class DefaultMutableTreeNode implements Cloneable, - final class PostorderEnumeration implements Enumeration { + static final class PostorderEnumeration implements Enumeration { protected TreeNode root; protected Enumeration children; protected Enumeration subtree; @@ -1398,7 +1398,7 @@ public class DefaultMutableTreeNode implements Cloneable, - final class BreadthFirstEnumeration implements Enumeration { + static final class BreadthFirstEnumeration implements Enumeration { protected Queue queue; public BreadthFirstEnumeration(TreeNode rootNode) { @@ -1430,11 +1430,11 @@ public class DefaultMutableTreeNode implements Cloneable, // A simple queue with a linked list data structure. - final class Queue { + static final class Queue { QNode head; // null if empty QNode tail; - final class QNode { + static final class QNode { public Object object; public QNode next; // null if end public QNode(Object object, QNode next) { @@ -1486,7 +1486,7 @@ public class DefaultMutableTreeNode implements Cloneable, - final class PathBetweenNodesEnumeration implements Enumeration { + static final class PathBetweenNodesEnumeration implements Enumeration { protected Stack stack; public PathBetweenNodesEnumeration(TreeNode ancestor, diff --git a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeModel.java b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeModel.java index 6bc1478309862f4eea0cc848aebf28ebb80724ce..6d2a692c0436f1a28c4b3130d76b81e3f837dd88 100644 --- a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeModel.java +++ b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeModel.java @@ -690,8 +690,8 @@ public class DefaultTreeModel implements Serializable, TreeModel { Vector values = new Vector(); s.defaultWriteObject(); - // Save the root, if its Serializable. - if(root != null && root instanceof Serializable) { + // Save the root, if it's Serializable. + if (root instanceof Serializable) { values.addElement("root"); values.addElement(root); } diff --git a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java index 2c592f24d2b51b6ff184ccc4ea3e66e040937400..e1bdc4fc94b3952bdf3856f43dc80d3979e1361c 100644 --- a/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java +++ b/src/java.desktop/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java @@ -1217,7 +1217,7 @@ public class DefaultTreeSelectionModel implements Cloneable, Serializable, TreeS s.defaultWriteObject(); // Save the rowMapper, if it implements Serializable - if(rowMapper != null && rowMapper instanceof Serializable) { + if (rowMapper instanceof Serializable) { tValues = new Object[2]; tValues[0] = "rowMapper"; tValues[1] = rowMapper; diff --git a/src/java.desktop/share/classes/javax/swing/undo/UndoableEditSupport.java b/src/java.desktop/share/classes/javax/swing/undo/UndoableEditSupport.java index decd6afb9a044bc5e9868202ce1411de1bba79c3..5646222ecb11f1ce7ba8b2df4c2075bab49bb94c 100644 --- a/src/java.desktop/share/classes/javax/swing/undo/UndoableEditSupport.java +++ b/src/java.desktop/share/classes/javax/swing/undo/UndoableEditSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,6 +33,7 @@ import java.util.*; * * @author Ray Ryan */ +@SuppressWarnings("doclint:missing") public class UndoableEditSupport { /** * The update level. diff --git a/src/java.desktop/share/classes/sun/awt/DebugSettings.java b/src/java.desktop/share/classes/sun/awt/DebugSettings.java index 6883fda1b2684aa463287c9264d48ff1164cd872..9d89b6519b7ed81ca37a87a3f4862b2c62fb9c72 100644 --- a/src/java.desktop/share/classes/sun/awt/DebugSettings.java +++ b/src/java.desktop/share/classes/sun/awt/DebugSettings.java @@ -173,9 +173,9 @@ public final class DebugSettings { File propFile = new File(propPath); try { println("Reading debug settings from '" + propFile.getCanonicalPath() + "'..."); - FileInputStream fin = new FileInputStream(propFile); - props.load(fin); - fin.close(); + try (FileInputStream fin = new FileInputStream(propFile)) { + props.load(fin); + } } catch ( FileNotFoundException fne ) { println("Did not find settings file."); } catch ( IOException ioe ) { diff --git a/src/java.desktop/share/classes/sun/awt/FontConfiguration.java b/src/java.desktop/share/classes/sun/awt/FontConfiguration.java index 782b9d25641cc2c140eba336c5d86841bda03a4a..e2e7ab3e5ae1bf488d9728a6c05c7e35b7e40e60 100644 --- a/src/java.desktop/share/classes/sun/awt/FontConfiguration.java +++ b/src/java.desktop/share/classes/sun/awt/FontConfiguration.java @@ -48,7 +48,6 @@ import java.util.Set; import java.util.Vector; import sun.font.CompositeFontDescriptor; import sun.font.SunFontManager; -import sun.font.FontManagerFactory; import sun.font.FontUtilities; import sun.util.logging.PlatformLogger; @@ -204,14 +203,12 @@ public abstract class FontConfiguration { getInstalledFallbackFonts(javaLib); if (f != null) { - try { - FileInputStream in = new FileInputStream(f.getPath()); + try (FileInputStream in = new FileInputStream(f.getPath())) { if (isProperties) { loadProperties(in); } else { loadBinary(in); } - in.close(); if (FontUtilities.debugFonts()) { logger.config("Read logical font configuration from " + f); } diff --git a/src/java.desktop/share/classes/sun/awt/PlatformFont.java b/src/java.desktop/share/classes/sun/awt/PlatformFont.java index aa175d4786c5003a0c67101c758619706ea4e48b..b1a9b7bc7ca4271460e026cde39b936ae512594c 100644 --- a/src/java.desktop/share/classes/sun/awt/PlatformFont.java +++ b/src/java.desktop/share/classes/sun/awt/PlatformFont.java @@ -428,8 +428,7 @@ public abstract class PlatformFont implements FontPeer { */ private static native void initIDs(); - class PlatformFontCache - { + static class PlatformFontCache { char uniChar; FontDescriptor fontDescriptor; ByteBuffer bb = ByteBuffer.allocate(4); diff --git a/src/java.desktop/share/classes/sun/awt/geom/Curve.java b/src/java.desktop/share/classes/sun/awt/geom/Curve.java index 0396ffc5d03998f65d818bb6d9781169458e467f..a59793d434988a7d95e2abfc2234693a6b31d686 100644 --- a/src/java.desktop/share/classes/sun/awt/geom/Curve.java +++ b/src/java.desktop/share/classes/sun/awt/geom/Curve.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -731,12 +731,12 @@ public abstract class Curve { public static int orderof(double x1, double x2) { if (x1 < x2) { - return -1; - } - if (x1 > x2) { - return 1; - } - return 0; + return -1; + } + if (x1 > x2) { + return 1; + } + return 0; } public static long signeddiffbits(double y1, double y2) { diff --git a/src/java.desktop/share/classes/sun/awt/im/InputContext.java b/src/java.desktop/share/classes/sun/awt/im/InputContext.java index 3ca1f6cedb988d9e9caff5905e526c3c0e9531ce..c35d17bfae3611114bb36694888975065cce65c2 100644 --- a/src/java.desktop/share/classes/sun/awt/im/InputContext.java +++ b/src/java.desktop/share/classes/sun/awt/im/InputContext.java @@ -790,8 +790,8 @@ public class InputContext extends java.awt.im.InputContext */ public void disableNativeIM() { InputMethod inputMethod = getInputMethod(); - if (inputMethod != null && inputMethod instanceof InputMethodAdapter) { - ((InputMethodAdapter)inputMethod).stopListening(); + if (inputMethod instanceof InputMethodAdapter adapter) { + adapter.stopListening(); } } diff --git a/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java b/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java index dd0d43bcf460dc8e6988b6168b07323ce229d431..0c375a900a0aae852f1e1edbc5a5e60319b357ff 100644 --- a/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java +++ b/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java @@ -181,9 +181,7 @@ public abstract class ShellFolder extends File { * @see #compareTo(Object) */ public int compareTo(File file2) { - if (file2 == null || !(file2 instanceof ShellFolder) - || ((file2 instanceof ShellFolder) && ((ShellFolder)file2).isFileSystem())) { - + if (!(file2 instanceof ShellFolder sf) || sf.isFileSystem()) { if (isFileSystem()) { return super.compareTo(file2); } else { diff --git a/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java b/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java index 8f1bbdc4714d178fc47645d576c4f0502685be28..98f93cc3ec7027fa9942a230d7889addeb9ea0df 100644 --- a/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java +++ b/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -203,7 +203,7 @@ public class IdentityArrayList extends AbstractList * Returns {@code true} if this list contains the specified element. * More formally, returns {@code true} if and only if this list contains * at least one element {@code e} such that - * {@code Objects.equals(o, e)}. + * {@code o == e}. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element @@ -216,8 +216,12 @@ public class IdentityArrayList extends AbstractList * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index {@code i} such that - * {@code Objects.equals(o, get(i))}, + * {@code get(i) == o}, * or -1 if there is no such index. + * + * @param o element to search for + * @return the index of the first occurrence of the specified element in + * this list, or -1 if this list does not contain the element */ public int indexOf(Object o) { for (int i = 0; i < size; i++) { @@ -232,8 +236,12 @@ public class IdentityArrayList extends AbstractList * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index {@code i} such that - * {@code Objects.equals(o, get(i))}, + * {@code get(i) == o}, * or -1 if there is no such index. + * + * @param o element to search for + * @return the index of the last occurrence of the specified element in + * this list, or -1 if this list does not contain the element */ public int lastIndexOf(Object o) { for (int i = size-1; i >= 0; i--) { @@ -390,9 +398,9 @@ public class IdentityArrayList extends AbstractList /** * Removes the first occurrence of the specified element from this list, - * if it is present. If the list does not contain the element, it is + * if it is present. If this list does not contain the element, the list is * unchanged. More formally, removes the element with the lowest index - * {@code i} such that {@code Objects.equals(o, get(i))} + * {@code i} such that {@code get(i) == o} * (if such an element exists). Returns {@code true} if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). diff --git a/src/java.desktop/share/classes/sun/awt/util/IdentityLinkedList.java b/src/java.desktop/share/classes/sun/awt/util/IdentityLinkedList.java index 21474bafcfdb5aed89b172cb09f236180994d41a..fef09665bc0788650a1685a108042c3b8f50e539 100644 --- a/src/java.desktop/share/classes/sun/awt/util/IdentityLinkedList.java +++ b/src/java.desktop/share/classes/sun/awt/util/IdentityLinkedList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -183,7 +183,7 @@ public class IdentityLinkedList * Returns {@code true} if this list contains the specified element. * More formally, returns {@code true} if and only if this list contains * at least one element {@code e} such that - * {@code Objects.equals(o, e)}. + * {@code o == e}. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element @@ -218,7 +218,7 @@ public class IdentityLinkedList * Removes the first occurrence of the specified element from this list, * if it is present. If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index - * {@code i} such that {@code get(i)==o} + * {@code i} such that {@code get(i) == o} * (if such an element exists). Returns {@code true} if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). @@ -389,7 +389,7 @@ public class IdentityLinkedList * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index {@code i} such that - * {@code get(i)==o}, + * {@code get(i) == o}, * or -1 if there is no such index. * * @param o element to search for @@ -411,7 +411,7 @@ public class IdentityLinkedList * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index {@code i} such that - * {@code get(i)==o}, + * {@code get(i) == o}, * or -1 if there is no such index. * * @param o element to search for diff --git a/src/java.desktop/share/classes/sun/font/AttributeValues.java b/src/java.desktop/share/classes/sun/font/AttributeValues.java index 910195a2a9eb41c70a7956e744850951e31b83e3..6b3c0aaf4e29b4be369900bd192f44f2f5903c48 100644 --- a/src/java.desktop/share/classes/sun/font/AttributeValues.java +++ b/src/java.desktop/share/classes/sun/font/AttributeValues.java @@ -764,8 +764,8 @@ public final class AttributeValues implements Cloneable { return ((AttributeMap)map).getValues().justification; } Object obj = map.get(TextAttribute.JUSTIFICATION); - if (obj != null && obj instanceof Number) { - return max(0, min(1, ((Number)obj).floatValue())); + if (obj instanceof Number number) { + return max(0, min(1, number.floatValue())); } } return DEFAULT.justification; @@ -778,8 +778,8 @@ public final class AttributeValues implements Cloneable { return ((AttributeMap)map).getValues().numericShaping; } Object obj = map.get(TextAttribute.NUMERIC_SHAPING); - if (obj != null && obj instanceof NumericShaper) { - return (NumericShaper)obj; + if (obj instanceof NumericShaper shaper) { + return shaper; } } return DEFAULT.numericShaping; diff --git a/src/java.desktop/share/classes/sun/font/FontUtilities.java b/src/java.desktop/share/classes/sun/font/FontUtilities.java index 550cdcce3cf3f38b5779477ae6819fb1027a025a..c4f8c317a92b8f3c813a58e331e3ef1c5098bceb 100644 --- a/src/java.desktop/share/classes/sun/font/FontUtilities.java +++ b/src/java.desktop/share/classes/sun/font/FontUtilities.java @@ -413,10 +413,9 @@ public final class FontUtilities { FontManager fm = FontManagerFactory.getInstance(); Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK); // Should never be null, but MACOSX fonts are not CompositeFonts - if (dialog == null || !(dialog instanceof CompositeFont)) { + if (!(dialog instanceof CompositeFont dialog2D)) { return fuir; } - CompositeFont dialog2D = (CompositeFont)dialog; PhysicalFont physicalFont = (PhysicalFont)font2D; ConcurrentHashMap compMap = compMapRef.get(); if (compMap == null) { // Its been collected. diff --git a/src/java.desktop/share/classes/sun/font/SunFontManager.java b/src/java.desktop/share/classes/sun/font/SunFontManager.java index 1942aacd99714f5cd24623dee00ee36af4e18ce4..4f36498f6e2718fee47ee1b067a8a92612e81db0 100644 --- a/src/java.desktop/share/classes/sun/font/SunFontManager.java +++ b/src/java.desktop/share/classes/sun/font/SunFontManager.java @@ -230,12 +230,6 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { /* Used to indicate required return type from toArray(..); */ private static String[] STR_ARRAY = new String[0]; - /** - * Deprecated, unsupported hack - actually invokes a bug! - * Left in for a customer, don't remove. - */ - private boolean usePlatformFontMetrics = false; - /** * Returns the global SunFontManager instance. This is similar to * {@link FontManagerFactory#getInstance()} but it returns a @@ -454,22 +448,6 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { } }); - boolean platformFont = AccessController.doPrivileged( - new PrivilegedAction() { - public Boolean run() { - String prop = System.getProperty("java2d.font.usePlatformFont"); - String env = System.getenv("JAVA2D_USEPLATFORMFONT"); - return "true".equals(prop) || env != null; - } - }); - - if (platformFont) { - usePlatformFontMetrics = true; - System.out.println("Enabling platform font metrics for win32. This is an unsupported option."); - System.out.println("This yields incorrect composite font metrics as reported by 1.1.x releases."); - System.out.println("It is appropriate only for use by applications which do not use any Java 2"); - System.out.println("functionality. This property will be removed in a later release."); - } } public Font2DHandle getNewComposite(String family, int style, @@ -2188,15 +2166,6 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { } } - /* - * Workaround for apps which are dependent on a font metrics bug - * in JDK 1.1. This is an unsupported win32 private setting. - * Left in for a customer - do not remove. - */ - public boolean usePlatformFontMetrics() { - return usePlatformFontMetrics; - } - public int getNumFonts() { return physicalFonts.size()+maxCompFont; } diff --git a/src/java.desktop/share/classes/sun/java2d/Spans.java b/src/java.desktop/share/classes/sun/java2d/Spans.java index c7be5d5ab360eaa0ef3711d03bc968a0251a8eba..98d2aaf9e99d5e003f5f9800f3a74485b7cf18ab 100644 --- a/src/java.desktop/share/classes/sun/java2d/Spans.java +++ b/src/java.desktop/share/classes/sun/java2d/Spans.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -315,6 +315,7 @@ public class Spans { * position. The end position is ignored * in this ranking. */ + @Override public int compareTo(Span otherSpan) { float otherStart = otherSpan.getStart(); int result; diff --git a/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java b/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java index 15db79d69d2f95219f648049ba5459949c55bef8..b5b5225938b3a441dd24f0b125751933f2963f41 100644 --- a/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java +++ b/src/java.desktop/share/classes/sun/java2d/SunGraphics2D.java @@ -3656,7 +3656,7 @@ public final class SunGraphics2D * enough to know that if our override is empty then it should not * mark us as finalizeable. */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void finalize() { // DO NOT REMOVE THIS METHOD } diff --git a/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java b/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java index 8198932bacda23bd828be84e42d9ae4a0199c5a2..939a583977ebd70d8f07706d0f708bec5b5f204a 100644 --- a/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java +++ b/src/java.desktop/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java @@ -52,7 +52,7 @@ import static sun.java2d.cmm.lcms.LCMSImageLayout.ImageLayoutException; final class LCMSTransform implements ColorTransform { - private final static class NativeTransform { + private static final class NativeTransform { private long ID; private int inFormatter; private boolean isInIntPacked; diff --git a/src/java.desktop/share/classes/sun/java2d/loops/DrawGlyphListColor.java b/src/java.desktop/share/classes/sun/java2d/loops/DrawGlyphListColor.java index 0950e799dd3d67307c951c9b13f0b1cfb5d786da..55ceaf4ce4e3b143c2fc883b97adbbc8588c9e26 100644 --- a/src/java.desktop/share/classes/sun/java2d/loops/DrawGlyphListColor.java +++ b/src/java.desktop/share/classes/sun/java2d/loops/DrawGlyphListColor.java @@ -37,10 +37,10 @@ import java.awt.*; */ public class DrawGlyphListColor extends GraphicsPrimitive { - public final static String methodSignature = + public static final String methodSignature = "DrawGlyphListColor(...)".toString(); - public final static int primTypeID = makePrimTypeID(); + public static final int primTypeID = makePrimTypeID(); public static DrawGlyphListColor locate(SurfaceType srctype, CompositeType comptype, diff --git a/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveMgr.java b/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveMgr.java index dadfbeb540c0d1ca4d02fa20db6203dd98fd1b86..8c2fb00d7b7abd7784bc87092872b8d4534f24a6 100644 --- a/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveMgr.java +++ b/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveMgr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,7 +79,7 @@ public final class GraphicsPrimitiveMgr { int id1 = o1.getUniqueID(); int id2 = o2.getUniqueID(); - return (id1 == id2 ? 0 : (id1 < id2 ? -1 : 1)); + return Integer.compare(id1, id2); } }; @@ -88,7 +88,7 @@ public final class GraphicsPrimitiveMgr { int id1 = ((GraphicsPrimitive) o1).getUniqueID(); int id2 = ((PrimitiveSpec) o2).uniqueID; - return (id1 == id2 ? 0 : (id1 < id2 ? -1 : 1)); + return Integer.compare(id1, id2); } }; diff --git a/src/java.desktop/share/classes/sun/java2d/loops/RenderCache.java b/src/java.desktop/share/classes/sun/java2d/loops/RenderCache.java index 6dbedb0a57384f977786a11d7c462bda27fd639c..7a9c2d59eb8eaf9e65f5e02be12b874c04e09cba 100644 --- a/src/java.desktop/share/classes/sun/java2d/loops/RenderCache.java +++ b/src/java.desktop/share/classes/sun/java2d/loops/RenderCache.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ package sun.java2d.loops; public final class RenderCache { - final class Entry { + static final class Entry { private SurfaceType src; private CompositeType comp; private SurfaceType dst; diff --git a/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderer.java b/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderer.java index 95b15fdcb123a1710b5812ca45184b8132677061..a933dacfb0d024d757fb8bc339024f57a224bae7 100644 --- a/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderer.java +++ b/src/java.desktop/share/classes/sun/java2d/opengl/OGLRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -108,7 +108,7 @@ class OGLRenderer extends BufferedRenderPipe { return new Tracer(this); } - private class Tracer extends OGLRenderer { + private static class Tracer extends OGLRenderer { private OGLRenderer oglr; Tracer(OGLRenderer oglr) { super(oglr.rq); diff --git a/src/java.desktop/share/classes/sun/java2d/pipe/GeneralCompositePipe.java b/src/java.desktop/share/classes/sun/java2d/pipe/GeneralCompositePipe.java index 2e5ec8b2d0c2ca4148b0c3014b2280286bacc27f..564093394bd5cecc756106a367ec6338b5d6bc7a 100644 --- a/src/java.desktop/share/classes/sun/java2d/pipe/GeneralCompositePipe.java +++ b/src/java.desktop/share/classes/sun/java2d/pipe/GeneralCompositePipe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ import sun.java2d.loops.MaskBlit; import sun.java2d.loops.CompositeType; public class GeneralCompositePipe implements CompositePipe { - class TileContext { + static class TileContext { SunGraphics2D sunG2D; PaintContext paintCtxt; CompositeContext compCtxt; diff --git a/src/java.desktop/share/classes/sun/java2d/pipe/SpanClipRenderer.java b/src/java.desktop/share/classes/sun/java2d/pipe/SpanClipRenderer.java index 8413fb8bceddb2d6b703307c432b169a3679fb04..62d1f119f3348fec0c24cfb10dd901a86011ca97 100644 --- a/src/java.desktop/share/classes/sun/java2d/pipe/SpanClipRenderer.java +++ b/src/java.desktop/share/classes/sun/java2d/pipe/SpanClipRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public class SpanClipRenderer implements CompositePipe outpipe = pipe; } - class SCRcontext { + static class SCRcontext { RegionIterator iterator; Object outcontext; int[] band; diff --git a/src/java.desktop/share/classes/sun/print/PSPrinterJob.java b/src/java.desktop/share/classes/sun/print/PSPrinterJob.java index e90b0b586c82c63f49d9e8d5260f202df71366a4..e0252aad226664ad44f2f2b97214ff21eb091f17 100644 --- a/src/java.desktop/share/classes/sun/print/PSPrinterJob.java +++ b/src/java.desktop/share/classes/sun/print/PSPrinterJob.java @@ -393,11 +393,12 @@ public class PSPrinterJob extends RasterPrinterJob { } // Load property file - InputStream in = - new BufferedInputStream(new FileInputStream(f.getPath())); Properties props = new Properties(); - props.load(in); - in.close(); + try (FileInputStream is = new FileInputStream(f.getPath()); + BufferedInputStream bis = new BufferedInputStream(is)) + { + props.load(bis); + } return props; } catch (Exception e){ return (Properties)null; diff --git a/src/java.desktop/share/classes/sun/print/PSStreamPrintService.java b/src/java.desktop/share/classes/sun/print/PSStreamPrintService.java index d221522940593e66ad9d26fd8e72f40faf9b64d9..62a28e0505261c016118840db40be102a7838136 100644 --- a/src/java.desktop/share/classes/sun/print/PSStreamPrintService.java +++ b/src/java.desktop/share/classes/sun/print/PSStreamPrintService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -320,8 +320,7 @@ public class PSStreamPrintService extends StreamPrintService MediaSize mediaSize = (MediaSize)attributes.get(MediaSize.class); if (mediaSize == null) { Media media = (Media)attributes.get(Media.class); - if (media != null && media instanceof MediaSizeName) { - MediaSizeName msn = (MediaSizeName)media; + if (media instanceof MediaSizeName msn) { mediaSize = MediaSize.getMediaSizeForName(msn); } } diff --git a/src/java.desktop/share/classes/sun/print/PathGraphics.java b/src/java.desktop/share/classes/sun/print/PathGraphics.java index 1fbd7fa68d6c232635f2730abef2a1835387e47d..2235f82aab595928375678e8950b302c73f4a78c 100644 --- a/src/java.desktop/share/classes/sun/print/PathGraphics.java +++ b/src/java.desktop/share/classes/sun/print/PathGraphics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -895,8 +895,8 @@ public abstract class PathGraphics extends ProxyGraphics2D { */ Map map = font.getAttributes(); Object o = map.get(TextAttribute.TRACKING); - boolean tracking = o != null && (o instanceof Number) && - (((Number)o).floatValue() != 0f); + boolean tracking = (o instanceof Number n) && + (n.floatValue() != 0f); if (tracking) { noPositionAdjustments = false; diff --git a/src/java.desktop/share/classes/sun/print/PeekGraphics.java b/src/java.desktop/share/classes/sun/print/PeekGraphics.java index c400ad59ca2b59b3f8da2ca70b72f469b355ae5c..b5eabc847739d312604b46d002b96f97af76e925 100644 --- a/src/java.desktop/share/classes/sun/print/PeekGraphics.java +++ b/src/java.desktop/share/classes/sun/print/PeekGraphics.java @@ -1336,7 +1336,7 @@ public class PeekGraphics extends Graphics2D /** * Empty finalizer as no clean up needed here. */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void finalize() { } diff --git a/src/java.desktop/share/classes/sun/print/PrintJob2D.java b/src/java.desktop/share/classes/sun/print/PrintJob2D.java index dcc238b4a53cc50977bbb35f9a0485a836e3a294..9083bd3e26965be3ba66460049c4f645a5dc2b7b 100644 --- a/src/java.desktop/share/classes/sun/print/PrintJob2D.java +++ b/src/java.desktop/share/classes/sun/print/PrintJob2D.java @@ -54,7 +54,6 @@ import java.util.Properties; import javax.print.PrintService; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; -import javax.print.attribute.ResolutionSyntax; import javax.print.attribute.Size2DSyntax; import javax.print.attribute.standard.Chromaticity; import javax.print.attribute.standard.Copies; @@ -64,7 +63,6 @@ import javax.print.attribute.standard.DialogOwner; import javax.print.attribute.standard.JobName; import javax.print.attribute.standard.MediaSize; import javax.print.attribute.standard.PrintQuality; -import javax.print.attribute.standard.PrinterResolution; import javax.print.attribute.standard.SheetCollate; import javax.print.attribute.standard.Sides; import javax.print.attribute.standard.Media; @@ -72,8 +70,6 @@ import javax.print.attribute.standard.OrientationRequested; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.PageRanges; -import sun.print.SunPageSelection; -import sun.print.SunMinMaxPage; /** * A class which initiates and executes a print job using @@ -454,8 +450,8 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { Media media = (Media)attributes.get(Media.class); MediaSize mediaSize = null; - if (media != null && media instanceof MediaSizeName) { - mediaSize = MediaSize.getMediaSizeForName((MediaSizeName)media); + if (media instanceof MediaSizeName msn) { + mediaSize = MediaSize.getMediaSizeForName(msn); } Paper p = pageFormat.getPaper(); @@ -594,9 +590,9 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { pageAttributes.setPrintQuality(PrintQualityType.NORMAL); } - Media msn = (Media)attributes.get(Media.class); - if (msn != null && msn instanceof MediaSizeName) { - MediaType mType = unMapMedia((MediaSizeName)msn); + Media media = (Media)attributes.get(Media.class); + if (media instanceof MediaSizeName msn) { + MediaType mType = unMapMedia(msn); if (mType != null) { pageAttributes.setMedia(mType); @@ -944,7 +940,7 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { * Ends this print job once it is no longer referenced. * @see #end */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void finalize() { end(); } @@ -1033,7 +1029,7 @@ public class PrintJob2D extends PrintJob implements Printable, Runnable { graphicsDrawn.close(); } - private class MessageQ { + private static class MessageQ { private String qid="noname"; diff --git a/src/java.desktop/share/classes/sun/print/ProxyGraphics.java b/src/java.desktop/share/classes/sun/print/ProxyGraphics.java index 124a7a487f62d1f789119376d24271526d732ea8..c6c0615c3439d8b6fed7d7aad8d00c997bac87e4 100644 --- a/src/java.desktop/share/classes/sun/print/ProxyGraphics.java +++ b/src/java.desktop/share/classes/sun/print/ProxyGraphics.java @@ -1099,7 +1099,7 @@ public class ProxyGraphics extends Graphics { /** * Empty finalizer as no clean up needed here. */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void finalize() { } diff --git a/src/java.desktop/share/classes/sun/print/ProxyGraphics2D.java b/src/java.desktop/share/classes/sun/print/ProxyGraphics2D.java index fc1c0e768108fc602ed53e27f58a997ac4d04373..c05ba9a6188e4bf2924b343a62882e2514956828 100644 --- a/src/java.desktop/share/classes/sun/print/ProxyGraphics2D.java +++ b/src/java.desktop/share/classes/sun/print/ProxyGraphics2D.java @@ -1264,7 +1264,7 @@ public class ProxyGraphics2D extends Graphics2D implements PrinterGraphics { /** * Empty finalizer as no clean up needed here. */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") public void finalize() { } diff --git a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java index 075bdefb1458e50fffde07395a4de08e263106c1..6ceeb48df85279161c11f8fb6327c4147a8059ef 100644 --- a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java +++ b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java @@ -28,8 +28,6 @@ package sun.print; import java.io.FilePermission; import java.awt.Color; -import java.awt.Dialog; -import java.awt.Frame; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; @@ -304,7 +302,7 @@ public abstract class RasterPrinterJob extends PrinterJob { * The redrawing code needs to look at sx, sy to calculate the scale * to device resolution. */ - private class GraphicsState { + private static class GraphicsState { Rectangle2D region; // Area of page to repaint Shape theClip; // image drawing clip. AffineTransform theTransform; // to transform clip to dev coords. diff --git a/src/java.desktop/share/classes/sun/print/ServiceDialog.java b/src/java.desktop/share/classes/sun/print/ServiceDialog.java index c294ba617eb639e7b3f462053b3b793f045fbeda..7167ba1884f1656adbb004bab7c3dc6a5d37174f 100644 --- a/src/java.desktop/share/classes/sun/print/ServiceDialog.java +++ b/src/java.desktop/share/classes/sun/print/ServiceDialog.java @@ -26,7 +26,6 @@ package sun.print; import java.awt.BorderLayout; -import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; @@ -35,9 +34,7 @@ import java.awt.Frame; import java.awt.GraphicsConfiguration; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; -import java.awt.GridLayout; import java.awt.Insets; -import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -61,13 +58,9 @@ import javax.print.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; import javax.swing.*; -import javax.swing.border.Border; import javax.swing.border.EmptyBorder; -import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.text.NumberFormatter; @@ -1620,11 +1613,10 @@ public class ServiceDialog extends JDialog implements ActionListener { MediaSize mediaSize = null; Media media = (Media)asCurrent.get(Media.class); - if (media == null || !(media instanceof MediaSizeName)) { + if (!(media instanceof MediaSizeName)) { media = (Media)psCurrent.getDefaultAttributeValue(Media.class); } - if (media != null && (media instanceof MediaSizeName)) { - MediaSizeName msn = (MediaSizeName)media; + if (media instanceof MediaSizeName msn) { mediaSize = MediaSize.getMediaSizeForName(msn); } if (mediaSize == null) { @@ -1706,11 +1698,10 @@ public class ServiceDialog extends JDialog implements ActionListener { MediaSize mediaSize = null; Media media = (Media)asCurrent.get(Media.class); - if (media == null || !(media instanceof MediaSizeName)) { + if (!(media instanceof MediaSizeName)) { media = (Media)psCurrent.getDefaultAttributeValue(Media.class); } - if (media != null && (media instanceof MediaSizeName)) { - MediaSizeName msn = (MediaSizeName)media; + if (media instanceof MediaSizeName msn) { mediaSize = MediaSize.getMediaSizeForName(msn); } if (mediaSize == null) { @@ -2835,7 +2826,7 @@ public class ServiceDialog extends JDialog implements ActionListener { * placed to the left of the radio button. */ @SuppressWarnings("serial") // Superclass is not serializable across versions - private class IconRadioButton extends JPanel { + private static class IconRadioButton extends JPanel { private JRadioButton rb; private JLabel lbl; @@ -2889,7 +2880,7 @@ public class ServiceDialog extends JDialog implements ActionListener { * user selects a file that already exists. */ @SuppressWarnings("serial") // JDK implementation class - private class ValidatingFileChooser extends JFileChooser { + private static class ValidatingFileChooser extends JFileChooser { public void approveSelection() { File selected = getSelectedFile(); boolean exists; diff --git a/src/java.desktop/share/classes/sun/swing/DefaultLookup.java b/src/java.desktop/share/classes/sun/swing/DefaultLookup.java index 51949f2c626e33f2722d0ee742467903fe5fb8dd..cf3919d9d97177fee317ac877cb3a29e74471af6 100644 --- a/src/java.desktop/share/classes/sun/swing/DefaultLookup.java +++ b/src/java.desktop/share/classes/sun/swing/DefaultLookup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -132,10 +132,10 @@ public class DefaultLookup { int defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Number)) { - return defaultValue; + if (iValue instanceof Number number) { + return number.intValue(); } - return ((Number)iValue).intValue(); + return defaultValue; } public static int getInt(JComponent c, ComponentUI ui, String key) { @@ -146,10 +146,10 @@ public class DefaultLookup { Insets defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Insets)) { - return defaultValue; + if (iValue instanceof Insets insets) { + return insets; } - return (Insets)iValue; + return defaultValue; } public static Insets getInsets(JComponent c, ComponentUI ui, String key) { @@ -160,10 +160,10 @@ public class DefaultLookup { boolean defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Boolean)) { - return defaultValue; + if (iValue instanceof Boolean b) { + return b; } - return ((Boolean)iValue).booleanValue(); + return defaultValue; } public static boolean getBoolean(JComponent c, ComponentUI ui, String key) { @@ -174,10 +174,10 @@ public class DefaultLookup { Color defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Color)) { - return defaultValue; + if (iValue instanceof Color color) { + return color; } - return (Color)iValue; + return defaultValue; } public static Color getColor(JComponent c, ComponentUI ui, String key) { @@ -187,10 +187,10 @@ public class DefaultLookup { public static Icon getIcon(JComponent c, ComponentUI ui, String key, Icon defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Icon)) { - return defaultValue; + if (iValue instanceof Icon icon) { + return icon; } - return (Icon)iValue; + return defaultValue; } public static Icon getIcon(JComponent c, ComponentUI ui, String key) { @@ -200,10 +200,10 @@ public class DefaultLookup { public static Border getBorder(JComponent c, ComponentUI ui, String key, Border defaultValue) { Object iValue = get(c, ui, key); - if (iValue == null || !(iValue instanceof Border)) { - return defaultValue; + if (iValue instanceof Border border) { + return border; } - return (Border)iValue; + return defaultValue; } public static Border getBorder(JComponent c, ComponentUI ui, String key) { diff --git a/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java b/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java index ff2898d0f72ba297cb64042cd52df820895b8579..6859fb0bab5612c4eada0dd87c466edfd477e635 100644 --- a/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java +++ b/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -378,10 +378,10 @@ public class MenuItemLayoutHelper { if (miParent != null) { value = miParent.getClientProperty(propertyName); } - if ((value == null) || !(value instanceof Integer)) { - value = 0; + if (value instanceof Integer intValue) { + return intValue; } - return (Integer) value; + return 0; } public static boolean isColumnLayout(boolean isLeftToRight, diff --git a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java index e746dad6e7ee07554c582b9a140f2d4d214039c6..5b8cf120e1389cf989934e6a679b1816931c518b 100644 --- a/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java +++ b/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java @@ -520,7 +520,7 @@ public class SwingUtilities2 { * it to fit in the screen width. This distributes the spacing * more evenly than directly laying out to the screen advances. */ - String trimmedText = trimTrailingSpaces(text); + String trimmedText = text.stripTrailing(); if (!trimmedText.isEmpty()) { float screenWidth = (float) g2d.getFont().getStringBounds (trimmedText, getFontRenderContext(c)).getWidth(); @@ -866,7 +866,7 @@ public class SwingUtilities2 { String text = new String(data, offset, length); TextLayout layout = new TextLayout(text, g2d.getFont(), deviceFontRenderContext); - String trimmedText = trimTrailingSpaces(text); + String trimmedText = text.stripTrailing(); if (!trimmedText.isEmpty()) { float screenWidth = (float)g2d.getFont(). getStringBounds(trimmedText, frc).getWidth(); @@ -1321,14 +1321,6 @@ public class SwingUtilities2 { return (g instanceof PrinterGraphics || g instanceof PrintGraphics); } - private static String trimTrailingSpaces(String s) { - int i = s.length() - 1; - while(i >= 0 && Character.isWhitespace(s.charAt(i))) { - i--; - } - return s.substring(0, i + 1); - } - private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator (AttributedCharacterIterator iterator) { int curIdx = iterator.getIndex(); diff --git a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java index 9760dad86c510cebc99390c5a416f6cb48618741..b190163ed6aa8694e6714d523aaca9c0c1fdd6e5 100644 --- a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java +++ b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -407,7 +407,7 @@ public abstract class SynthFileChooserUI extends BasicFileChooserUI implements /* A file filter which accepts file patterns containing * the special wildcard '*' on windows, plus '?', and '[ ]' on Unix. */ - class GlobFilter extends FileFilter { + static class GlobFilter extends FileFilter { Pattern pattern; String globPattern; diff --git a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java index 0d067a37b515f2c53b0efb5db6dcd300fa23f42b..754630f1220867e7034753e9588b3a04db26cb2c 100644 --- a/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java +++ b/src/java.desktop/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java @@ -29,8 +29,6 @@ import java.awt.event.*; import java.beans.*; import java.io.*; import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; import javax.swing.*; import javax.swing.event.*; @@ -697,7 +695,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { } static final int space = 10; - class IndentIcon implements Icon { + static class IndentIcon implements Icon { Icon icon = null; int depth = 0; @@ -1068,7 +1066,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { } @SuppressWarnings("serial") // JDK-implementation class - private class AlignedLabel extends JLabel { + private static class AlignedLabel extends JLabel { private AlignedLabel[] group; private int maxWidth = 0; diff --git a/src/java.desktop/share/classes/sun/swing/table/DefaultTableCellHeaderRenderer.java b/src/java.desktop/share/classes/sun/swing/table/DefaultTableCellHeaderRenderer.java index 8aa945d166e2cd44815f332cb6644a80f6113f4c..1a112b726230e2955c83cb160bcc6591cbb3b16b 100644 --- a/src/java.desktop/share/classes/sun/swing/table/DefaultTableCellHeaderRenderer.java +++ b/src/java.desktop/share/classes/sun/swing/table/DefaultTableCellHeaderRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -189,7 +189,7 @@ public class DefaultTableCellHeaderRenderer extends DefaultTableCellRenderer } @SuppressWarnings("serial") // JDK-implementation class - private class EmptyIcon implements Icon, Serializable { + private static class EmptyIcon implements Icon, Serializable { int width = 0; int height = 0; public void paintIcon(Component c, Graphics g, int x, int y) {} diff --git a/src/java.desktop/share/native/liblcms/LCMS.c b/src/java.desktop/share/native/liblcms/LCMS.c index e4aaeb728913f82a9c5c6a84c647ecfa69df517a..4bbd6e100c386a823f3fbc7b13ace3a5b09d1a94 100644 --- a/src/java.desktop/share/native/liblcms/LCMS.c +++ b/src/java.desktop/share/native/liblcms/LCMS.c @@ -85,7 +85,9 @@ void errorHandler(cmsContext ContextID, cmsUInt32Number errorCode, errMsg[count] = 0; (*javaVM)->AttachCurrentThread(javaVM, (void**)&env, NULL); - JNU_ThrowByName(env, "java/awt/color/CMMException", errMsg); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it before + JNU_ThrowByName(env, "java/awt/color/CMMException", errMsg); + } } JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *jvm, void *reserved) { @@ -113,6 +115,26 @@ void LCMS_freeTransform(JNIEnv *env, jlong ID) cmsDeleteTransform(sTrans); } +/* + * Throw an IllegalArgumentException and init the cause. + */ +static void ThrowIllegalArgumentException(JNIEnv *env, const char *msg) { + jthrowable cause = (*env)->ExceptionOccurred(env); + if (cause != NULL) { + (*env)->ExceptionClear(env); + } + jstring str = JNU_NewStringPlatform(env, msg); + if (str != NULL) { + jobject iae = JNU_NewObjectByName(env, + "java/lang/IllegalArgumentException", + "(Ljava/lang/String;Ljava/lang/Throwable;)V", + str, cause); + if (iae != NULL) { + (*env)->Throw(env, iae); + } + } +} + /* * Class: sun_java2d_cmm_lcms_LCMS * Method: createNativeTransform @@ -185,7 +207,7 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_createNativeTransform if (sTrans == NULL) { J2dRlsTraceLn(J2D_TRACE_ERROR, "LCMS_createNativeTransform: " "sTrans == NULL"); - if ((*env)->ExceptionOccurred(env) == NULL) { + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it JNU_ThrowByName(env, "java/awt/color/CMMException", "Cannot get color transform"); } @@ -214,7 +236,7 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative cmsHPROFILE pf; if (JNU_IsNull(env, data)) { - JNU_ThrowIllegalArgumentException(env, "Invalid profile data"); + ThrowIllegalArgumentException(env, "Invalid profile data"); return 0L; } @@ -232,7 +254,7 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative (*env)->ReleaseByteArrayElements (env, data, dataArray, 0); if (pf == NULL) { - JNU_ThrowIllegalArgumentException(env, "Invalid profile data"); + ThrowIllegalArgumentException(env, "Invalid profile data"); } else { /* Sanity check: try to save the profile in order * to force basic validation. @@ -241,8 +263,7 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative if (!cmsSaveProfileToMem(pf, NULL, &pfSize) || pfSize < sizeof(cmsICCHeader)) { - JNU_ThrowIllegalArgumentException(env, "Invalid profile data"); - + ThrowIllegalArgumentException(env, "Invalid profile data"); cmsCloseProfile(pf); pf = NULL; } @@ -276,8 +297,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getProfileDataNative // determine actual profile size if (!cmsSaveProfileToMem(sProf->pf, NULL, &pfSize)) { - JNU_ThrowByName(env, "java/awt/color/CMMException", - "Can not access specified profile."); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it + JNU_ThrowByName(env, "java/awt/color/CMMException", + "Can not access specified profile."); + } return NULL; } @@ -298,8 +321,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getProfileDataNative (*env)->ReleaseByteArrayElements(env, data, dataArray, 0); if (!status) { - JNU_ThrowByName(env, "java/awt/color/CMMException", - "Can not access specified profile."); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it + JNU_ThrowByName(env, "java/awt/color/CMMException", + "Can not access specified profile."); + } return NULL; } return data; @@ -354,8 +379,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagNative (*env)->ReleaseByteArrayElements (env, data, dataArray, 0); if (!status) { - JNU_ThrowByName(env, "java/awt/color/CMMException", - "ICC Profile header not found"); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it + JNU_ThrowByName(env, "java/awt/color/CMMException", + "ICC Profile header not found"); + } return NULL; } @@ -365,8 +392,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagNative if (cmsIsTag(sProf->pf, sig.cms)) { tagSize = cmsReadRawTag(sProf->pf, sig.cms, NULL, 0); } else { - JNU_ThrowByName(env, "java/awt/color/CMMException", - "ICC profile tag not found"); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it + JNU_ThrowByName(env, "java/awt/color/CMMException", + "ICC profile tag not found"); + } return NULL; } @@ -389,8 +418,10 @@ JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagNative (*env)->ReleaseByteArrayElements (env, data, dataArray, 0); if (bufSize != tagSize) { - JNU_ThrowByName(env, "java/awt/color/CMMException", - "Can not get tag data."); + if (!(*env)->ExceptionCheck(env)) { // errorHandler may throw it + JNU_ThrowByName(env, "java/awt/color/CMMException", + "Can not get tag data."); + } return NULL; } return data; @@ -415,7 +446,7 @@ JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagDataNative sig.j = tagSig; if (JNU_IsNull(env, data)) { - JNU_ThrowIllegalArgumentException(env, "Can not write tag data."); + ThrowIllegalArgumentException(env, "Can not write tag data."); return; } @@ -443,7 +474,7 @@ JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagDataNative (*env)->ReleaseByteArrayElements(env, data, dataArray, 0); if (!status) { - JNU_ThrowIllegalArgumentException(env, "Can not write tag data."); + ThrowIllegalArgumentException(env, "Can not write tag data."); } else if (pfReplace != NULL) { cmsCloseProfile(sProf->pf); sProf->pf = pfReplace; @@ -554,7 +585,7 @@ JNIEXPORT jobject JNICALL Java_sun_java2d_cmm_lcms_LCMS_getProfileID return NULL; } jobject cmmProfile = (*env)->CallObjectMethod(env, pf, mid); - if ((*env)->ExceptionOccurred(env)) { + if ((*env)->ExceptionCheck(env)) { return NULL; } jclass lcmsPCls = (*env)->FindClass(env, "sun/java2d/cmm/lcms/LCMSProfile"); diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XComponentPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XComponentPeer.java index 8297bf738f87cefd500b7eb5ac9365fe626580e6..1f4b0a4d5c87eba5bf664c970a1098db026ce1a6 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XComponentPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XComponentPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1365,8 +1365,8 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget if (graphicsConfig != null) { oldVisual = graphicsConfig.getVisual(); } - if (gc != null && gc instanceof X11GraphicsConfig) { - newVisual = ((X11GraphicsConfig)gc).getVisual(); + if (gc instanceof X11GraphicsConfig x11Config) { + newVisual = x11Config.getVisual(); } // If the new visual differs from the old one, the peer must be diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java index fe2f5ffb7e48c246faeeb8e2c70092c6ea592154..4317136816c2a6e34cd4972c922adc54b7871413 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XEmbedCanvasPeer.java @@ -567,8 +567,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener // Find the top-level and see if it is XEmbed client. If so, ask him to // register the accelerator XWindowPeer parent = getToplevelXWindow(); - if (parent != null && parent instanceof XEmbeddedFramePeer) { - XEmbeddedFramePeer embedded = (XEmbeddedFramePeer)parent; + if (parent instanceof XEmbeddedFramePeer embedded) { embedded.registerAccelerator(stroke); } } @@ -577,8 +576,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener // Find the top-level and see if it is XEmbed client. If so, ask him to // register the accelerator XWindowPeer parent = getToplevelXWindow(); - if (parent != null && parent instanceof XEmbeddedFramePeer) { - XEmbeddedFramePeer embedded = (XEmbeddedFramePeer)parent; + if (parent instanceof XEmbeddedFramePeer embedded) { embedded.unregisterAccelerator(stroke); } } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java index 9dad1de7ceeab48be790ea04b142f8a5ca38f57e..8fea352942a1f5f9078f6e73a5985bf67f83a756 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,6 @@ package sun.awt.X11; import java.awt.*; -import java.awt.peer.ComponentPeer; import java.awt.peer.TextAreaPeer; import java.awt.event.*; import javax.swing.event.DocumentListener; @@ -526,7 +525,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { return jtext.getCaretPosition(); } - final class AWTTextAreaUI extends MotifTextAreaUI { + static final class AWTTextAreaUI extends MotifTextAreaUI { private JTextArea jta; @@ -633,7 +632,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } @SuppressWarnings("serial") // JDK-implementation class - final class XAWTScrollBarButton extends BasicArrowButton { + static final class XAWTScrollBarButton extends BasicArrowButton { private UIDefaults uidefaults = XToolkit.getUIDefaults(); private Color darkShadow = SystemColor.controlShadow; @@ -804,7 +803,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } } - final class XAWTScrollBarUI extends BasicScrollBarUI { + static final class XAWTScrollBarUI extends BasicScrollBarUI { @Override protected void installDefaults() @@ -894,7 +893,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } @SuppressWarnings("serial") // JDK-implementation class - final class AWTTextArea extends JTextArea implements DocumentListener { + static final class AWTTextArea extends JTextArea implements DocumentListener { private boolean isFocused = false; private final XTextAreaPeer peer; @@ -983,7 +982,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } } - final class XAWTScrollPaneUI extends BasicScrollPaneUI { + static final class XAWTScrollPaneUI extends BasicScrollPaneUI { private final Border vsbMarginBorderR = new EmptyBorder(0, 2, 0, 0); private final Border vsbMarginBorderL = new EmptyBorder(0, 0, 0, 2); @@ -1093,7 +1092,7 @@ final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } @SuppressWarnings("serial") // JDK-implementation class - private class AWTTextPane extends JScrollPane implements FocusListener { + private static class AWTTextPane extends JScrollPane implements FocusListener { private final JTextArea jtext; private final XWindow xwin; diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XTextFieldPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XTextFieldPeer.java index 4046b292ee638189decab3a5372564309fc91539..2caaefed8c0618f7bcc2597fd427006e3c5b1419 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XTextFieldPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XTextFieldPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,9 +28,6 @@ package sun.awt.X11; import java.awt.*; import java.awt.peer.*; import java.awt.event.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.TextEvent; import javax.swing.text.*; import javax.swing.event.DocumentListener; import javax.swing.event.DocumentEvent; @@ -40,10 +37,6 @@ import javax.swing.JPasswordField; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; -import java.awt.event.MouseEvent; -import java.awt.event.FocusEvent; -import java.awt.event.KeyEvent; - import javax.swing.plaf.UIResource; import javax.swing.UIDefaults; import javax.swing.JTextField; @@ -445,7 +438,7 @@ final class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { } } - final class AWTTextFieldUI extends MotifPasswordFieldUI { + static final class AWTTextFieldUI extends MotifPasswordFieldUI { private JTextField jtf; @@ -541,7 +534,7 @@ final class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { } @SuppressWarnings("serial") // JDK-implementation class - final class XAWTTextField extends JPasswordField + static final class XAWTTextField extends JPasswordField implements ActionListener, DocumentListener { private boolean isFocused = false; diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java b/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java index b047e688f79b1ff831e271ce6520db26dc238baa..8d2ba131cb7d55b6ad1cdb85a5e20e30160bdc5a 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -303,15 +303,13 @@ class XWindow extends XBaseWindow implements X11ComponentPeer { Component temp = target.getParent(); final ComponentAccessor acc = AWTAccessor.getComponentAccessor(); ComponentPeer peer = acc.getPeer(temp); - while (!(peer instanceof XWindow)) + while (!(peer instanceof XWindow window)) { temp = temp.getParent(); peer = acc.getPeer(temp); } - if (peer != null && peer instanceof XWindow) - return ((XWindow)peer).getContentWindow(); - else return 0; + return window.getContentWindow(); } @@ -327,8 +325,8 @@ class XWindow extends XBaseWindow implements X11ComponentPeer { temp = temp.getParent(); peer = acc.getPeer(temp); } - if (peer != null && peer instanceof XWindow) - return (XWindow) peer; + if (peer instanceof XWindow xWindow) + return xWindow; else return null; } @@ -927,9 +925,7 @@ class XWindow extends XBaseWindow implements X11ComponentPeer { long childWnd = xce.get_subwindow(); if (childWnd != XConstants.None) { XBaseWindow child = XToolkit.windowToXWindow(childWnd); - if (child != null && child instanceof XWindow && - !child.isEventDisabled(xev)) - { + if (child instanceof XWindow && !child.isEventDisabled(xev)) { return; } } @@ -1438,20 +1434,19 @@ class XWindow extends XBaseWindow implements X11ComponentPeer { XToolkit.awtLock(); try { Object wpeer = XToolkit.targetToPeer(comp); - if (wpeer == null - || !(wpeer instanceof XDecoratedPeer) - || ((XDecoratedPeer)wpeer).configure_seen) + if (!(wpeer instanceof XDecoratedPeer xDecoratedPeer) + || xDecoratedPeer.configure_seen) { return toGlobal(0, 0); } // wpeer is an XDecoratedPeer not yet fully adopted by WM Point pt = toOtherWindow(getContentWindow(), - ((XDecoratedPeer)wpeer).getContentWindow(), + xDecoratedPeer.getContentWindow(), 0, 0); if (pt == null) { - pt = new Point(((XBaseWindow)wpeer).getAbsoluteX(), ((XBaseWindow)wpeer).getAbsoluteY()); + pt = new Point(xDecoratedPeer.getAbsoluteX(), xDecoratedPeer.getAbsoluteY()); } pt.x += comp.getX(); pt.y += comp.getY(); diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java index 3a79e785be64bd41fd4f9eb833c6b276f3bec00c..94a1dfd519666f8b1a4a300631669defb4d3d8cc 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java @@ -416,10 +416,10 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, final ComponentAccessor acc = AWTAccessor.getComponentAccessor(); for (int i = 0; i < cnt; i++) { final ComponentPeer childPeer = acc.getPeer(children[i]); - if (childPeer != null && childPeer instanceof XWindowPeer) { - if (((XWindowPeer)childPeer).winAttr.iconsInherited) { - ((XWindowPeer)childPeer).winAttr.icons = icons; - ((XWindowPeer)childPeer).recursivelySetIcon(icons); + if (childPeer instanceof XWindowPeer xWindowPeer) { + if (xWindowPeer.winAttr.iconsInherited) { + xWindowPeer.winAttr.icons = icons; + xWindowPeer.recursivelySetIcon(icons); } } } diff --git a/src/java.desktop/unix/classes/sun/awt/X11InputMethodBase.java b/src/java.desktop/unix/classes/sun/awt/X11InputMethodBase.java index 671df20d1dbeb6a6bc62130e1c14d4e56cc5e53c..eb71b7a59729cc3939deecb3a341ff3ffe1797cc 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11InputMethodBase.java +++ b/src/java.desktop/unix/classes/sun/awt/X11InputMethodBase.java @@ -172,7 +172,7 @@ public abstract class X11InputMethodBase extends InputMethodAdapter { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { dispose(); super.finalize(); diff --git a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java index 87c7907441bcee26f3743cf2ab25dca3bafc85a9..d839731bb2f0238d82b0005b1237417755bc644d 100644 --- a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java +++ b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java @@ -314,7 +314,9 @@ public class FcFontConfiguration extends FontConfiguration { * For Ubuntu the ID is "Ubuntu". */ Properties props = new Properties(); - props.load(new FileInputStream(f)); + try (FileInputStream fis = new FileInputStream(f)) { + props.load(fis); + } osName = props.getProperty("DISTRIB_ID"); osVersion = props.getProperty("DISTRIB_RELEASE"); } else if ((f = new File("/etc/redhat-release")).canRead()) { @@ -401,10 +403,9 @@ public class FcFontConfiguration extends FontConfiguration { File dir = fcInfoFile.getParentFile(); dir.mkdirs(); File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile(); - FileOutputStream fos = new FileOutputStream(tempFile); - props.store(fos, - "JDK Font Configuration Generated File: *Do Not Edit*"); - fos.close(); + try (FileOutputStream fos = new FileOutputStream(tempFile)) { + props.store(fos, "JDK Font Configuration Generated File: *Do Not Edit*"); + } boolean renamed = tempFile.renameTo(fcInfoFile); if (!renamed && FontUtilities.debugFonts()) { System.out.println("rename failed"); diff --git a/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java b/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java index 89212a210169aa373c86037ef4fa1e5c5c1e05a1..e0e58cf167b237956c0281bc69d90a566a58ffd1 100644 --- a/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java +++ b/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java @@ -27,8 +27,6 @@ package sun.font; import sun.awt.FontConfiguration; import sun.awt.X11FontManager; -import sun.font.FontUtilities; -import sun.font.SunFontManager; import sun.util.logging.PlatformLogger; import java.io.File; @@ -111,7 +109,9 @@ public class MFontConfiguration extends FontConfiguration { * For Ubuntu the ID is "Ubuntu". */ Properties props = new Properties(); - props.load(new FileInputStream(f)); + try (FileInputStream fis = new FileInputStream(f)) { + props.load(fis); + } osName = props.getProperty("DISTRIB_ID"); osVersion = props.getProperty("DISTRIB_RELEASE"); } diff --git a/src/java.desktop/unix/classes/sun/font/X11GB2312.java b/src/java.desktop/unix/classes/sun/font/X11GB2312.java index 11d109a532395a3030b2852f3852e507a2adb2f8..e1d64cbe54dd3c850c0b5fc6bd11496ea5d5d52c 100644 --- a/src/java.desktop/unix/classes/sun/font/X11GB2312.java +++ b/src/java.desktop/unix/classes/sun/font/X11GB2312.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,7 @@ public class X11GB2312 extends Charset { return cs instanceof X11GB2312; } - private class Encoder extends CharsetEncoder { + private static class Encoder extends CharsetEncoder { private DoubleByte.Encoder enc = (DoubleByte.Encoder)new EUC_CN().newEncoder(); public Encoder(Charset cs) { @@ -98,7 +98,7 @@ public class X11GB2312 extends Charset { } } - private class Decoder extends CharsetDecoder { + private static class Decoder extends CharsetDecoder { private DoubleByte.Decoder dec = (DoubleByte.Decoder)new EUC_CN().newDecoder(); public Decoder(Charset cs) { diff --git a/src/java.desktop/unix/classes/sun/font/X11GBK.java b/src/java.desktop/unix/classes/sun/font/X11GBK.java index 04df97da485855d022a06dfe4cc37642f44c0965..effe8f54f9c45d44859a5b2048b2bde5834bebef 100644 --- a/src/java.desktop/unix/classes/sun/font/X11GBK.java +++ b/src/java.desktop/unix/classes/sun/font/X11GBK.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public class X11GBK extends Charset { return cs instanceof X11GBK; } - private class Encoder extends DoubleByte.Encoder { + private static class Encoder extends DoubleByte.Encoder { private DoubleByte.Encoder enc = (DoubleByte.Encoder)new GBK().newEncoder(); diff --git a/src/java.desktop/unix/classes/sun/font/X11KSC5601.java b/src/java.desktop/unix/classes/sun/font/X11KSC5601.java index 3eca7c0137335d7c7c054029b01e6c4f78cb10ce..1a7cc310bbfdc35e901d03c2ee5310d04ddc5407 100644 --- a/src/java.desktop/unix/classes/sun/font/X11KSC5601.java +++ b/src/java.desktop/unix/classes/sun/font/X11KSC5601.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,7 @@ public class X11KSC5601 extends Charset { return cs instanceof X11KSC5601; } - private class Encoder extends CharsetEncoder { + private static class Encoder extends CharsetEncoder { private DoubleByte.Encoder enc = (DoubleByte.Encoder)new EUC_KR().newEncoder(); public Encoder(Charset cs) { @@ -97,7 +97,7 @@ public class X11KSC5601 extends Charset { } } - private class Decoder extends CharsetDecoder { + private static class Decoder extends CharsetDecoder { private DoubleByte.Decoder dec = (DoubleByte.Decoder)new EUC_KR().newDecoder(); public Decoder(Charset cs) { diff --git a/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java b/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java index f41f3778da46cb35f92963e6b123c5ab15d01785..b40d1d0ffa1a6ed334dbe7888ee5c018b2a89453 100644 --- a/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java +++ b/src/java.desktop/unix/classes/sun/java2d/xr/XRCompositeManager.java @@ -25,15 +25,18 @@ package sun.java2d.xr; -import java.awt.*; -import java.awt.geom.*; - +import java.awt.AlphaComposite; +import java.awt.Composite; +import java.awt.Paint; +import java.awt.geom.AffineTransform; +import java.awt.geom.NoninvertibleTransformException; import java.security.AccessController; import java.security.PrivilegedAction; -import sun.font.*; -import sun.java2d.*; -import sun.java2d.loops.*; +import sun.awt.image.PixelConverter; +import sun.font.XRTextRenderer; +import sun.java2d.SunGraphics2D; +import sun.java2d.loops.XORComposite; /** * Manages per-application resources, e.g. the 1x1 pixmap used for solid color @@ -68,6 +71,7 @@ public class XRCompositeManager { int gradCachePicture; boolean xorEnabled = false; + int eargb; int validatedPixel = 0; Composite validatedComp; Paint validatedPaint; @@ -170,8 +174,10 @@ public class XRCompositeManager { validatedComp = comp; } - if (sg2d != null && (validatedPixel != sg2d.pixel || updatePaint)) { - validatedPixel = sg2d.pixel; + if (sg2d != null && (eargb != sg2d.eargb || updatePaint)) { + eargb = sg2d.eargb; + validatedPixel = PixelConverter.ArgbPre.instance + .rgbToPixel(eargb, null); setForeground(validatedPixel); } diff --git a/src/java.desktop/unix/classes/sun/java2d/xr/XRGraphicsConfig.java b/src/java.desktop/unix/classes/sun/java2d/xr/XRGraphicsConfig.java index 680e634cce85ac65c0de165a2b80c22cc6f040c1..7483128bec6476024bb8b4a702e7500827963b7d 100644 --- a/src/java.desktop/unix/classes/sun/java2d/xr/XRGraphicsConfig.java +++ b/src/java.desktop/unix/classes/sun/java2d/xr/XRGraphicsConfig.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,14 +25,12 @@ package sun.java2d.xr; -import java.awt.Transparency; -import sun.awt.X11GraphicsConfig; import sun.awt.X11ComponentPeer; +import sun.awt.X11GraphicsConfig; import sun.awt.X11GraphicsDevice; import sun.awt.X11GraphicsEnvironment; import sun.awt.image.SurfaceManager; import sun.java2d.SurfaceData; -import sun.java2d.loops.SurfaceType; public class XRGraphicsConfig extends X11GraphicsConfig implements SurfaceManager.ProxiedGraphicsConfig { @@ -58,14 +56,4 @@ public class XRGraphicsConfig extends X11GraphicsConfig implements public Object getProxyKey() { return this; } - - public synchronized SurfaceType getSurfaceType() { - if (surfaceType != null) { - return surfaceType; - } - - surfaceType = XRSurfaceData.getSurfaceType(this, Transparency.OPAQUE); - return surfaceType; - } - } diff --git a/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java b/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java index 1b12b54b8f81f6d98266d52549fe9ecab411a6cd..7a0f8d1bb29d3ccf35b7237b66bbb04de138d6df 100644 --- a/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java +++ b/src/java.desktop/unix/classes/sun/java2d/xr/XRSurfaceData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,10 +36,12 @@ import java.awt.geom.AffineTransform; import java.awt.image.ColorModel; import java.awt.image.DirectColorModel; import java.awt.image.Raster; + import sun.awt.SunHints; import sun.awt.SunToolkit; import sun.awt.X11ComponentPeer; import sun.awt.image.PixelConverter; +import sun.font.FontManagerNativeLibrary; import sun.java2d.InvalidPipeException; import sun.java2d.SunGraphics2D; import sun.java2d.SurfaceData; @@ -55,7 +57,6 @@ import sun.java2d.pipe.ShapeDrawPipe; import sun.java2d.pipe.TextPipe; import sun.java2d.pipe.ValidatePipe; import sun.java2d.x11.XSurfaceData; -import sun.font.FontManagerNativeLibrary; public abstract class XRSurfaceData extends XSurfaceData { X11ComponentPeer peer; @@ -207,9 +208,8 @@ public abstract class XRSurfaceData extends XSurfaceData { protected MaskFill getMaskFill(SunGraphics2D sg2d) { AlphaComposite aComp = null; - if(sg2d.composite != null - && sg2d.composite instanceof AlphaComposite) { - aComp = (AlphaComposite) sg2d.composite; + if (sg2d.composite instanceof AlphaComposite alphaComposite) { + aComp = alphaComposite; } boolean supportedPaint = sg2d.paintState <= SunGraphics2D.PAINT_ALPHACOLOR @@ -277,7 +277,7 @@ public abstract class XRSurfaceData extends XSurfaceData { } return new XRPixmapSurfaceData - (gc, width, height, image, getSurfaceType(gc, transparency), + (gc, width, height, image, getPixmapSurfaceType(transparency), cm, drawable, transparency, XRUtils.getPictureFormatForTransparency(transparency), depth, isTexture); } @@ -396,8 +396,7 @@ public abstract class XRSurfaceData extends XSurfaceData { * Returns the XRender SurfaceType which is able to fullfill the specified * transparency requirement. */ - public static SurfaceType getSurfaceType(XRGraphicsConfig gc, - int transparency) { + public static SurfaceType getPixmapSurfaceType(int transparency) { SurfaceType sType = null; switch (transparency) { diff --git a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java index 2bb401698da6dd721046a8de9c412911140cf432..82cb84a14550e632d9561a986a492e54a20eee6b 100644 --- a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java +++ b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java @@ -671,8 +671,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { int match = -1; Media media = (Media)attributes.get(Media.class); - if (media != null && media instanceof MediaSizeName) { - MediaSizeName msn = (MediaSizeName)media; + if (media instanceof MediaSizeName msn) { // case when no supported mediasizenames are reported // check given media against the default @@ -832,7 +831,7 @@ public class IPPPrintService implements PrintService, SunPrinterJobService { //This class is for getting all pre-defined Finishings @SuppressWarnings("serial") // JDK implementation class - private class ExtFinishing extends Finishings { + private static class ExtFinishing extends Finishings { ExtFinishing(int value) { super(100); // 100 to avoid any conflicts with predefined values. } diff --git a/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java b/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java index 268fc9b69af7dfc693182caf823283591e399bd5..7fa1b201340c5af4790cbfcf9d8bda790af4ce38 100644 --- a/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java +++ b/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java @@ -26,10 +26,8 @@ package sun.print; import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; import java.io.IOException; +import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Vector; import java.security.AccessController; @@ -54,6 +52,8 @@ import java.io.FileReader; import java.net.URL; import java.nio.file.Files; +import sun.awt.util.ThreadGroupUtils; + /* * Remind: This class uses solaris commands. We also need a linux * version @@ -204,14 +204,18 @@ public class PrintServiceLookupProvider extends PrintServiceLookup return BSD_LPD; } - + @SuppressWarnings("removal") public PrintServiceLookupProvider() { // start the printer listener thread if (pollServices) { - Thread thr = new Thread(null, new PrinterChangeListener(), - "PrinterListener", 0, false); - thr.setDaemon(true); - thr.start(); + AccessController.doPrivileged((PrivilegedAction) () -> { + Thread thr = new Thread(ThreadGroupUtils.getRootThreadGroup(), + new PrinterChangeListener(), + "PrinterListener", 0, false); + thr.setContextClassLoader(null); + thr.setDaemon(true); + return thr; + }).start(); IPPPrintService.debug_println(debugPrefix+"polling turned on"); } } diff --git a/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java b/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java index 2184e8a3fcf4de3e8deadeadca36e735d3f422bf..eefef8a53539ba4930ae10ae10f2f584bcbdbb18 100644 --- a/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java +++ b/src/java.desktop/unix/classes/sun/print/UnixPrintJob.java @@ -366,8 +366,7 @@ public class UnixPrintJob implements CancelablePrintJob { } } - if (customTray != null && - customTray instanceof CustomMediaTray) { + if (customTray != null) { String choice = customTray.getChoiceName(); if (choice != null) { mOptions += " InputSlot="+choice; diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/AnimationController.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/AnimationController.java index 05c2f5c0a40cb4b3d7115a29f80b3d5420522dc4..b50a5ad583ec59bc720ef16f10f81ab1891d3309 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/AnimationController.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/AnimationController.java @@ -59,7 +59,7 @@ import sun.awt.AppContext; *
    • It tracks the animation state for every UI component involved in the * animation and paints {@code Skin} in new {@code State} over the * {@code Skin} in last {@code State} using - * {@code AlphaComposite.SrcOver.derive(alpha)} where {code alpha} + * {@code AlphaComposite.SrcOver.derive(alpha)} where {@code alpha} * depends on the state of animation * * diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java index 695bb4be499ba0b0a5854bd0800882e33829e552..1a601f40332b93bb4d19d0cb6fd41ada1e52a1af 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java @@ -593,7 +593,7 @@ public class WindowsComboBoxUI extends BasicComboBoxUI { private static final Border NULL_BORDER = new EmptyBorder(0, 0, 0, 0); // Create own version of DashedBorder with more space on left side - private class WindowsComboBoxDashedBorder extends DashedBorder { + private static class WindowsComboBoxDashedBorder extends DashedBorder { public WindowsComboBoxDashedBorder(Color color, int thickness) { super(color, thickness); diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java index 801529b6e6ee86504375b8868454e3d28ac0edac..92980c52a009d8e6eea7269451050b49cfa6da1b 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java @@ -1054,7 +1054,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { } static final int space = 10; - class IndentIcon implements Icon { + static class IndentIcon implements Icon { Icon icon = null; int depth = 0; @@ -1221,8 +1221,8 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value != null && value instanceof FileFilter) { - setText(((FileFilter)value).getDescription()); + if (value instanceof FileFilter fileFilter) { + setText(fileFilter.getDescription()); } return this; diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index e8ad9418cb3b8f833769921bedc1185d54aacc32..ecbd0bbe30f3f2e77b862945a014cacabf2bef95 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -2113,7 +2113,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel * Gets an Icon from the native libraries if available. * A desktop property is used to trigger reloading the icon when needed. */ - private class ActiveWindowsIcon implements UIDefaults.ActiveValue { + private static class ActiveWindowsIcon implements UIDefaults.ActiveValue { private Icon icon; private String nativeImageName; private String fallbackName; @@ -2419,7 +2419,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel } } - private class TriggerDesktopProperty extends WindowsDesktopProperty { + private static class TriggerDesktopProperty extends WindowsDesktopProperty { TriggerDesktopProperty(String key) { super(key, null); // This call adds a property change listener for the property, @@ -2436,7 +2436,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel } } - private class FontDesktopProperty extends TriggerDesktopProperty { + private static class FontDesktopProperty extends TriggerDesktopProperty { FontDesktopProperty(String key) { super(key); } diff --git a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/XPStyle.java b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/XPStyle.java index 45fc54c07a64df31f79ecaa8f283a762937fd0bc..c2c11c896cf7411ff667b8856280aa0dc97154f7 100644 --- a/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/XPStyle.java +++ b/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/XPStyle.java @@ -301,7 +301,7 @@ class XPStyle { } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class XPFillBorder extends LineBorder implements UIResource { + private static class XPFillBorder extends LineBorder implements UIResource { XPFillBorder(Color color, int thickness) { super(color, thickness); } @@ -398,7 +398,7 @@ class XPStyle { } @SuppressWarnings("serial") // Superclass is not serializable across versions - private class XPEmptyBorder extends EmptyBorder implements UIResource { + private static class XPEmptyBorder extends EmptyBorder implements UIResource { XPEmptyBorder(Insets m) { super(m.top+2, m.left+2, m.bottom+2, m.right+2); } diff --git a/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolder2.java b/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolder2.java index 0f8ae20454f2d64f371e7bcbcdf0514d29ad92e5..1564804cf843496d86c431b5d635672ae3b10041 100644 --- a/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolder2.java +++ b/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolder2.java @@ -85,7 +85,7 @@ final class Win32ShellFolder2 extends ShellFolder { static final int LARGE_ICON_SIZE = 32; static final int MIN_QUALITY_ICON = 16; static final int MAX_QUALITY_ICON = 256; - private final static int[] ICON_RESOLUTIONS + private static final int[] ICON_RESOLUTIONS = {16, 24, 32, 48, 64, 72, 96, 128, 256}; static final int FILE_ICON_ID = 1; @@ -540,14 +540,13 @@ final class Win32ShellFolder2 extends ShellFolder { * Check to see if two ShellFolder objects are the same */ public boolean equals(Object o) { - if (o == null || !(o instanceof Win32ShellFolder2)) { + if (!(o instanceof Win32ShellFolder2 rhs)) { // Short-circuit circuitous delegation path if (!(o instanceof File)) { return super.equals(o); } return pathsEqual(getPath(), ((File) o).getPath()); } - Win32ShellFolder2 rhs = (Win32ShellFolder2) o; if ((parent == null && rhs.parent != null) || (parent != null && rhs.parent == null)) { return false; diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java b/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java index 9ad52ba7111c0b697fc58a92ace475c54ffaed33..681662032e147799bc0ae20c38f703ed0da634e3 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WInputMethod.java @@ -133,7 +133,7 @@ final class WInputMethod extends InputMethodAdapter } @Override - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { // Release the resources used by the native input context. diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WPrinterJob.java b/src/java.desktop/windows/classes/sun/awt/windows/WPrinterJob.java index 6661ae218a1d18c590135644ef45b525b8e7b09f..028cb36c2fcec95605a73e8c4b9b2e9ebbc3431f 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WPrinterJob.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WPrinterJob.java @@ -731,8 +731,7 @@ public final class WPrinterJob extends RasterPrinterJob */ if (attr.getCategory() == SunAlternateMedia.class) { Media media = (Media)attributes.get(Media.class); - if (media == null || - !(media instanceof MediaTray)) { + if (!(media instanceof MediaTray)) { attr = ((SunAlternateMedia)attr).getMedia(); } } @@ -2297,7 +2296,7 @@ public final class WPrinterJob extends RasterPrinterJob } @SuppressWarnings("serial") // JDK-implementation class -class PrintToFileErrorDialog extends Dialog implements ActionListener{ +static class PrintToFileErrorDialog extends Dialog implements ActionListener { public PrintToFileErrorDialog(Frame parent, String title, String message, String buttonText) { super(parent, title, true); diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WScrollPanePeer.java b/src/java.desktop/windows/classes/sun/awt/windows/WScrollPanePeer.java index 2c7667f25efa07371634622fca07e77776d2a997..b3d0402213f1e37ff045be2fb5f4cc74656214e5 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WScrollPanePeer.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WScrollPanePeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -162,7 +162,7 @@ final class WScrollPanePeer extends WPanelPeer implements ScrollPanePeer { * operation. */ @SuppressWarnings("serial") // JDK-implementation class - class ScrollEvent extends PeerEvent { + static class ScrollEvent extends PeerEvent { ScrollEvent(Object source, Runnable runnable) { super(source, runnable, 0L); } diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java b/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java index 745c2d6d8c08c29b71d89cd972977103bd17cd01..f01ae946020e16bca4ff6358616472f889f5acf0 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java @@ -684,19 +684,6 @@ public final class WToolkit extends SunToolkit implements Runnable { private native Insets getScreenInsets(int screen); - - @Override - public FontMetrics getFontMetrics(Font font) { - // This is an unsupported hack, but left in for a customer. - // Do not remove. - FontManager fm = FontManagerFactory.getInstance(); - if (fm instanceof SunFontManager - && ((SunFontManager) fm).usePlatformFontMetrics()) { - return WFontMetrics.getFontMetrics(font); - } - return super.getFontMetrics(font); - } - @Override public FontPeer getFontPeer(String name, int style) { FontPeer retval = null; diff --git a/src/java.desktop/windows/classes/sun/java2d/d3d/D3DRenderer.java b/src/java.desktop/windows/classes/sun/java2d/d3d/D3DRenderer.java index bf46ec92934ea5b032c85fe8e1c6d6d6bed62e23..924dd024d6725fa78a116aec9c6b7cf1aba4cd54 100644 --- a/src/java.desktop/windows/classes/sun/java2d/d3d/D3DRenderer.java +++ b/src/java.desktop/windows/classes/sun/java2d/d3d/D3DRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.awt.geom.Path2D; import sun.java2d.InvalidPipeException; import sun.java2d.SunGraphics2D; import sun.java2d.loops.GraphicsPrimitive; -import sun.java2d.pipe.BufferedPaints; import sun.java2d.pipe.BufferedRenderPipe; import sun.java2d.pipe.RenderQueue; import sun.java2d.pipe.SpanIterator; @@ -108,7 +107,7 @@ class D3DRenderer extends BufferedRenderPipe { return new Tracer(this); } - private class Tracer extends D3DRenderer { + private static class Tracer extends D3DRenderer { private D3DRenderer d3dr; Tracer(D3DRenderer d3dr) { super(d3dr.rq); diff --git a/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java b/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java index 1d76ebae4799c5f231cf2bda4375659f50b56bab..28055c1afece63eb341e2024d0a2b587d9b0650f 100644 --- a/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java +++ b/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java @@ -25,6 +25,8 @@ package sun.print; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.ArrayList; import javax.print.DocFlavor; @@ -41,6 +43,8 @@ import javax.print.attribute.PrintServiceAttribute; import javax.print.attribute.PrintServiceAttributeSet; import javax.print.attribute.standard.PrinterName; +import sun.awt.util.ThreadGroupUtils; + public class PrintServiceLookupProvider extends PrintServiceLookup { private PrintService defaultPrintService; @@ -81,22 +85,31 @@ public class PrintServiceLookupProvider extends PrintServiceLookup { return win32PrintLUS; } + @SuppressWarnings("removal") public PrintServiceLookupProvider() { if (win32PrintLUS == null) { win32PrintLUS = this; // start the local printer listener thread - Thread thr = new Thread(null, new PrinterChangeListener(), - "PrinterListener", 0, false); - thr.setDaemon(true); - thr.start(); + AccessController.doPrivileged((PrivilegedAction) () -> { + Thread thr = new Thread(ThreadGroupUtils.getRootThreadGroup(), + new PrinterChangeListener(), + "PrinterListener", 0, false); + thr.setContextClassLoader(null); + thr.setDaemon(true); + return thr; + }).start(); // start the remote printer listener thread - Thread remThr = new Thread(null, new RemotePrinterChangeListener(), - "RemotePrinterListener", 0, false); - remThr.setDaemon(true); - remThr.start(); + AccessController.doPrivileged((PrivilegedAction) () -> { + Thread thr = new Thread(ThreadGroupUtils.getRootThreadGroup(), + new RemotePrinterChangeListener(), + "RemotePrinterListener", 0, false); + thr.setContextClassLoader(null); + thr.setDaemon(true); + return thr; + }).start(); } /* else condition ought to never happen! */ } diff --git a/src/java.desktop/windows/native/libawt/windows/ShellFolder2.cpp b/src/java.desktop/windows/native/libawt/windows/ShellFolder2.cpp index bc0c27d069a55478870da585b2c88c5a4faf1708..124efa09be148b08e457eee889c018b9ee1ec541 100644 --- a/src/java.desktop/windows/native/libawt/windows/ShellFolder2.cpp +++ b/src/java.desktop/windows/native/libawt/windows/ShellFolder2.cpp @@ -1056,38 +1056,57 @@ JNIEXPORT jintArray JNICALL Java_sun_awt_shell_Win32ShellFolder2_getIconBits bmi.bmiHeader.biCompression = BI_RGB; // Extract the color bitmap int nBits = iconSize * iconSize; - long colorBits[MAX_ICON_SIZE * MAX_ICON_SIZE]; - GetDIBits(dc, iconInfo.hbmColor, 0, iconSize, colorBits, &bmi, DIB_RGB_COLORS); - // XP supports alpha in some icons, and depending on device. - // This should take precedence over the icon mask bits. - BOOL hasAlpha = FALSE; - if (IS_WINXP) { - for (int i = 0; i < nBits; i++) { - if ((colorBits[i] & 0xff000000) != 0) { - hasAlpha = TRUE; - break; + + long *colorBits = NULL; + long *maskBits = NULL; + + try { + entry_point(); + colorBits = (long*)safe_Malloc(MAX_ICON_SIZE * MAX_ICON_SIZE * sizeof(long)); + GetDIBits(dc, iconInfo.hbmColor, 0, iconSize, colorBits, &bmi, DIB_RGB_COLORS); + // XP supports alpha in some icons, and depending on device. + // This should take precedence over the icon mask bits. + BOOL hasAlpha = FALSE; + if (IS_WINXP) { + for (int i = 0; i < nBits; i++) { + if ((colorBits[i] & 0xff000000) != 0) { + hasAlpha = TRUE; + break; + } } } - } - if (!hasAlpha) { - // Extract the mask bitmap - long maskBits[MAX_ICON_SIZE * MAX_ICON_SIZE]; - GetDIBits(dc, iconInfo.hbmMask, 0, iconSize, maskBits, &bmi, DIB_RGB_COLORS); - // Copy the mask alphas into the color bits - for (int i = 0; i < nBits; i++) { - if (maskBits[i] == 0) { - colorBits[i] |= 0xff000000; + if (!hasAlpha) { + // Extract the mask bitmap + maskBits = (long*)safe_Malloc(MAX_ICON_SIZE * MAX_ICON_SIZE * sizeof(long)); + GetDIBits(dc, iconInfo.hbmMask, 0, iconSize, maskBits, &bmi, DIB_RGB_COLORS); + // Copy the mask alphas into the color bits + for (int i = 0; i < nBits; i++) { + if (maskBits[i] == 0) { + colorBits[i] |= 0xff000000; + } } } + // Create java array + iconBits = env->NewIntArray(nBits); + if (!(env->ExceptionCheck())) { + // Copy values to java array + env->SetIntArrayRegion(iconBits, 0, nBits, colorBits); + } + } catch(std::bad_alloc&) { + handle_bad_alloc(); } + // Release DC ReleaseDC(NULL, dc); - // Create java array - iconBits = env->NewIntArray(nBits); - if (!(env->ExceptionCheck())) { - // Copy values to java array - env->SetIntArrayRegion(iconBits, 0, nBits, colorBits); - } + + // Free bitmap buffers if they were allocated + if (colorBits != NULL) { + free(colorBits); + } + + if (maskBits != NULL) { + free(maskBits); + } } // Fix 4745575 GDI Resource Leak // MSDN diff --git a/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp b/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp index 4868fed9089672164bf93f14d962182c2ad6ce50..8db02f9aee485ce89f2cfc3d03e02e7b867d7c6a 100644 --- a/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp +++ b/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,6 +47,7 @@ #include "awt_Win32GraphicsDevice.h" #include "Hashtable.h" #include "ComCtl32Util.h" +#include "math.h" #include @@ -2234,8 +2235,8 @@ void AwtComponent::PaintUpdateRgn(const RECT *insets) */ RECT* r = (RECT*)(buffer + rgndata->rdh.dwSize); RECT* un[2] = {0, 0}; - DWORD i; - for (i = 0; i < rgndata->rdh.nCount; i++, r++) { + DWORD i; + for (i = 0; i < rgndata->rdh.nCount; i++, r++) { int width = r->right-r->left; int height = r->bottom-r->top; if (width > 0 && height > 0) { @@ -2247,13 +2248,22 @@ void AwtComponent::PaintUpdateRgn(const RECT *insets) } } } + // The Windows may request to update the small region of pixels that + // cannot be represented in the user's space, in this case, we will + // request to repaint the smallest non-empty bounding box in the user's + // space + int screen = GetScreenImOn(); + Devices::InstanceAccess devices; + AwtWin32GraphicsDevice* device = devices->GetDevice(screen); + float scaleX = (device == NULL) ? 1 : device->GetScaleX(); + float scaleY = (device == NULL) ? 1 : device->GetScaleY(); for(i = 0; i < 2; i++) { if (un[i] != 0) { - DoCallback("handleExpose", "(IIII)V", - ScaleDownX(un[i]->left), - ScaleDownY(un[i]->top), - ScaleDownX(un[i]->right - un[i]->left), - ScaleDownY(un[i]->bottom - un[i]->top)); + int x1 = floor(un[i]->left / scaleX); + int y1 = floor(un[i]->top / scaleY); + int x2 = ceil(un[i]->right / scaleX); + int y2 = ceil(un[i]->bottom / scaleY); + DoCallback("handleExpose", "(IIII)V", x1, y1, x2 - x1, y2 - y1); } } delete [] buffer; diff --git a/src/java.logging/share/classes/java/util/logging/Logger.java b/src/java.logging/share/classes/java/util/logging/Logger.java index 51ebfb58aea7c7116c8a9d0da4b17ea5cb2a001e..0dc602c2c2486828b8c0b47f2aefa8602c0d037a 100644 --- a/src/java.logging/share/classes/java/util/logging/Logger.java +++ b/src/java.logging/share/classes/java/util/logging/Logger.java @@ -40,6 +40,7 @@ import java.util.function.Supplier; import jdk.internal.access.JavaUtilResourceBundleAccess; import jdk.internal.access.SharedSecrets; import jdk.internal.reflect.CallerSensitive; +import jdk.internal.reflect.CallerSensitiveAdapter; import jdk.internal.reflect.Reflection; import static jdk.internal.logger.DefaultLoggerFinder.isSystem; @@ -714,6 +715,7 @@ public class Logger { * #getLogger(java.lang.String)}. * @return a suitable Logger for {@code callerClass}. */ + @CallerSensitiveAdapter private static Logger getLogger(String name, Class callerClass) { return demandLogger(name, null, callerClass); } @@ -788,6 +790,7 @@ public class Logger { * not {@code null}. * @return a suitable Logger for {@code callerClass}. */ + @CallerSensitiveAdapter private static Logger getLogger(String name, String resourceBundleName, Class callerClass) { Logger result = demandLogger(name, resourceBundleName, callerClass); diff --git a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java index bbd491260a8a9ac83aa6a1c9c7800e2fdacc3d62..bedeaea4ba891fb54835db03f984499c47f0a574 100644 --- a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java +++ b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java @@ -1648,8 +1648,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced { */ private static IOException newIOException(String message, Throwable cause) { - final IOException x = new IOException(message); - return EnvHelp.initCause(x,cause); + return new IOException(message, cause); } /** diff --git a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java index 7a903122ad7080566d5c081fb33bd523067691ca..d875ce3a5bb3284b66e118c2c34e4d07b4be3a08 100644 --- a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java +++ b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java @@ -367,7 +367,7 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable } catch (NamingException e) { final String msg = "Failed to retrieve RMIServer stub: " + e; if (tracing) logger.trace("connect",idstr + " " + msg); - throw EnvHelp.initCause(new IOException(msg),e); + throw new IOException(msg, e); } } @@ -543,9 +543,7 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable throw (IOException) closeException; if (closeException instanceof RuntimeException) throw (RuntimeException) closeException; - final IOException x = - new IOException("Failed to close: " + closeException); - throw EnvHelp.initCause(x,closeException); + throw new IOException("Failed to close: " + closeException, closeException); } } diff --git a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectorServer.java b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectorServer.java index a918921356ea2edc5dfd7782d1b084c1143d67c3..139b7653424c84b360c35580e5a88fa2913cd94c 100644 --- a/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectorServer.java +++ b/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnectorServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -420,8 +420,7 @@ public class RMIConnectorServer extends JMXConnectorServer { try { mbsf = new MBeanServerFileAccessController(accessFile); } catch (IOException e) { - throw EnvHelp.initCause( - new IllegalArgumentException(e.getMessage()), e); + throw new IllegalArgumentException(e.getMessage(), e); } // Set the MBeanServerForwarder // @@ -434,9 +433,7 @@ public class RMIConnectorServer extends JMXConnectorServer { defaultClassLoader = EnvHelp.resolveServerClassLoader( attributes, getMBeanServer()); } catch (InstanceNotFoundException infc) { - IllegalArgumentException x = new - IllegalArgumentException("ClassLoader not found: "+infc); - throw EnvHelp.initCause(x,infc); + throw new IllegalArgumentException("ClassLoader not found: " + infc, infc); } if (tracing) logger.trace("start", "setting RMIServer object"); @@ -831,8 +828,7 @@ public class RMIConnectorServer extends JMXConnectorServer { */ private static IOException newIOException(String message, Throwable cause) { - final IOException x = new IOException(message); - return EnvHelp.initCause(x,cause); + return new IOException(message, cause); } diff --git a/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java b/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java index 0a8350be8eb2cb294d6ea23661d548bd9eaab0cd..0b817e4746325d903226a8c69bd6c73bd870fa0e 100644 --- a/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java +++ b/src/java.management/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java @@ -38,7 +38,6 @@ import com.sun.jmx.mbeanserver.Repository.RegistrationContext; import com.sun.jmx.mbeanserver.Util; import com.sun.jmx.remote.util.EnvHelp; -import java.io.ObjectInputStream; import java.lang.ref.WeakReference; import java.security.AccessControlContext; import java.security.AccessController; @@ -80,7 +79,6 @@ import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; -import javax.management.OperationsException; import javax.management.QueryEval; import javax.management.QueryExp; import javax.management.ReflectionException; @@ -208,8 +206,7 @@ public class DefaultMBeanServerInterceptor implements MBeanServerInterceptor { } catch (InstanceNotFoundException e) { /* Can only happen if loaderName doesn't exist, but we just passed null, so we shouldn't get this exception. */ - throw EnvHelp.initCause( - new IllegalArgumentException("Unexpected exception: " + e), e); + throw new IllegalArgumentException("Unexpected exception: " + e, e); } } diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java index 6f35c44953fd5e5269e83142a9044bc1a9bf0891..278ce9e250046cb1642632e0595ece53dcbab2bc 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java @@ -120,7 +120,7 @@ import sun.reflect.misc.ReflectUtil; * @since 1.6 */ public class DefaultMXBeanMappingFactory extends MXBeanMappingFactory { - static abstract class NonNullMXBeanMapping extends MXBeanMapping { + abstract static class NonNullMXBeanMapping extends MXBeanMapping { NonNullMXBeanMapping(Type javaType, OpenType openType) { super(javaType, openType); } @@ -936,7 +936,7 @@ public class DefaultMXBeanMappingFactory extends MXBeanMappingFactory { } /** Converts from a CompositeData to an instance of the targetClass. */ - private static abstract class CompositeBuilder { + private abstract static class CompositeBuilder { CompositeBuilder(Class targetClass, String[] itemNames) { this.targetClass = targetClass; this.itemNames = itemNames; diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java index 41ab9491f7ecd4c1a7ca82d4f05cce918ed1cc7a..3f73b2c0b1eb3ecef6670b20beb6e34905d13a53 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -66,7 +66,7 @@ import sun.reflect.misc.ReflectUtil; * @since 1.5 */ public class Introspector { - final public static boolean ALLOW_NONPUBLIC_MBEAN; + public static final boolean ALLOW_NONPUBLIC_MBEAN; static { @SuppressWarnings("removal") String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic")); diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanServerDelegateImpl.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanServerDelegateImpl.java index fc9a4ad10f412788bea976a9d996a0007809599c..ab63cab823c14bc3bb01c372b862dee83670c0c3 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanServerDelegateImpl.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MBeanServerDelegateImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ final class MBeanServerDelegateImpl extends MBeanServerDelegate implements DynamicMBean, MBeanRegistration { - final private static String[] attributeNames = new String[] { + private static final String[] attributeNames = new String[] { "MBeanServerId", "SpecificationName", "SpecificationVersion", @@ -106,22 +106,22 @@ final class MBeanServerDelegateImpl null,getNotificationInfo()); } - final public ObjectName preRegister (MBeanServer server, ObjectName name) + public final ObjectName preRegister (MBeanServer server, ObjectName name) throws java.lang.Exception { if (name == null) return DELEGATE_NAME; else return name; } - final public void postRegister (Boolean registrationDone) { + public final void postRegister (Boolean registrationDone) { } - final public void preDeregister() + public final void preDeregister() throws java.lang.Exception { throw new IllegalArgumentException( "The MBeanServerDelegate MBean cannot be unregistered"); } - final public void postDeregister() { + public final void postDeregister() { } /** diff --git a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanProxy.java b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanProxy.java index d2bdcb19b391d5c95fd6c38672c329b54c067cc7..35660e415df0c6a049fc6560f8ae786a45b44228 100644 --- a/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanProxy.java +++ b/src/java.management/share/classes/com/sun/jmx/mbeanserver/MXBeanProxy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,7 +89,7 @@ public class MXBeanProxy { } } - private static abstract class Handler { + private abstract static class Handler { Handler(String name, ConvertingMethod cm) { this.name = name; this.convertingMethod = cm; diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java index 5b490b546fc75a409a6b8b2ee62590f1cf57fd39..ae21c9352faa6c917a9042d4141c353ab14ab258 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java @@ -610,11 +610,9 @@ public class ArrayNotificationBuffer implements NotificationBuffer { logger.debug("createListeners", "added creationListener"); } catch (Exception e) { final String msg = "Can't add listener to MBean server delegate: "; - RuntimeException re = new IllegalArgumentException(msg + e); - EnvHelp.initCause(re, e); logger.fine("createListeners", msg + e); logger.debug("createListeners", e); - throw re; + throw new IllegalArgumentException(msg + e, e); } /* Spec doesn't say whether Set returned by QueryNames can be modified diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java index 02ea3ff8bf9894ab5dd754650ab0395bc3bde745..28c68feb9930cbc266f12bffce5ce4bad43244cd 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java @@ -51,7 +51,6 @@ import javax.management.remote.TargetedNotification; import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; -import java.lang.reflect.UndeclaredThrowableException; import java.util.concurrent.RejectedExecutionException; @@ -146,22 +145,22 @@ public abstract class ClientNotifForwarder { /** * Called to fetch notifications from a server. */ - abstract protected NotificationResult fetchNotifs(long clientSequenceNumber, + protected abstract NotificationResult fetchNotifs(long clientSequenceNumber, int maxNotifications, long timeout) throws IOException, ClassNotFoundException; - abstract protected Integer addListenerForMBeanRemovedNotif() + protected abstract Integer addListenerForMBeanRemovedNotif() throws IOException, InstanceNotFoundException; - abstract protected void removeListenerForMBeanRemovedNotif(Integer id) + protected abstract void removeListenerForMBeanRemovedNotif(Integer id) throws IOException, InstanceNotFoundException, ListenerNotFoundException; /** * Used to send out a notification about lost notifs */ - abstract protected void lostNotifs(String message, long number); + protected abstract void lostNotifs(String message, long number); public synchronized void addNotificationListener(Integer listenerID, @@ -340,9 +339,7 @@ public abstract class ClientNotifForwarder { try { wait(); } catch (InterruptedException ire) { - IOException ioe = new IOException(ire.toString()); - EnvHelp.initCause(ioe, ire); - throw ioe; + throw new IOException(ire.toString(), ire); } } @@ -381,9 +378,7 @@ public abstract class ClientNotifForwarder { try { wait(); } catch (InterruptedException ire) { - IOException ioe = new IOException(ire.toString()); - EnvHelp.initCause(ioe, ire); - throw ioe; + throw new IOException(ire.toString(), ire); } } @@ -821,10 +816,7 @@ public abstract class ClientNotifForwarder { try { wait(); } catch (InterruptedException ire) { - IOException ioe = new IOException(ire.toString()); - EnvHelp.initCause(ioe, ire); - - throw ioe; + throw new IOException(ire.toString(), ire); } } @@ -901,10 +893,7 @@ public abstract class ClientNotifForwarder { try { wait(); } catch (InterruptedException ire) { - IOException ioe = new IOException(ire.toString()); - EnvHelp.initCause(ioe, ire); - - throw ioe; + throw new IOException(ire.toString(), ire); } } diff --git a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java index c7408f524ba1192c204698027f6c098ae3345357..c119ca9c05373bc8bd50582a92bb00121567cbdd 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java @@ -121,9 +121,7 @@ public class ServerNotifForwarder { name.getKeyPropertyList()); } catch (MalformedObjectNameException mfoe) { // impossible, but... - IOException ioe = new IOException(mfoe.getMessage()); - ioe.initCause(mfoe); - throw ioe; + throw new IOException(mfoe.getMessage(), mfoe); } } diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java b/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java index 63b68db88f424285a2632a0504e96e2064859edc..a26cb5dabefb9c2300754420e74c40538b99bd86 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/HashedPasswordManager.java @@ -85,7 +85,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; * clear-text password file. If generated by the user, hashed passwords must * follow the format specified above. */ -final public class HashedPasswordManager { +public final class HashedPasswordManager { private static final class UserCredentials { diff --git a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java index 722d17a28b4ff0b4f74179ec70a0c0dbae1d853d..3e854d60a3e371b6929f246179b29f67850f1ed4 100644 --- a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java +++ b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXPluggableAuthenticator.java @@ -44,7 +44,6 @@ import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import com.sun.jmx.remote.util.ClassLogger; -import com.sun.jmx.remote.util.EnvHelp; /** *

      This class represents a @@ -228,9 +227,7 @@ public final class JMXPluggableAuthenticator implements JMXAuthenticator { se = (SecurityException) exception; } else { msg = "Authentication failed! " + exception.getMessage(); - final SecurityException e = new SecurityException(msg); - EnvHelp.initCause(e, exception); - se = e; + se = new SecurityException(msg, exception); } logException(method, msg, se); throw se; diff --git a/src/java.management/share/classes/java/lang/management/MemoryMXBean.java b/src/java.management/share/classes/java/lang/management/MemoryMXBean.java index 716d2bcefca02a4c752b0f622147625f7850b7ee..f17e5e8077a86c5c947ab6d55458701e6c938d00 100644 --- a/src/java.management/share/classes/java/lang/management/MemoryMXBean.java +++ b/src/java.management/share/classes/java/lang/management/MemoryMXBean.java @@ -207,9 +207,15 @@ public interface MemoryMXBean extends PlatformManagedObject { * Returns the approximate number of objects for which * finalization is pending. * + * @deprecated Finalization has been deprecated for removal. See + * {@link java.lang.Object#finalize} for details. + * * @return the approximate number objects for which finalization - * is pending. + * is pending. If this MemoryMXBean contains information about a JVM in + * which finalization has been disabled or removed, this method always + * returns zero. */ + @Deprecated(since="18") public int getObjectPendingFinalizationCount(); /** diff --git a/src/java.management/share/classes/javax/management/BinaryRelQueryExp.java b/src/java.management/share/classes/javax/management/BinaryRelQueryExp.java index 4f8a9f4cbffac217255b7fee7041582321704e08..0bedf209a6378320d5c38ca308fccb3036114c39 100644 --- a/src/java.management/share/classes/javax/management/BinaryRelQueryExp.java +++ b/src/java.management/share/classes/javax/management/BinaryRelQueryExp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -167,17 +167,18 @@ class BinaryRelQueryExp extends QueryEval implements QueryExp { String sval1 = ((StringValueExp)val1).getValue(); String sval2 = ((StringValueExp)val2).getValue(); + int cmp = sval1.compareTo(sval2); switch (relOp) { case Query.GT: - return sval1.compareTo(sval2) > 0; + return cmp > 0; case Query.LT: - return sval1.compareTo(sval2) < 0; + return cmp < 0; case Query.GE: - return sval1.compareTo(sval2) >= 0; + return cmp >= 0; case Query.LE: - return sval1.compareTo(sval2) <= 0; + return cmp <= 0; case Query.EQ: - return sval1.compareTo(sval2) == 0; + return cmp == 0; } } diff --git a/src/java.management/share/classes/javax/management/MBeanServerFactory.java b/src/java.management/share/classes/javax/management/MBeanServerFactory.java index fb88d7adf53f45e007f0932803f2e86f7dae613f..ae49d8e5b3175396cdd55071b16d129c45108825 100644 --- a/src/java.management/share/classes/javax/management/MBeanServerFactory.java +++ b/src/java.management/share/classes/javax/management/MBeanServerFactory.java @@ -355,7 +355,7 @@ public class MBeanServerFactory { * caller's permissions do not include or imply {@link * MBeanServerPermission}("findMBeanServer"). */ - public synchronized static + public static synchronized ArrayList findMBeanServer(String agentId) { checkPermission("findMBeanServer"); diff --git a/src/java.management/share/classes/javax/management/ObjectName.java b/src/java.management/share/classes/javax/management/ObjectName.java index 24e9f2098dd4bf0c4a61002858189f05cf747284..a46b2c99bede3b19c77e20513bc5d5c180b90055 100644 --- a/src/java.management/share/classes/javax/management/ObjectName.java +++ b/src/java.management/share/classes/javax/management/ObjectName.java @@ -351,7 +351,7 @@ public class ObjectName implements Comparable, QueryExp { /** * a shared empty array for empty property lists */ - static final private Property[] _Empty_property_array = new Property[0]; + private static final Property[] _Empty_property_array = new Property[0]; // Class private fields <============================== diff --git a/src/java.management/share/classes/javax/management/loading/MLet.java b/src/java.management/share/classes/javax/management/loading/MLet.java index 4adf762c69342f601d906d0be73b4d6475f81cd9..bff07766d5763441c637446bfc21ac6b23f0a76f 100644 --- a/src/java.management/share/classes/javax/management/loading/MLet.java +++ b/src/java.management/share/classes/javax/management/loading/MLet.java @@ -25,16 +25,12 @@ package javax.management.loading; -// Java import -import com.sun.jmx.defaults.JmxProperties; - import com.sun.jmx.defaults.ServiceName; import com.sun.jmx.remote.util.EnvHelp; import java.io.Externalizable; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; @@ -71,7 +67,6 @@ import javax.management.ReflectionException; import static com.sun.jmx.defaults.JmxProperties.MLET_LIB_DIR; import static com.sun.jmx.defaults.JmxProperties.MLET_LOGGER; -import com.sun.jmx.defaults.ServiceName; import javax.management.ServiceNotFoundException; /** @@ -1270,24 +1265,16 @@ public class MLet extends java.net.URLClassLoader MLET_LOGGER.log(Level.DEBUG, "Got unexpected exception", e); } } - if (type.compareTo("java.lang.Boolean") == 0) - return Boolean.valueOf(param); - if (type.compareTo("java.lang.Byte") == 0) - return Byte.valueOf(param); - if (type.compareTo("java.lang.Short") == 0) - return Short.valueOf(param); - if (type.compareTo("java.lang.Long") == 0) - return Long.valueOf(param); - if (type.compareTo("java.lang.Integer") == 0) - return Integer.valueOf(param); - if (type.compareTo("java.lang.Float") == 0) - return Float.valueOf(param); - if (type.compareTo("java.lang.Double") == 0) - return Double.valueOf(param); - if (type.compareTo("java.lang.String") == 0) - return param; - - return param; + return switch (type) { + case "java.lang.Boolean" -> Boolean.valueOf(param); + case "java.lang.Byte" -> Byte.valueOf(param); + case "java.lang.Short" -> Short.valueOf(param); + case "java.lang.Long" -> Long.valueOf(param); + case "java.lang.Integer" -> Integer.valueOf(param); + case "java.lang.Float" -> Float.valueOf(param); + case "java.lang.Double" -> Double.valueOf(param); + default -> param; + }; } @SuppressWarnings("removal") diff --git a/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java b/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java index c706ababeca75c7583a757c4fd4559631bc61192..abace393e671fd4b90149249ba76796794e9e4bc 100644 --- a/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java +++ b/src/java.management/share/classes/javax/management/modelmbean/RequiredModelMBean.java @@ -144,7 +144,7 @@ public class RequiredModelMBean private static final JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess(); @SuppressWarnings("removal") - final private AccessControlContext acc = AccessController.getContext(); + private final AccessControlContext acc = AccessController.getContext(); /*************************************/ /* constructors */ @@ -192,7 +192,7 @@ public class RequiredModelMBean * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an - * {link java.lang.IllegalArgumentException}: + * {@link java.lang.IllegalArgumentException}: * The MBeanInfo passed in parameter is null. * **/ diff --git a/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java b/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java index a7ff232e8e4ef786bd91006e34afd5d45db258fc..ed7edcab09b365adf093124d498c55e91aaaaa5f 100644 --- a/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java +++ b/src/java.management/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,6 @@ package javax.management.openmbean; -// java import -// import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -44,7 +42,6 @@ import javax.management.Descriptor; import javax.management.DescriptorRead; import javax.management.ImmutableDescriptor; import javax.management.MBeanAttributeInfo; -import com.sun.jmx.remote.util.EnvHelp; import sun.reflect.misc.MethodUtil; import sun.reflect.misc.ReflectUtil; @@ -626,7 +623,7 @@ public class OpenMBeanAttributeInfoSupport final String msg = "Cannot convert descriptor field " + name + " to " + openType.getTypeName(); - throw EnvHelp.initCause(new IllegalArgumentException(msg), e); + throw new IllegalArgumentException(msg, e); } } diff --git a/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java b/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java index 14f4189afc60ca59a81ed93c6e9c9050236b3852..c3e580cf911bca5592ca64aceee154ba3f020f6c 100644 --- a/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java +++ b/src/java.management/share/classes/javax/management/remote/JMXConnectorFactory.java @@ -619,8 +619,7 @@ public class JMXConnectorFactory { if (e instanceof IOException) { exception = (IOException) e; } else { - exception = EnvHelp.initCause( - new IOException(e.getMessage()), e); + exception = new IOException(e.getMessage(), e); } } } diff --git a/src/java.management/share/classes/javax/management/timer/Timer.java b/src/java.management/share/classes/javax/management/timer/Timer.java index edbf85e86271feebcf8fec93e9ab6626ce1c0c05..6df2d7df047350d362ba51f71cb2fd61d6a714f3 100644 --- a/src/java.management/share/classes/javax/management/timer/Timer.java +++ b/src/java.management/share/classes/javax/management/timer/Timer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,7 +127,7 @@ public class Timer extends NotificationBroadcasterSupport * Table containing all the timer notifications of this timer, * with the associated date, period and number of occurrences. */ - final private Map timerTable = + private final Map timerTable = new HashMap<>(); /** @@ -162,7 +162,7 @@ public class Timer extends NotificationBroadcasterSupport * The notification counter ID. * Used to keep the max key value inserted into the timer table. */ - volatile private int counterID = 0; + private volatile int counterID = 0; private java.util.Timer timer; diff --git a/src/java.management/share/classes/sun/management/ClassLoadingImpl.java b/src/java.management/share/classes/sun/management/ClassLoadingImpl.java index c59297b90b47145e012d0ae7357ba0282796d238..9c3c62158b7f96ce3db6a67f2bb30cf69029a51d 100644 --- a/src/java.management/share/classes/sun/management/ClassLoadingImpl.java +++ b/src/java.management/share/classes/sun/management/ClassLoadingImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,7 @@ class ClassLoadingImpl implements ClassLoadingMXBean { setVerboseClass(value); } - native static void setVerboseClass(boolean value); + static native void setVerboseClass(boolean value); public ObjectName getObjectName() { return Util.newObjectName(ManagementFactory.CLASS_LOADING_MXBEAN_NAME); diff --git a/src/java.management/share/classes/sun/management/MemoryImpl.java b/src/java.management/share/classes/sun/management/MemoryImpl.java index 7850b90e7838c5a98e85ba2614505835ea8ff6d5..5bdbe7b63499bd516fa6042b940feeec0f31bcff 100644 --- a/src/java.management/share/classes/sun/management/MemoryImpl.java +++ b/src/java.management/share/classes/sun/management/MemoryImpl.java @@ -58,6 +58,7 @@ class MemoryImpl extends NotificationEmitterSupport this.jvm = vm; } + @SuppressWarnings("deprecation") public int getObjectPendingFinalizationCount() { return jdk.internal.misc.VM.getFinalRefCount(); } diff --git a/src/java.management/share/classes/sun/management/NotificationEmitterSupport.java b/src/java.management/share/classes/sun/management/NotificationEmitterSupport.java index da6898c84af922cf39907322e5756cae6b927588..ab7c1368656b447d123dd391ad4ed9e67908219d 100644 --- a/src/java.management/share/classes/sun/management/NotificationEmitterSupport.java +++ b/src/java.management/share/classes/sun/management/NotificationEmitterSupport.java @@ -193,5 +193,5 @@ public abstract class NotificationEmitterSupport implements NotificationEmitter */ private List listenerList = Collections.emptyList(); - abstract public MBeanNotificationInfo[] getNotificationInfo(); + public abstract MBeanNotificationInfo[] getNotificationInfo(); } diff --git a/src/java.management/share/classes/sun/management/VMManagementImpl.java b/src/java.management/share/classes/sun/management/VMManagementImpl.java index e9b8f87f5a5d9f81e62d526c678102e5c422f826..6b2a456bd6e403e0ef1a4c373117d7e5f401ca54 100644 --- a/src/java.management/share/classes/sun/management/VMManagementImpl.java +++ b/src/java.management/share/classes/sun/management/VMManagementImpl.java @@ -65,8 +65,8 @@ class VMManagementImpl implements VMManagement { } initOptionalSupportFields(); } - private native static String getVersion0(); - private native static void initOptionalSupportFields(); + private static native String getVersion0(); + private static native void initOptionalSupportFields(); // Optional supports public boolean isCompilationTimeMonitoringSupported() { diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java b/src/java.naming/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java index 94c15c09d11cd9ac9788a82656f1445c194432eb..5c7644212f979674ffc08774a0c8fcfdc5cb686a 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java @@ -383,7 +383,7 @@ abstract class AbstractLdapNamingEnumeration listArg = ne.listArg; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected final void finalize() { cleanup(); } diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/Connection.java b/src/java.naming/share/classes/com/sun/jndi/ldap/Connection.java index d6de10e643b33f4c8772ca2e552d475deecc6e4f..80d788d937a88ecafe9c2d8bb157ef31bb32159e 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/Connection.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/Connection.java @@ -689,7 +689,7 @@ public final class Connection implements Runnable { // "synchronize" might lead to deadlock so don't synchronize method // Use streamLock instead for synchronizing update to stream - synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) { + public synchronized void replaceStreams(InputStream newIn, OutputStream newOut) { if (debug) { System.err.println("Replacing " + inStream + " with: " + newIn); System.err.println("Replacing " + outStream + " with: " + newOut); @@ -712,7 +712,7 @@ public final class Connection implements Runnable { /* * Replace streams and set isUpdradedToStartTls flag to the provided value */ - synchronized public void replaceStreams(InputStream newIn, OutputStream newOut, boolean isStartTls) { + public synchronized void replaceStreams(InputStream newIn, OutputStream newOut, boolean isStartTls) { synchronized (startTlsLock) { replaceStreams(newIn, newOut); isUpgradedToStartTls = isStartTls; @@ -731,7 +731,7 @@ public final class Connection implements Runnable { * This ensures that there is no contention between the main thread * and the Connection thread when the main thread updates inStream. */ - synchronized private InputStream getInputStream() { + private synchronized InputStream getInputStream() { return inStream; } @@ -1043,7 +1043,7 @@ public final class Connection implements Runnable { */ private volatile HandshakeListener tlsHandshakeListener; - synchronized public void setHandshakeCompletedListener(SSLSocket sslSocket) { + public synchronized void setHandshakeCompletedListener(SSLSocket sslSocket) { if (tlsHandshakeListener != null) tlsHandshakeListener.tlsHandshakeCompleted.cancel(false); diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/Filter.java b/src/java.naming/share/classes/com/sun/jndi/ldap/Filter.java index ab43fa7aa9c572563864fe019012ae0620947503..5b172c44a81d4b3eaf7dab59ade34f9472986669 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/Filter.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/Filter.java @@ -307,7 +307,6 @@ final class Filter { dbgIndent++; } - String type, value; int valueStart, valueEnd, typeStart, typeEnd; int eq; diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/LdapClient.java b/src/java.naming/share/classes/com/sun/jndi/ldap/LdapClient.java index 3e916a5d7f8a8d476dba054d79c602b602d094e6..4834b6e530aec1bc71a22fcd2151c19a4766b5d5 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/LdapClient.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/LdapClient.java @@ -312,7 +312,7 @@ public final class LdapClient implements PooledConnection { * @param auth The authentication mechanism * */ - synchronized public LdapResult ldapBind(String dn, byte[]toServer, + public synchronized LdapResult ldapBind(String dn, byte[]toServer, Control[] bindCtls, String auth, boolean pauseAfterReceipt) throws java.io.IOException, NamingException { @@ -477,7 +477,7 @@ public final class LdapClient implements PooledConnection { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() { if (debug > 0) System.err.println("LdapClient: finalize " + this); forceClose(pooled); @@ -486,7 +486,7 @@ public final class LdapClient implements PooledConnection { /* * Used by connection pooling to close physical connection. */ - synchronized public void closeConnection() { + public synchronized void closeConnection() { forceClose(false); // this is a pool callback so no need to clean pool } diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java b/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java index 332e7dbea2bdbf2a6f0d1873fddbed8890cfd50f..9a918edf0c3dd5451a86c41d1ba1bf4e2355c7ee 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/LdapCtx.java @@ -2603,7 +2603,6 @@ public final class LdapCtx extends ComponentDirContext Vector> referrals = new Vector<>(urlCount); int iURL; - int i = 0; separator = refString.indexOf('\n'); iURL = separator + 1; @@ -2640,7 +2639,7 @@ public final class LdapCtx extends ComponentDirContext // ----------------- Connection --------------------- - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() { try { close(); @@ -2649,7 +2648,7 @@ public final class LdapCtx extends ComponentDirContext } } - synchronized public void close() throws NamingException { + public synchronized void close() throws NamingException { if (debug) { System.err.println("LdapCtx: close() called " + this); (new Throwable()).printStackTrace(); diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/DefaultCallbackHandler.java b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/DefaultCallbackHandler.java index 2a782c0e9cc5442930c6193ceb4e00defe09e2e8..b6388915840b2d4df99c259f4b102b82acd67aa3 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/DefaultCallbackHandler.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/DefaultCallbackHandler.java @@ -131,7 +131,7 @@ final class DefaultCallbackHandler implements CallbackHandler { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { clearPassword(); } diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslOutputStream.java b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslOutputStream.java index e8e73c7b825ee3ef6a8023649f580c34875877cb..30d64fc86119b69e4390c3ca469e195c4a9fcfc7 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslOutputStream.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ class SaslOutputStream extends FilterOutputStream { */ public void write(byte[] buffer, int offset, int total) throws IOException { int count; - byte[] wrappedToken, saslBuffer; + byte[] wrappedToken; // "Packetize" buffer to be within rawSendSize if (debug) { diff --git a/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java b/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java index a2a971826eb84c9f14cfe3c0ae65a2559aefa099..1a6d930460e6ebe618e47a52dae793964427cba2 100644 --- a/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java +++ b/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -134,7 +134,7 @@ public class Continuation extends ResolveResult { /** * Fills in an exception's fields using data from this Continuation. * The resolved name is set by subtracting remainingName from starter. - * %%% This might not not always produce the correct answer wrt trailing "/". + * %%% This might not always produce the correct answer wrt trailing "/". * If the exception is a CannotProceedException, its environment, * altName, and altNameCtx fields are set using this continuation's * environment, relativeResolvedName, and resolvedContext. @@ -296,8 +296,6 @@ public class Continuation extends ResolveResult { * @param currCtx The non-null context from which relResName is to be resolved. */ public void setContinueNNS(Object resObj, Name relResName, Context currCtx) { - CompositeName rname = new CompositeName(); - setContinue(resObj, relResName, currCtx, PartialCompositeContext._NNS_NAME); } diff --git a/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java b/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java index 19b8eb2158813e87994ba16aec276cf8cd4585b2..2359292e422bf07ff600bede6892f22c546f09d3 100644 --- a/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java +++ b/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -510,12 +510,11 @@ public abstract class PartialCompositeContext implements Context, Resolver { throws NamingException { Object obj = cont.getResolvedObj(); - PartialCompositeContext pctx = null; - if (obj instanceof PartialCompositeContext) { + if (obj instanceof PartialCompositeContext partialCtx) { // Just cast if octx already is PartialCompositeContext // %%% ignoring environment for now - return (PartialCompositeContext)obj; + return partialCtx; } else { throw cont.fillInException(new CannotProceedException()); } diff --git a/src/java.net.http/share/classes/java/net/http/HttpRequest.java b/src/java.net.http/share/classes/java/net/http/HttpRequest.java index 5dc0486826aebc9f934b296b88fa39d5a61de556..fc9c10b14bc0b055397c9b82c542b4c2e627b3d8 100644 --- a/src/java.net.http/share/classes/java/net/http/HttpRequest.java +++ b/src/java.net.http/share/classes/java/net/http/HttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -256,6 +256,19 @@ public abstract class HttpRequest { */ public Builder DELETE(); + /** + * Sets the request method of this builder to HEAD. + * + * @implSpec The default implementation is expected to have the same behaviour as: + * {@code return method("HEAD", BodyPublishers.noBody());} + * + * @return this builder + * @since 18 + */ + default Builder HEAD() { + return method("HEAD", BodyPublishers.noBody()); + } + /** * Sets the request method and request body of this builder to the * given values. @@ -360,12 +373,13 @@ public abstract class HttpRequest { request.bodyPublisher().ifPresentOrElse( // if body is present, set it bodyPublisher -> builder.method(method, bodyPublisher), - // otherwise, the body is absent, special case for GET/DELETE, + // otherwise, the body is absent, special case for GET/DELETE/HEAD, // or else use empty body () -> { switch (method) { case "GET" -> builder.GET(); case "DELETE" -> builder.DELETE(); + case "HEAD" -> builder.HEAD(); default -> builder.method(method, HttpRequest.BodyPublishers.noBody()); } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java b/src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java index 6b112a65cbba3838d6162be6f002e4364d9c091e..2561afd645d07ceff8c4ce329efd2fb60915f7ca 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/AuthenticationFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -323,7 +323,7 @@ class AuthenticationFilter implements HeaderFilter { return req; } else if (au.retries > retry_limit) { throw new IOException("too many authentication attempts. Limit: " + - Integer.toString(retry_limit)); + retry_limit); } else { // we sent credentials, but they were rejected if (au.fromcache) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http1AsyncReceiver.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http1AsyncReceiver.java index 115077da0d247dba9d823f114ac61a7e17e414c9..75cf84c53cd96cc28b59535fc22c1b7c8f6588ff 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http1AsyncReceiver.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http1AsyncReceiver.java @@ -116,7 +116,7 @@ class Http1AsyncReceiver { public AbstractSubscription subscription(); /** - * Called to make sure resources are released when the + * Called to make sure resources are released * when the Http1AsyncReceiver is stopped. * @param error The Http1AsyncReceiver pending error ref, * if any. @@ -478,7 +478,7 @@ class Http1AsyncReceiver { // the pool. if (retry && (ex instanceof IOException)) { // could be either EOFException, or - // IOException("connection reset by peer), or + // IOException("connection reset by peer"), or // SSLHandshakeException resulting from the server having // closed the SSL session. if (received.get() == 0) { @@ -709,7 +709,7 @@ class Http1AsyncReceiver { for (ByteBuffer b : lbb) { if (!sbb.remove(b)) { msg.append(sep) - .append(String.valueOf(b)) + .append(b) .append("[remaining=") .append(b.remaining()) .append(", position=") @@ -727,14 +727,12 @@ class Http1AsyncReceiver { String dbgString() { String tag = dbgTag; if (tag == null) { - String flowTag = null; Http1Exchange exchg = owner; Object flow = (exchg != null) ? exchg.connection().getConnectionFlow() : null; - flowTag = tag = flow == null ? null: (String.valueOf(flow)); - if (flowTag != null) { - dbgTag = tag = "Http1AsyncReceiver("+ flowTag + ")"; + if (flow != null) { + dbgTag = tag = "Http1AsyncReceiver(" + flow + ")"; } else { tag = "Http1AsyncReceiver(?)"; } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Exchange.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Exchange.java index 6edfe99f13aec1ee2f1bfbe37fe919c1c4df0154..4db164364077b411121e3a76a6ded331f78db26e 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Exchange.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Exchange.java @@ -117,7 +117,7 @@ class Http1Exchange extends ExchangeImpl { * concrete implementations: {@link Http1Request.StreamSubscriber}, and * {@link Http1Request.FixedContentSubscriber}, for receiving chunked and * fixed length bodies, respectively. */ - static abstract class Http1BodySubscriber implements Flow.Subscriber { + abstract static class Http1BodySubscriber implements Flow.Subscriber { final MinimalFuture whenSubscribed = new MinimalFuture<>(); private volatile Flow.Subscription subscription; volatile boolean complete; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Request.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Request.java index 5d657ec291e074fea5fc2a46506810c937dc2612..4e4c96909f5c68e8c34b3f9a875c63a90fb3ba06 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Request.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Request.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -109,21 +109,22 @@ class Http1Request { final HttpHeaders uh = userHeaders; // Filter any headers from systemHeaders that are set in userHeaders - systemHeaders = HttpHeaders.of(systemHeaders.map(), (k,v) -> uh.firstValue(k).isEmpty()); + final HttpHeaders sh = HttpHeaders.of(systemHeaders.map(), + (k,v) -> uh.firstValue(k).isEmpty()); // If we're sending this request through a tunnel, // then don't send any preemptive proxy-* headers that // the authentication filter may have saved in its // cache. - collectHeaders1(sb, systemHeaders, nocookies); + collectHeaders1(sb, sh, nocookies); // If we're sending this request through a tunnel, // don't send any user-supplied proxy-* headers // to the target server. - collectHeaders1(sb, userHeaders, nocookies); + collectHeaders1(sb, uh, nocookies); - // Gather all 'Cookie:' headers and concatenate their - // values in a single line. + // Gather all 'Cookie:' headers from the unfiltered system headers, + // and the user headers, and concatenate their values in a single line collectCookies(sb, systemHeaders, userHeaders); // terminate headers @@ -236,7 +237,7 @@ class Http1Request { if (defaultPort) { return host; } else { - return host + ":" + Integer.toString(port); + return host + ":" + port; } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Response.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Response.java index 8090568c4e4516f95186d55718f6d493a0ee692f..1cf818eb7628390ed3242463eacaeb23e60d550e 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http1Response.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http1Response.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,14 +71,14 @@ class Http1Response { private volatile EOFException eof; private volatile BodyParser bodyParser; // max number of bytes of (fixed length) body to ignore on redirect - private final static int MAX_IGNORE = 1024; + private static final int MAX_IGNORE = 1024; // Revisit: can we get rid of this? static enum State {INITIAL, READING_HEADERS, READING_BODY, DONE} private volatile State readProgress = State.INITIAL; final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG); - final static AtomicLong responseCount = new AtomicLong(); + static final AtomicLong responseCount = new AtomicLong(); final long id = responseCount.incrementAndGet(); private Http1HeaderParser hd; @@ -114,7 +114,7 @@ class Http1Response { } // The ClientRefCountTracker is used to track the state - // of a pending operation. Altough there usually is a single + // of a pending operation. Although there usually is a single // point where the operation starts, it may terminate at // different places. private final class ClientRefCountTracker { @@ -294,7 +294,7 @@ class Http1Response { * subscribed. * @param The type of response. */ - final static class Http1BodySubscriber implements TrustedSubscriber { + static final class Http1BodySubscriber implements TrustedSubscriber { final HttpResponse.BodySubscriber userSubscriber; final AtomicBoolean completed = new AtomicBoolean(); volatile Throwable withError; @@ -585,7 +585,7 @@ class Http1Response { } - static abstract class Receiver + abstract static class Receiver implements Http1AsyncReceiver.Http1AsyncDelegate { abstract void start(T parser); abstract CompletableFuture completion(); @@ -828,7 +828,7 @@ class Http1Response { @Override public String toString() { - return super.toString() + "/parser=" + String.valueOf(parser); + return super.toString() + "/parser=" + parser; } } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http2ClientImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http2ClientImpl.java index 6dc465adc236ae40ef4a7f6d4767f35cce4cca87..4101133a025d87c576bcbf4e2379f19034f6b540 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http2ClientImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http2ClientImpl.java @@ -54,7 +54,7 @@ import static jdk.internal.net.http.frame.SettingsFrame.MAX_FRAME_SIZE; */ class Http2ClientImpl { - final static Logger debug = + static final Logger debug = Utils.getDebugLogger("Http2ClientImpl"::toString, Utils.DEBUG); private final HttpClientImpl client; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java b/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java index 59c88e9f09984f86a3e3ff002b800894787f492d..6a07d755e69684ba34138b7697e128295d7eccf4 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Http2Connection.java @@ -113,14 +113,14 @@ import static jdk.internal.net.http.frame.SettingsFrame.*; class Http2Connection { final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG); - final static Logger DEBUG_LOGGER = + static final Logger DEBUG_LOGGER = Utils.getDebugLogger("Http2Connection"::toString, Utils.DEBUG); private final Logger debugHpack = Utils.getHpackLogger(this::dbgString, Utils.DEBUG_HPACK); static final ByteBuffer EMPTY_TRIGGER = ByteBuffer.allocate(0); - static private final int MAX_CLIENT_STREAM_ID = Integer.MAX_VALUE; // 2147483647 - static private final int MAX_SERVER_STREAM_ID = Integer.MAX_VALUE - 1; // 2147483646 + private static final int MAX_CLIENT_STREAM_ID = Integer.MAX_VALUE; // 2147483647 + private static final int MAX_SERVER_STREAM_ID = Integer.MAX_VALUE - 1; // 2147483646 /** * Flag set when no more streams to be opened on this connection. @@ -1008,7 +1008,7 @@ class Http2Connection { throws IOException { shutdown(new IOException( - String.valueOf(connection.channel().getLocalAddress()) + connection.channel().getLocalAddress() +": GOAWAY received")); } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java index ada37a1fbe9c38d6ae1a60693d6355625c2ce19e..6394b7b3cfa18bdcd29ead3d5dd38450eef607ac 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpClientImpl.java @@ -135,7 +135,7 @@ final class HttpClientImpl extends HttpClient implements Trackable { * is the SelectorManager thread. If the current thread is not * the selector manager thread the given task is executed inline. */ - final static class DelegatingExecutor implements Executor { + static final class DelegatingExecutor implements Executor { private final BooleanSupplier isInSelectorThread; private final Executor delegate; DelegatingExecutor(BooleanSupplier isInSelectorThread, Executor delegate) { @@ -436,7 +436,7 @@ final class HttpClientImpl extends HttpClient implements Trackable { return pendingOperationCount.get(); } - final static class HttpClientTracker implements Tracker { + static final class HttpClientTracker implements Tracker { final AtomicLong httpCount; final AtomicLong http2Count; final AtomicLong websocketCount; @@ -670,7 +670,7 @@ final class HttpClientImpl extends HttpClient implements Trackable { } // Main loop for this client's selector - private final static class SelectorManager extends Thread { + private static final class SelectorManager extends Thread { // For testing purposes we have an internal System property that // can control the frequency at which the selector manager will wake @@ -1007,7 +1007,7 @@ final class HttpClientImpl extends HttpClient implements Trackable { private final SelectableChannel chan; private final Selector selector; private final Set pending; - private final static Logger debug = + private static final Logger debug = Utils.getDebugLogger("SelectorAttachment"::toString, Utils.DEBUG); private int interestOps; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpConnection.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpConnection.java index 6f47a0bad6a4bb5950f14de5b665a166b6519fe6..1fe3536b83157d07a0db6111ef6be53c03365a68 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpConnection.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpConnection.java @@ -67,7 +67,7 @@ import static jdk.internal.net.http.common.Utils.ProxyHeaders; abstract class HttpConnection implements Closeable { final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG); - final static Logger DEBUG_LOGGER = Utils.getDebugLogger( + static final Logger DEBUG_LOGGER = Utils.getDebugLogger( () -> "HttpConnection(SocketTube(?))", Utils.DEBUG); /** The address this connection is connected to. Could be a server or a proxy. */ diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestBuilderImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestBuilderImpl.java index d11a18f7c5858bf9aeea80ed3ad091cd1e3849d9..e4dee55d8ea376b897d55cdea4740c65708a02e5 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestBuilderImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestBuilderImpl.java @@ -182,6 +182,11 @@ public class HttpRequestBuilderImpl implements HttpRequest.Builder { return method0("DELETE", null); } + @Override + public HttpRequest.Builder HEAD() { + return method0("HEAD", null); + } + @Override public HttpRequest.Builder PUT(BodyPublisher body) { return method0("PUT", requireNonNull(body)); diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java index d2b908dffa525fcb30d7626b927f989dc695c1dd..a04ded70480a03b3a739e8b59d9c54bc0e61d307 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/HttpRequestImpl.java @@ -44,7 +44,6 @@ import java.net.http.HttpRequest; import jdk.internal.net.http.common.HttpHeadersBuilder; import jdk.internal.net.http.common.Utils; -import jdk.internal.net.http.websocket.OpeningHandshake; import jdk.internal.net.http.websocket.WebSocketRequest; import static jdk.internal.net.http.common.Utils.ALLOWED_HEADERS; @@ -216,7 +215,7 @@ public class HttpRequestImpl extends HttpRequest implements WebSocketRequest { this.systemHeadersBuilder.map().putAll(headers.systemHeaders().map()); this.userHeaders = headers.userHeaders(); this.uri = URI.create("socket://" + authority.getHostString() + ":" - + Integer.toString(authority.getPort()) + "/"); + + authority.getPort() + "/"); this.proxy = null; this.requestPublisher = null; this.authority = authority; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java index 1a81b3edcbdc648f98b902d521791f796b092352..9506d1333240b0d78d6e49350c7262a35b4cec1d 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/ResponseSubscribers.java @@ -362,7 +362,7 @@ public class ResponseSubscribers { result.completeExceptionally(throwable); } - static private byte[] join(List bytes) { + private static byte[] join(List bytes) { int size = Utils.remaining(bytes, Integer.MAX_VALUE); byte[] res = new byte[size]; int from = 0; @@ -396,7 +396,7 @@ public class ResponseSubscribers { public static class HttpResponseInputStream extends InputStream implements TrustedSubscriber { - final static int MAX_BUFFERS_IN_QUEUE = 1; // lock-step with the producer + static final int MAX_BUFFERS_IN_QUEUE = 1; // lock-step with the producer // An immutable ByteBuffer sentinel to mark that the last byte was received. private static final ByteBuffer LAST_BUFFER = ByteBuffer.wrap(new byte[0]); @@ -882,7 +882,7 @@ public class ResponseSubscribers { // A subscription that wraps an upstream subscription and // holds a reference to a subscriber. The subscriber reference // is cleared when the subscription is cancelled - final static class SubscriptionRef implements Flow.Subscription { + static final class SubscriptionRef implements Flow.Subscription { final Flow.Subscription subscription; final SubscriberRef subscriberRef; SubscriptionRef(Flow.Subscription subscription, @@ -1086,7 +1086,7 @@ public class ResponseSubscribers { * Invokes bs::getBody using the provided executor. * If invoking bs::getBody requires an executor, and the given executor * is a {@link HttpClientImpl.DelegatingExecutor}, then the executor's - * delegate is used. If an error occurs anywhere then the given {code cf} + * delegate is used. If an error occurs anywhere then the given {@code cf} * is completed exceptionally (this method does not throw). * @param e The executor that should be used to call bs::getBody * @param bs The BodySubscriber diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/SocketTube.java b/src/java.net.http/share/classes/jdk/internal/net/http/SocketTube.java index b0b5c373a90ecb0f37221ae87de547974993884e..321a228e776b47901c525bc1abe30f07243578c4 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/SocketTube.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/SocketTube.java @@ -226,7 +226,7 @@ final class SocketTube implements FlowTube { * signaled. It is the responsibility of the code triggered by * {@code signalEvent} to resume the event if required. */ - private static abstract class SocketFlowEvent extends AsyncEvent { + private abstract static class SocketFlowEvent extends AsyncEvent { final SocketChannel channel; final int defaultInterest; volatile int interestOps; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java b/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java index cf9d548911c486cb1cb572447238604b2463d359..5fc8eb3677222f807ebe07fe04c83acbb1f20241 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java @@ -97,6 +97,7 @@ import jdk.internal.net.http.hpack.DecodingCallback; */ class Stream extends ExchangeImpl { + private static final String COOKIE_HEADER = "Cookie"; final Logger debug = Utils.getDebugLogger(this::dbgString, Utils.DEBUG); final ConcurrentLinkedQueue inputQ = new ConcurrentLinkedQueue<>(); @@ -245,7 +246,7 @@ class Stream extends ExchangeImpl { debug.log("already completed: dropping error %s", (Object) t); } } catch (Throwable x) { - Log.logError("Subscriber::onError threw exception: {0}", (Object) t); + Log.logError("Subscriber::onError threw exception: {0}", t); } finally { cancelImpl(t); drainInputQueue(); @@ -328,10 +329,7 @@ class Stream extends ExchangeImpl { @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("streamid: ") - .append(streamid); - return sb.toString(); + return "streamid: " + streamid; } private void receiveDataFrame(DataFrame df) { @@ -398,7 +396,6 @@ class Stream extends ExchangeImpl { return sendBodyImpl().thenApply( v -> this); } - @SuppressWarnings("unchecked") Stream(Http2Connection connection, Exchange e, WindowController windowController) @@ -455,7 +452,7 @@ class Stream extends ExchangeImpl { case ResetFrame.TYPE -> incoming_reset((ResetFrame) frame); case PriorityFrame.TYPE -> incoming_priority((PriorityFrame) frame); - default -> throw new IOException("Unexpected frame: " + frame.toString()); + default -> throw new IOException("Unexpected frame: " + frame); } } @@ -652,10 +649,16 @@ class Stream extends ExchangeImpl { // Filter context restricted from userHeaders userh = HttpHeaders.of(userh.map(), Utils.CONTEXT_RESTRICTED(client())); + // Don't override Cookie values that have been set by the CookieHandler. final HttpHeaders uh = userh; + BiPredicate overrides = + (k, v) -> COOKIE_HEADER.equalsIgnoreCase(k) + || uh.firstValue(k).isEmpty(); // Filter any headers from systemHeaders that are set in userHeaders - sysh = HttpHeaders.of(sysh.map(), (k,v) -> uh.firstValue(k).isEmpty()); + // except for "Cookie:" - user cookies will be appended to system + // cookies + sysh = HttpHeaders.of(sysh.map(), overrides); OutgoingHeaders> f = new OutgoingHeaders<>(sysh, userh, this); if (contentLength == 0) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/DebugLogger.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/DebugLogger.java index 57358e33bcc11ce25468959e804a72d5f2875a67..01f962f5bbe5d94f4b98def5bbfbaffca73e5050 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/DebugLogger.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/DebugLogger.java @@ -46,19 +46,19 @@ import java.util.function.Supplier; */ final class DebugLogger implements Logger { // deliberately not in the same subtree than standard loggers. - final static String HTTP_NAME = "jdk.internal.httpclient.debug"; - final static String WS_NAME = "jdk.internal.httpclient.websocket.debug"; - final static String HPACK_NAME = "jdk.internal.httpclient.hpack.debug"; - final static System.Logger HTTP = System.getLogger(HTTP_NAME); - final static System.Logger WS = System.getLogger(WS_NAME); - final static System.Logger HPACK = System.getLogger(HPACK_NAME); + static final String HTTP_NAME = "jdk.internal.httpclient.debug"; + static final String WS_NAME = "jdk.internal.httpclient.websocket.debug"; + static final String HPACK_NAME = "jdk.internal.httpclient.hpack.debug"; + static final System.Logger HTTP = System.getLogger(HTTP_NAME); + static final System.Logger WS = System.getLogger(WS_NAME); + static final System.Logger HPACK = System.getLogger(HPACK_NAME); private static final DebugLogger NO_HTTP_LOGGER = new DebugLogger(HTTP, "HTTP"::toString, Level.OFF, Level.OFF); private static final DebugLogger NO_WS_LOGGER = new DebugLogger(HTTP, "WS"::toString, Level.OFF, Level.OFF); private static final DebugLogger NO_HPACK_LOGGER = new DebugLogger(HTTP, "HPACK"::toString, Level.OFF, Level.OFF); - final static long START_NANOS = System.nanoTime(); + static final long START_NANOS = System.nanoTime(); private final Supplier dbgTag; private final Level errLevel; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/Demand.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/Demand.java index 842b57588e7200d12b2051effd87b7674072a6b1..2e9575d2885e1a3c7921c46834a0112f3d143004 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/Demand.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/Demand.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,7 @@ public final class Demand { */ public boolean increase(long n) { if (n <= 0) { - throw new IllegalArgumentException("non-positive subscription request: " + String.valueOf(n)); + throw new IllegalArgumentException("non-positive subscription request: " + n); } long prev = val.getAndAccumulate(n, (p, i) -> p + i < 0 ? Long.MAX_VALUE : p + i); return prev == 0; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/FlowTube.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/FlowTube.java index f079f400c123bd67392fe9d6bc51256043c14429..023086e3dee5fdb92c2c73b0a4614eeaa9b2a353 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/FlowTube.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/FlowTube.java @@ -138,7 +138,7 @@ public interface FlowTube extends * It is not required that a {@code TubePublisher} implementation extends * this class. */ - static abstract class AbstractTubePublisher implements TubePublisher { + abstract static class AbstractTubePublisher implements TubePublisher { static final class TubePublisherWrapper extends AbstractTubePublisher { final Flow.Publisher> delegate; public TubePublisherWrapper(Flow.Publisher> delegate) { @@ -156,7 +156,7 @@ public interface FlowTube extends * It is not required that a {@code TubeSubscriber} implementation extends * this class. */ - static abstract class AbstractTubeSubscriber implements TubeSubscriber { + abstract static class AbstractTubeSubscriber implements TubeSubscriber { static final class TubeSubscriberWrapper extends AbstractTubeSubscriber { final Flow.Subscriber> delegate; TubeSubscriberWrapper(Flow.Subscriber> delegate) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/MinimalFuture.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/MinimalFuture.java index 8fc79b0437cc01bbfaf622c2060d03c82fa61908..ddbcce661aa172bf5b2c46956415a0ac0f0dbcf0 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/MinimalFuture.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/MinimalFuture.java @@ -42,7 +42,7 @@ public final class MinimalFuture extends CompletableFuture { U get() throws Throwable; } - private final static AtomicLong TOKENS = new AtomicLong(); + private static final AtomicLong TOKENS = new AtomicLong(); private final long id; private final Cancelable cancelable; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLFlowDelegate.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLFlowDelegate.java index 3f3e4ff339a4601d2f974e5a96f1f4d7327cd74a..cd248b46fb7ee6f116cb09e4f5d46ddc9c371188 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLFlowDelegate.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLFlowDelegate.java @@ -938,7 +938,7 @@ public class SSLFlowDelegate { @Override public String toString() { return "WRITER: " + super.toString() - + ", writeList size: " + Integer.toString(writeList.size()) + + ", writeList size: " + writeList.size() + ", scheduler: " + (scheduler.isStopped() ? "stopped" : "running") + ", status: " + lastWrappedStatus; //" writeList: " + writeList.toString(); @@ -1113,7 +1113,7 @@ public class SSLFlowDelegate { exec.execute(() -> { try { List nextTasks = tasks; - if (debug.on()) debug.log("#tasks to execute: " + Integer.toString(nextTasks.size())); + if (debug.on()) debug.log("#tasks to execute: " + nextTasks.size()); do { nextTasks.forEach(Runnable::run); if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLTube.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLTube.java index 620b9af372e9ee09959d96187a7d4798027cddbe..42174ef9c44feacbed750301ba1dbc14bd7162fb 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLTube.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/SSLTube.java @@ -184,7 +184,7 @@ public class SSLTube implements FlowTube { // The DelegateWrapper wraps a subscribed {@code Flow.Subscriber} and // tracks the subscriber's state. In particular it makes sure that // onComplete/onError are not called before onSubscribed. - final static class DelegateWrapper implements FlowTube.TubeSubscriber { + static final class DelegateWrapper implements FlowTube.TubeSubscriber { private final FlowTube.TubeSubscriber delegate; private final Logger debug; volatile boolean subscribedCalled; diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/SequentialScheduler.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/SequentialScheduler.java index 499aa944ac38b106452dd0558760e5decf36ca31..88809ec0678a5781c7a735bfe3ab3d3f887ad292 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/SequentialScheduler.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/SequentialScheduler.java @@ -111,7 +111,7 @@ public final class SequentialScheduler { * later time, and maybe in different thread. This type exists for * readability purposes at use-sites only. */ - public static abstract class DeferredCompleter { + public abstract static class DeferredCompleter { /** Extensible from this (outer) class ONLY. */ private DeferredCompleter() { } @@ -140,7 +140,7 @@ public final class SequentialScheduler { * A simple and self-contained task that completes once its {@code run} * method returns. */ - public static abstract class CompleteRestartableTask + public abstract static class CompleteRestartableTask implements RestartableTask { @Override diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/SubscriberWrapper.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/SubscriberWrapper.java index 7c7772cc08530640c777dd7fb958b23fdde2577a..1dec768d004d59b89985b690989db67084550b32 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/SubscriberWrapper.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/SubscriberWrapper.java @@ -490,13 +490,13 @@ public abstract class SubscriberWrapper public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SubscriberWrapper:") - .append(" upstreamCompleted: ").append(Boolean.toString(upstreamCompleted)) - .append(" upstreamWindow: ").append(upstreamWindow.toString()) - .append(" downstreamCompleted: ").append(Boolean.toString(downstreamCompleted)) - .append(" completionAcknowledged: ").append(Boolean.toString(completionAcknowledged)) - .append(" outputQ size: ").append(Integer.toString(outputQ.size())) + .append(" upstreamCompleted: ").append(upstreamCompleted) + .append(" upstreamWindow: ").append(upstreamWindow) + .append(" downstreamCompleted: ").append(downstreamCompleted) + .append(" completionAcknowledged: ").append(completionAcknowledged) + .append(" outputQ size: ").append(outputQ.size()) //.append(" outputQ: ").append(outputQ.toString()) - .append(" cf: ").append(cf.toString()) + .append(" cf: ").append(cf) .append(" downstreamSubscription: ").append(downstreamSubscription) .append(" downstreamSubscriber: ").append(downstreamSubscriber); diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java b/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java index 7597647684fb150cb1434620eb44a252ab61631f..c22c36a1eb3bcc07346e36eebfadf206ff4bb613 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/common/Utils.java @@ -391,7 +391,6 @@ public final class Utils { return new URLPermission(urlString, actionStringBuilder.toString()); } - // ABNF primitives defined in RFC 7230 private static final boolean[] tchar = new boolean[256]; private static final boolean[] fieldvchar = new boolean[256]; @@ -411,7 +410,7 @@ public final class Utils { } /* - * Validates a RFC 7230 field-name. + * Validates an RFC 7230 field-name. */ public static boolean isValidName(String token) { for (int i = 0; i < token.length(); i++) { @@ -472,7 +471,7 @@ public final class Utils { } /* - * Validates a RFC 7230 field-value. + * Validates an RFC 7230 field-value. * * "Obsolete line folding" rule * @@ -495,7 +494,6 @@ public final class Utils { return true; } - @SuppressWarnings("removal") public static int getIntegerNetProperty(String name, int defaultValue) { return AccessController.doPrivileged((PrivilegedAction) () -> @@ -873,7 +871,7 @@ public final class Utils { if (defaultPort) { return host; } else { - return host + ":" + Integer.toString(port); + return host + ":" + port; } } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/frame/ErrorFrame.java b/src/java.net.http/share/classes/jdk/internal/net/http/frame/ErrorFrame.java index 2d25193c11814b413228364911847ded6062bec1..bf281368a98690eab0b8a7d3ebeec1f8044f8d46 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/frame/ErrorFrame.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/frame/ErrorFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,7 +67,7 @@ public abstract class ErrorFrame extends Http2Frame { } if (code > LAST_ERROR) { - return "Error: " + Integer.toString(code); + return "Error: " + code; } else { return errorStrings[code]; } diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/frame/Http2Frame.java b/src/java.net.http/share/classes/jdk/internal/net/http/frame/Http2Frame.java index 36fc0c8dffddab73777de272f622dc753a133b8b..f837645696fccc0a2590c3304ff3f460c69e1c2e 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/frame/Http2Frame.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/frame/Http2Frame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,7 @@ public abstract class Http2Frame { StringBuilder sb = new StringBuilder(); sb.append(typeAsString()) .append(": length=") - .append(Integer.toString(length())) + .append(length()) .append(", streamid=") .append(streamid) .append(", flags="); diff --git a/src/java.net.http/share/classes/jdk/internal/net/http/frame/SettingsFrame.java b/src/java.net.http/share/classes/jdk/internal/net/http/frame/SettingsFrame.java index ca68eae8cf6845ac77cd11b791159e5e9be14991..8a0119594176a18695cf6dd1e1853c992fb9b530 100644 --- a/src/java.net.http/share/classes/jdk/internal/net/http/frame/SettingsFrame.java +++ b/src/java.net.http/share/classes/jdk/internal/net/http/frame/SettingsFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ public class SettingsFrame extends Http2Frame { if (parameters[i] != -1) { sb.append(name(i)) .append("=") - .append(Integer.toString(parameters[i])) + .append(parameters[i]) .append(' '); } } diff --git a/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java b/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java index ab954513b81a0a19c1a2b3b603eb283f611f1eb9..61ee92cf6013a8af12ae88209bd38743d1d4c562 100644 --- a/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java +++ b/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java @@ -93,18 +93,12 @@ class MacOSXPreferencesFile { }); } - private class FlushTask extends TimerTask { + private static class FlushTask extends TimerTask { public void run() { MacOSXPreferencesFile.flushWorld(); } } - private class SyncTask extends TimerTask { - public void run() { - MacOSXPreferencesFile.syncWorld(); - } - } - // Maps string -> weak reference to MacOSXPreferencesFile private static HashMap> cachedFiles; diff --git a/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java b/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java index e0e2551bb690bb8217c2cc769dccb6d428cf95d7..b0844b2e7ca1eeab278b56fc61f0f0ee993f661e 100644 --- a/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java +++ b/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java @@ -29,11 +29,6 @@ import java.util.*; import java.io.*; import java.security.AccessController; import java.security.PrivilegedAction; -// These imports needed only as a workaround for a JavaDoc bug -import java.lang.Integer; -import java.lang.Long; -import java.lang.Float; -import java.lang.Double; /** * This class provides a skeletal implementation of the {@link Preferences} @@ -1498,13 +1493,13 @@ public abstract class AbstractPreferences extends Preferences { * eventQueue so the event dispatch thread knows whether to call * childAdded or childRemoved. */ - private class NodeAddedEvent extends NodeChangeEvent { + private static class NodeAddedEvent extends NodeChangeEvent { private static final long serialVersionUID = -6743557530157328528L; NodeAddedEvent(Preferences parent, Preferences child) { super(parent, child); } } - private class NodeRemovedEvent extends NodeChangeEvent { + private static class NodeRemovedEvent extends NodeChangeEvent { private static final long serialVersionUID = 8735497392918824837L; NodeRemovedEvent(Preferences parent, Preferences child) { super(parent, child); diff --git a/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java b/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java index 5aafccbc487464a750a6d1c3126db90a8081a033..2a8947146666c8515a5b029df61cb30541b6ad82 100644 --- a/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java +++ b/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java @@ -24,6 +24,7 @@ */ package java.util.prefs; + import java.util.*; import java.io.*; import java.security.AccessController; @@ -298,8 +299,8 @@ class FileSystemPreferences extends AbstractPreferences { * A temporary file used for saving changes to preferences. As part of * the sync operation, changes are first saved into this file, and then * atomically renamed to prefsFile. This results in an atomic state - * change from one valid set of preferences to another. The - * the file-lock is held for the duration of this transformation. + * change from one valid set of preferences to another. + * The file-lock is held for the duration of this transformation. */ private final File tmpFile; @@ -385,12 +386,12 @@ class FileSystemPreferences extends AbstractPreferences { /** * Represents a change to a preference. */ - private abstract class Change { + private abstract static class Change { /** * Reapplies the change to prefsCache. */ abstract void replay(); - }; + } /** * Represents a preference put. @@ -426,7 +427,7 @@ class FileSystemPreferences extends AbstractPreferences { /** * Represents the creation of this node. */ - private class NodeCreate extends Change { + private static class NodeCreate extends Change { /** * Performs no action, but the presence of this object in changeLog * will force the node and its ancestors to be made permanent at the diff --git a/src/java.rmi/share/classes/java/rmi/server/LoaderHandler.java b/src/java.rmi/share/classes/java/rmi/server/LoaderHandler.java index 1955583741b3f1b9997992fa229098d75350c6b4..5ff1e38f831533fc05f3326e0b83a49653be2ba2 100644 --- a/src/java.rmi/share/classes/java/rmi/server/LoaderHandler.java +++ b/src/java.rmi/share/classes/java/rmi/server/LoaderHandler.java @@ -42,7 +42,7 @@ import java.net.URL; public interface LoaderHandler { /** package of system LoaderHandler implementation. */ - final static String packagePrefix = "sun.rmi.server"; + static final String packagePrefix = "sun.rmi.server"; /** * Loads a class from the location specified by the diff --git a/src/java.rmi/share/classes/java/rmi/server/ObjID.java b/src/java.rmi/share/classes/java/rmi/server/ObjID.java index 335123b8e95df257609db8c07268b3188ba34bb4..ae3a61277ec39e54ff043f741c6c62168b97b84c 100644 --- a/src/java.rmi/share/classes/java/rmi/server/ObjID.java +++ b/src/java.rmi/share/classes/java/rmi/server/ObjID.java @@ -201,7 +201,7 @@ public final class ObjID implements Serializable { */ @Override public int hashCode() { - return Long.hashCode(objNum); + return (int) objNum; } /** diff --git a/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java b/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java index fb17f04ef4e1e7e66857ce794e288fd900052b0f..7ee253e5dc88930070cef75b878d742b8635df2f 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java +++ b/src/java.rmi/share/classes/java/rmi/server/RMIClassLoader.java @@ -694,10 +694,8 @@ public class RMIClassLoader { } catch (InstantiationException e) { throw new InstantiationError(e.getMessage()); } catch (ClassCastException e) { - Error error = new LinkageError( - "provider class not assignable to RMIClassLoaderSpi"); - error.initCause(e); - throw error; + throw new LinkageError( + "provider class not assignable to RMIClassLoaderSpi", e); } } @@ -711,10 +709,8 @@ public class RMIClassLoader { try { return iter.next(); } catch (ClassCastException e) { - Error error = new LinkageError( - "provider class not assignable to RMIClassLoaderSpi"); - error.initCause(e); - throw error; + throw new LinkageError( + "provider class not assignable to RMIClassLoaderSpi", e); } } diff --git a/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java b/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java index 70f2191b4b9905980fe8bacc695aaa2197f34e35..0693992e95889b0942c7117318ae50c1e96a2319 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java +++ b/src/java.rmi/share/classes/java/rmi/server/RMISocketFactory.java @@ -131,7 +131,7 @@ public abstract class RMISocketFactory * @see java.lang.SecurityManager#checkSetFactory() * @since 1.1 */ - public synchronized static void setSocketFactory(RMISocketFactory fac) + public static synchronized void setSocketFactory(RMISocketFactory fac) throws IOException { if (factory != null) { @@ -153,7 +153,7 @@ public abstract class RMISocketFactory * @see #setSocketFactory(RMISocketFactory) * @since 1.1 */ - public synchronized static RMISocketFactory getSocketFactory() + public static synchronized RMISocketFactory getSocketFactory() { return factory; } @@ -166,7 +166,7 @@ public abstract class RMISocketFactory * @return the default RMI socket factory * @since 1.1 */ - public synchronized static RMISocketFactory getDefaultSocketFactory() { + public static synchronized RMISocketFactory getDefaultSocketFactory() { if (defaultSocketFactory == null) { defaultSocketFactory = new sun.rmi.transport.tcp.TCPDirectSocketFactory(); @@ -193,7 +193,7 @@ public abstract class RMISocketFactory * @see java.rmi.server.RMIFailureHandler#failure(Exception) * @since 1.1 */ - public synchronized static void setFailureHandler(RMIFailureHandler fh) + public static synchronized void setFailureHandler(RMIFailureHandler fh) { @SuppressWarnings("removal") SecurityManager security = System.getSecurityManager(); @@ -210,7 +210,7 @@ public abstract class RMISocketFactory * @see #setFailureHandler(RMIFailureHandler) * @since 1.1 */ - public synchronized static RMIFailureHandler getFailureHandler() + public static synchronized RMIFailureHandler getFailureHandler() { return handler; } diff --git a/src/java.rmi/share/classes/java/rmi/server/RemoteObject.java b/src/java.rmi/share/classes/java/rmi/server/RemoteObject.java index 4bf8367865ea021c78226534c623634d277739e7..4245d362a2425b1943539fdb9d2811f060658758 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RemoteObject.java +++ b/src/java.rmi/share/classes/java/rmi/server/RemoteObject.java @@ -45,7 +45,7 @@ import sun.rmi.server.Util; public abstract class RemoteObject implements Remote, java.io.Serializable { /** The object's remote reference. */ - transient protected RemoteRef ref; + protected transient RemoteRef ref; /** indicate compatibility with JDK 1.1.x version of class */ @java.io.Serial @@ -251,7 +251,7 @@ public abstract class RemoteObject implements Remote, java.io.Serializable { * written by {@link java.io.ObjectOutput#writeInt(int)} * *

    • the data written as a result of calling - * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} + * {@link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the ObjID instance contained in the reference * *
    • the boolean value false, @@ -275,7 +275,7 @@ public abstract class RemoteObject implements Remote, java.io.Serializable { * written by {@link java.io.ObjectOutput#writeInt(int)} * *
    • the data written as a result of calling - * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} + * {@link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the ObjID instance contained in the reference * *
    • the boolean value false, @@ -304,7 +304,7 @@ public abstract class RemoteObject implements Remote, java.io.Serializable { * writeObject on the stream instance * *
    • the data written as a result of calling - * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} + * {@link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the ObjID instance contained in the reference * *
    • the boolean value false, diff --git a/src/java.rmi/share/classes/java/rmi/server/RemoteObjectInvocationHandler.java b/src/java.rmi/share/classes/java/rmi/server/RemoteObjectInvocationHandler.java index 68d04f10e40a56c26c70e67c50ae03d9f425d619..e619515818ca6129c87995b7eb4cb3291bd7e761 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RemoteObjectInvocationHandler.java +++ b/src/java.rmi/share/classes/java/rmi/server/RemoteObjectInvocationHandler.java @@ -221,8 +221,7 @@ public class RemoteObjectInvocationHandler method = cl.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException nsme) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(nsme); + throw new IllegalArgumentException(nsme); } Class thrownType = e.getClass(); for (Class declaredType : method.getExceptionTypes()) { diff --git a/src/java.rmi/share/classes/java/rmi/server/RemoteRef.java b/src/java.rmi/share/classes/java/rmi/server/RemoteRef.java index 6a059cb6e3d565f285da3ffe7d1229bf4001915e..57201cd8dc3c55c00073dfb82bc2fc316061dbe8 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RemoteRef.java +++ b/src/java.rmi/share/classes/java/rmi/server/RemoteRef.java @@ -53,7 +53,7 @@ public interface RemoteRef extends java.io.Externalizable { * UnicastServerRef) are located in the package defined by the * prefix. */ - final static String packagePrefix = "sun.rmi.server"; + static final String packagePrefix = "sun.rmi.server"; /** * Invoke a method. This form of delegating method invocation diff --git a/src/java.rmi/share/classes/java/rmi/server/RemoteStub.java b/src/java.rmi/share/classes/java/rmi/server/RemoteStub.java index 536a29c4e56287b0e7b1767d46e94409a0ceb60f..4a64e8ebe9253bf47504fcbc50b2911947725f7c 100644 --- a/src/java.rmi/share/classes/java/rmi/server/RemoteStub.java +++ b/src/java.rmi/share/classes/java/rmi/server/RemoteStub.java @@ -40,7 +40,7 @@ package java.rmi.server; * for information about dynamic stub generation. */ @Deprecated -abstract public class RemoteStub extends RemoteObject { +public abstract class RemoteStub extends RemoteObject { /** indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -1585587260594494182L; diff --git a/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIClientSocketFactory.java b/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIClientSocketFactory.java index f0faba4345a39afedd80086cf972e2493d7721c6..ab6664b9d8fdfe8fd6c716c2618db0d24c34816c 100644 --- a/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIClientSocketFactory.java +++ b/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIClientSocketFactory.java @@ -133,8 +133,7 @@ public class SslRMIClientSocketFactory try { sslSocket.setEnabledCipherSuites(enabledCipherSuitesList); } catch (IllegalArgumentException e) { - throw (IOException) - new IOException(e.getMessage()).initCause(e); + throw new IOException(e.getMessage(), e); } } // Set the SSLSocket Enabled Protocols @@ -151,8 +150,7 @@ public class SslRMIClientSocketFactory try { sslSocket.setEnabledProtocols(enabledProtocolsList); } catch (IllegalArgumentException e) { - throw (IOException) - new IOException(e.getMessage()).initCause(e); + throw new IOException(e.getMessage(), e); } } // Return the preconfigured SSLSocket diff --git a/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIServerSocketFactory.java b/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIServerSocketFactory.java index af0055dac0a1ff435b1dbed8383e61d1f3c5935d..3424bf77812718bad07431ed1cedc9a8f872b998 100644 --- a/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIServerSocketFactory.java +++ b/src/java.rmi/share/classes/javax/rmi/ssl/SslRMIServerSocketFactory.java @@ -185,8 +185,7 @@ public class SslRMIServerSocketFactory implements RMIServerSocketFactory { } catch (Exception e) { final String msg = "Unable to check if the cipher suites " + "and protocols to enable are supported"; - throw (IllegalArgumentException) - new IllegalArgumentException(msg).initCause(e); + throw new IllegalArgumentException(msg, e); } } diff --git a/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java b/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java index 649fa22516d43c991c3ae459c11937d2243d9f07..1dbdd3064bcf4ae06a911bc4ad8a8b8da0c72f58 100644 --- a/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java +++ b/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java @@ -128,7 +128,7 @@ class LogInputStream extends InputStream { /** * Closes the stream when garbage is collected. */ - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws IOException { close(); } diff --git a/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java b/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java index 91144b1c94f12ff7790cbba35cff68e1017a8462..293e2ccdec3c758fc4dd9d7a065daf892f33b9d1 100644 --- a/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java +++ b/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java @@ -78,8 +78,8 @@ import java.security.PrivilegedAction; */ public class ReliableLog { - public final static int PreferredMajorVersion = 0; - public final static int PreferredMinorVersion = 2; + public static final int PreferredMajorVersion = 0; + public static final int PreferredMinorVersion = 2; // sun.rmi.log.debug=false private boolean Debug = false; @@ -285,8 +285,7 @@ public class ReliableLog { } catch (IOException e) { throw e; } catch (Exception e) { - throw (IOException) - new IOException("write update failed").initCause(e); + throw new IOException("write update failed", e); } log.sync(); @@ -547,8 +546,7 @@ public class ReliableLog { new LogFile(logName, "rw") : logClassConstructor.newInstance(logName, "rw")); } catch (Exception e) { - throw (IOException) new IOException( - "unable to construct LogFile instance").initCause(e); + throw new IOException("unable to construct LogFile instance", e); } if (truncate) { diff --git a/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java b/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java index caa727e9db1a7128522c81973608beddca65436f..326edf2590c29f5125c1573cd72d0bb7e95738a9 100644 --- a/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java +++ b/src/java.rmi/share/classes/sun/rmi/server/UnicastRef.java @@ -71,6 +71,7 @@ public class UnicastRef implements RemoteRef { Boolean.getBoolean("sun.rmi.client.logCalls"))); private static final long serialVersionUID = 8258372400816541186L; + @SuppressWarnings("serial") // Type of field is not Serializable protected LiveRef ref; /** diff --git a/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java b/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java index 61d2668f45d393969992b9e0e7edd2ea4529eed1..d01256f5533e4ee13a1504e36cd2ad78339c4b7e 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/ObjectTable.java @@ -49,7 +49,7 @@ public final class ObjectTable { /** maximum interval between complete garbage collections of local heap */ @SuppressWarnings("removal") - private final static long gcInterval = // default 1 hour + private static final long gcInterval = // default 1 hour AccessController.doPrivileged((PrivilegedAction) () -> Long.getLong("sun.rmi.dgc.server.gcInterval", 3600000)); diff --git a/src/java.rmi/share/classes/sun/rmi/transport/Target.java b/src/java.rmi/share/classes/sun/rmi/transport/Target.java index 1a2c10db4b66f9abbe2469e1665430c0819c2740..c0d79bb38e2d22d3249044f146ab9de08ea83c01 100644 --- a/src/java.rmi/share/classes/sun/rmi/transport/Target.java +++ b/src/java.rmi/share/classes/sun/rmi/transport/Target.java @@ -308,7 +308,7 @@ public final class Target { * Remove endpoint from the reference set. */ @SuppressWarnings("removal") - synchronized private void refSetRemove(VMID vmid) { + private synchronized void refSetRemove(VMID vmid) { // remove notification request DGCImpl.getDGCImpl().unregisterTarget(vmid, this); @@ -434,7 +434,7 @@ public final class Target { * vmid dies. In that case, the vmid should be removed * from the reference set. */ - synchronized public void vmidDead(VMID vmid) { + public synchronized void vmidDead(VMID vmid) { if (DGCImpl.dgcLog.isLoggable(Log.BRIEF)) { DGCImpl.dgcLog.log(Log.BRIEF, "removing endpoint " + vmid + " from reference set"); diff --git a/src/java.rmi/share/man/rmiregistry.1 b/src/java.rmi/share/man/rmiregistry.1 index d4c84ea58c2e10e29887d482b18a07253dd11da2..d6e27ceec1ca1bfda4031284e2ed76f9cfca7b0d 100644 --- a/src/java.rmi/share/man/rmiregistry.1 +++ b/src/java.rmi/share/man/rmiregistry.1 @@ -21,7 +21,7 @@ .\" .\" Automatically generated by Pandoc 2.3.1 .\" -.TH "RMIREGISTRY" "1" "2021" "JDK 18\-ea" "JDK Commands" +.TH "RMIREGISTRY" "1" "2022" "JDK 19\-ea" "JDK Commands" .hy .SH NAME .PP diff --git a/src/java.scripting/share/man/jrunscript.1 b/src/java.scripting/share/man/jrunscript.1 index 2c7ac2d40bc8ac73e0a1043d71df7c36a0336d05..727f6d2cece36df01cf8c91d23b481ec9c110ac0 100644 --- a/src/java.scripting/share/man/jrunscript.1 +++ b/src/java.scripting/share/man/jrunscript.1 @@ -21,7 +21,7 @@ .\" .\" Automatically generated by Pandoc 2.3.1 .\" -.TH "JRUNSCRIPT" "1" "2021" "JDK 18\-ea" "JDK Commands" +.TH "JRUNSCRIPT" "1" "2022" "JDK 19\-ea" "JDK Commands" .hy .SH NAME .PP diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java b/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java index 6d0d711325ea173cd1350a8d0c6603f22eff2a49..18c2604c9c798691c9b4b9cd163c4ead20c9897f 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -405,12 +405,12 @@ public class GSSCredentialImpl implements GSSCredential { throw new IllegalStateException("This credential is " + "no longer valid"); } - Vector result = new Vector(hashtable.size()); + ArrayList result = new ArrayList(hashtable.size()); for (Enumeration e = hashtable.keys(); e.hasMoreElements(); ) { SearchKey tempKey = e.nextElement(); - result.addElement(tempKey.getMech()); + result.add(tempKey.getMech()); } return result.toArray(new Oid[0]); } diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java b/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java index 9f21ac5e84d31b750dc455e166d89d43ff9e5c21..482bb8533e8e7fa03958dfb0e99b1d312aa78e2d 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java @@ -40,7 +40,6 @@ import java.util.HashSet; import java.util.Vector; import java.util.Iterator; import java.security.AccessController; -import java.security.AccessControlContext; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import javax.security.auth.callback.CallbackHandler; @@ -313,20 +312,18 @@ public class GSSUtil { (initiate? " INIT" : " ACCEPT") + " cred (" + (name == null? "<>" : name.toString()) + ", " + credCls.getName() + ")"); - @SuppressWarnings("removal") - final AccessControlContext acc = AccessController.getContext(); try { @SuppressWarnings("removal") Vector creds = - AccessController.doPrivileged + AccessController.doPrivilegedWithCombiner (new PrivilegedExceptionAction>() { public Vector run() throws Exception { - Subject accSubj = Subject.getSubject(acc); + Subject currSubj = Subject.current(); Vector result = null; - if (accSubj != null) { + if (currSubj != null) { result = new Vector(); Iterator iterator = - accSubj.getPrivateCredentials + currSubj.getPrivateCredentials (GSSCredentialImpl.class).iterator(); while (iterator.hasNext()) { GSSCredentialImpl cred = iterator.next(); diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/ProviderList.java b/src/java.security.jgss/share/classes/sun/security/jgss/ProviderList.java index e74afff99d3efa27e1ea22051c12a0f0476533cc..8ccd2b6da4911457bb58bc988ab9f80ee4868356 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/ProviderList.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/ProviderList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -160,7 +160,7 @@ public final class ProviderList { } // So the existing code do not have to be changed - synchronized public MechanismFactory getMechFactory(Oid mechOid) + public synchronized MechanismFactory getMechFactory(Oid mechOid) throws GSSException { if (mechOid == null) mechOid = ProviderList.DEFAULT_MECH_OID; return getMechFactory(mechOid, null); @@ -177,7 +177,7 @@ public final class ProviderList { * support the desired mechanism, or when no provider supports * the desired mechanism. */ - synchronized public MechanismFactory getMechFactory(Oid mechOid, + public synchronized MechanismFactory getMechFactory(Oid mechOid, Provider p) throws GSSException { @@ -335,7 +335,7 @@ public final class ProviderList { return mechs.toArray(new Oid[] {}); } - synchronized public void addProviderAtFront(Provider p, Oid mechOid) + public synchronized void addProviderAtFront(Provider p, Oid mechOid) throws GSSException { PreferencesEntry newEntry = new PreferencesEntry(p, mechOid); @@ -367,7 +367,7 @@ public final class ProviderList { } } - synchronized public void addProviderAtEnd(Provider p, Oid mechOid) + public synchronized void addProviderAtEnd(Provider p, Oid mechOid) throws GSSException { PreferencesEntry newEntry = new PreferencesEntry(p, mechOid); diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/TokenTracker.java b/src/java.security.jgss/share/classes/sun/security/jgss/TokenTracker.java index 5ce25f8711a8ab0e071a4f381ac4e9fa9a66fd56..a010023c721754fe9a9bb77f2f3aeba3f9ddb31e 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/TokenTracker.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/TokenTracker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -147,7 +147,7 @@ public class TokenTracker { * (This analysis leaves out the possibility that expectedNumber passes * initNumber after wrapping around. That may be added later.) */ - synchronized public final void getProps(int number, MessageProp prop) { + public final synchronized void getProps(int number, MessageProp prop) { boolean gap = false; boolean old = false; diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java index 10bb08c37adeb0d3c4aeb8aa513bf18ec3cdee66..272a079401408754ef52dd3df8f3e2edf1121384 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java @@ -25,7 +25,6 @@ package sun.security.jgss.krb5; -import java.io.IOException; import org.ietf.jgss.*; import sun.security.jgss.GSSCaller; import sun.security.jgss.spi.*; @@ -33,7 +32,6 @@ import sun.security.krb5.*; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.AccessController; -import java.security.AccessControlContext; import javax.security.auth.DestroyFailedException; /** @@ -65,16 +63,15 @@ public class Krb5AcceptCredential final String serverPrinc = (name == null? null: name.getKrb5PrincipalName().getName()); - final AccessControlContext acc = AccessController.getContext(); ServiceCreds creds = null; try { - creds = AccessController.doPrivileged( + creds = AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction() { public ServiceCreds run() throws Exception { return Krb5Util.getServiceCreds( caller == GSSCaller.CALLER_UNKNOWN ? GSSCaller.CALLER_ACCEPT: caller, - serverPrinc, acc); + serverPrinc); }}); } catch (PrivilegedActionException e) { GSSException ge = diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java index 3cb0bf46cb8c22edefc93223aef6786c809f2d1d..6e0286c5d5bd32553042ea5f10092ae17964c2bf 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java @@ -37,7 +37,6 @@ import java.io.OutputStream; import java.io.IOException; import java.security.Provider; import java.security.AccessController; -import java.security.AccessControlContext; import java.security.Key; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -46,7 +45,6 @@ import javax.security.auth.kerberos.ServicePermission; import javax.security.auth.kerberos.KerberosCredMessage; import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.kerberos.KerberosTicket; -import sun.security.krb5.internal.Ticket; import sun.security.krb5.internal.AuthorizationData; /** @@ -121,9 +119,12 @@ class Krb5Context implements GSSContextSpi { // XXX See if the required info from these can be extracted and // stored elsewhere private Credentials tgt; + + // On the Initiator side, contains the final TGS to a service on both + // delegation and no-delegation scenarios. + // On the Acceptor side, contains a user TGS usable for delegation. private Credentials serviceCreds; private KrbApReq apReq; - Ticket serviceTicket; private final GSSCaller caller; private static final boolean DEBUG = Krb5Util.DEBUG; @@ -549,7 +550,7 @@ class Krb5Context implements GSSContextSpi { delegatedCred = new Krb5ProxyCredential( Krb5InitCredential.getInstance( GSSCaller.CALLER_ACCEPT, myName, lifetime), - peerName, serviceTicket); + peerName, serviceCreds); } catch (GSSException gsse) { // OK, delegatedCred is null then } @@ -624,13 +625,13 @@ class Krb5Context implements GSSContextSpi { "No TGT available"); } myName = (Krb5NameElement) myCred.getName(); - final Krb5ProxyCredential second; + final Krb5ProxyCredential proxyCreds; if (myCred instanceof Krb5InitCredential) { - second = null; + proxyCreds = null; tgt = ((Krb5InitCredential) myCred).getKrb5Credentials(); } else { - second = (Krb5ProxyCredential) myCred; - tgt = second.self.getKrb5Credentials(); + proxyCreds = (Krb5ProxyCredential) myCred; + tgt = proxyCreds.self.getKrb5Credentials(); } checkPermission(peerName.getKrb5PrincipalName().getName(), @@ -641,16 +642,12 @@ class Krb5Context implements GSSContextSpi { * for this service in the Subject and reuse it */ - @SuppressWarnings("removal") - final AccessControlContext acc = - AccessController.getContext(); - if (GSSUtil.useSubjectCredsOnly(caller)) { KerberosTicket kerbTicket = null; try { // get service ticket from caller's subject @SuppressWarnings("removal") - var tmp = AccessController.doPrivileged( + var tmp = AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction() { public KerberosTicket run() throws Exception { // XXX to be cleaned @@ -662,11 +659,10 @@ class Krb5Context implements GSSContextSpi { GSSCaller.CALLER_UNKNOWN, // since it's useSubjectCredsOnly here, // don't worry about the null - second == null ? + proxyCreds == null ? myName.getKrb5PrincipalName().getName(): - second.getName().getKrb5PrincipalName().getName(), - peerName.getKrb5PrincipalName().getName(), - acc); + proxyCreds.getName().getKrb5PrincipalName().getName(), + peerName.getKrb5PrincipalName().getName()); }}); kerbTicket = tmp; } catch (PrivilegedActionException e) { @@ -696,24 +692,24 @@ class Krb5Context implements GSSContextSpi { "the subject"); } // Get Service ticket using the Kerberos protocols - if (second == null) { + if (proxyCreds == null) { serviceCreds = Credentials.acquireServiceCreds( peerName.getKrb5PrincipalName().getName(), tgt); } else { serviceCreds = Credentials.acquireS4U2proxyCreds( peerName.getKrb5PrincipalName().getName(), - second.tkt, - second.getName().getKrb5PrincipalName(), + proxyCreds.userCreds, + proxyCreds.getName().getKrb5PrincipalName(), tgt); } if (GSSUtil.useSubjectCredsOnly(caller)) { @SuppressWarnings("removal") final Subject subject = - AccessController.doPrivileged( + AccessController.doPrivilegedWithCombiner( new java.security.PrivilegedAction() { public Subject run() { - return (Subject.getSubject(acc)); + return (Subject.current()); } }); if (subject != null && @@ -850,7 +846,7 @@ class Krb5Context implements GSSContextSpi { retVal = new AcceptSecContextToken(this, token.getKrbApReq()).encode(); } - serviceTicket = token.getKrbApReq().getCreds().getTicket(); + serviceCreds = token.getKrbApReq().getCreds(); myCred = null; state = STATE_DONE; } else { diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java index 3e168cd718ea46f8318bb6ca45ed7a669ce5f2ed..5ec6c30a676f12e4bdca03403b70b6e0969f9f9b 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java @@ -35,7 +35,6 @@ import java.net.InetAddress; import java.io.IOException; import java.util.Date; import java.security.AccessController; -import java.security.AccessControlContext; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; @@ -365,20 +364,17 @@ public class Krb5InitCredential clientPrincipal = null; } - final AccessControlContext acc = AccessController.getContext(); - try { final GSSCaller realCaller = (caller == GSSCaller.CALLER_UNKNOWN) ? GSSCaller.CALLER_INITIATE : caller; - return AccessController.doPrivileged( + return AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction() { public KerberosTicket run() throws Exception { // It's OK to use null as serverPrincipal. TGT is almost // the first ticket for a principal and we use list. return Krb5Util.getInitialTicket( - realCaller, - clientPrincipal, acc); + realCaller, clientPrincipal); }}); } catch (PrivilegedActionException e) { GSSException ge = @@ -396,7 +392,7 @@ public class Krb5InitCredential Krb5NameElement kname = (Krb5NameElement)name; Credentials newCred = Credentials.acquireS4U2selfCreds( kname.getKrb5PrincipalName(), krb5Credentials); - return new Krb5ProxyCredential(this, kname, newCred.getTicket()); + return new Krb5ProxyCredential(this, kname, newCred); } catch (IOException | KrbException ke) { GSSException ge = new GSSException(GSSException.FAILURE, -1, diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java index f698d3b0e27da43eab550bbf638efb33e4b022fd..21b48d58fc226816f5d0e8dd8d200acda5a7ee16 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java @@ -154,7 +154,7 @@ public final class Krb5MechFactory implements MechanismFactory { sm.checkPermission(perm); } catch (SecurityException e) { if (DEBUG) { - System.out.println("Permission to initiate" + + System.out.println("Permission to initiate " + "kerberos init credential" + e.getMessage()); } throw e; diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5ProxyCredential.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5ProxyCredential.java index 8fbe93a57685dcd1b6aec5500b10e3e8fd920606..8859c759f13e37508968f848de29522d28c368cd 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5ProxyCredential.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5ProxyCredential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,6 @@ import java.io.IOException; import sun.security.krb5.Credentials; import sun.security.krb5.KrbException; -import sun.security.krb5.internal.Ticket; import javax.security.auth.kerberos.KerberosTicket; @@ -50,23 +49,23 @@ public class Krb5ProxyCredential implements Krb5CredElement { public final Krb5InitCredential self; // the middle server - private final Krb5NameElement client; // the client + private final Krb5NameElement user; // the user - // The ticket with cname=client and sname=self. This can be a normal - // service ticket or an S4U2self ticket. - public final Ticket tkt; + // The creds with cname=user and sname=self. The ticket inside can + // be either a normal service ticket or an S4U2self ticket. + public final Credentials userCreds; - Krb5ProxyCredential(Krb5InitCredential self, Krb5NameElement client, - Ticket tkt) { + Krb5ProxyCredential(Krb5InitCredential self, Krb5NameElement user, + Credentials userCreds) { this.self = self; - this.tkt = tkt; - this.client = client; + this.userCreds = userCreds; + this.user = user; } - // The client name behind the proxy + // The user name behind the proxy @Override public final Krb5NameElement getName() throws GSSException { - return client; + return user; } @Override @@ -130,7 +129,7 @@ public class Krb5ProxyCredential Credentials proxyCreds = Krb5Util.ticketToCreds(proxy); return new Krb5ProxyCredential(initiator, Krb5NameElement.getInstance(proxyCreds.getClient()), - proxyCreds.getTicket()); + proxyCreds); } else { return initiator; } diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Util.java b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Util.java index 24353cceeca9b662e653768c10f6246a4d4c80a9..bf2bc82ffaf1d4eeb98f1728b099f0b12b113aba 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Util.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Util.java @@ -30,7 +30,6 @@ import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.kerberos.KeyTab; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; -import java.security.AccessControlContext; import sun.security.action.GetBooleanAction; import sun.security.jgss.GSSUtil; @@ -62,14 +61,12 @@ public class Krb5Util { * pair from the Subject in the specified AccessControlContext. */ static KerberosTicket getServiceTicket(GSSCaller caller, - String clientPrincipal, String serverPrincipal, - @SuppressWarnings("removal") AccessControlContext acc) throws LoginException { - - // Try to get ticket from acc's Subject + String clientPrincipal, String serverPrincipal) { + // Try to get ticket from current Subject @SuppressWarnings("removal") - Subject accSubj = Subject.getSubject(acc); + Subject currSubj = Subject.current(); KerberosTicket ticket = - SubjectComber.find(accSubj, serverPrincipal, clientPrincipal, + SubjectComber.find(currSubj, serverPrincipal, clientPrincipal, KerberosTicket.class); return ticket; @@ -83,14 +80,11 @@ public class Krb5Util { * a LoginContext. */ static KerberosTicket getInitialTicket(GSSCaller caller, - String clientPrincipal, - @SuppressWarnings("removal") AccessControlContext acc) throws LoginException { + String clientPrincipal) throws LoginException { - // Try to get ticket from acc's Subject - @SuppressWarnings("removal") - Subject accSubj = Subject.getSubject(acc); + Subject currSubj = Subject.current(); KerberosTicket ticket = - SubjectComber.find(accSubj, null, clientPrincipal, + SubjectComber.find(currSubj, null, clientPrincipal, KerberosTicket.class); // Try to get ticket from Subject obtained from GSSUtil @@ -106,18 +100,14 @@ public class Krb5Util { * Retrieves the ServiceCreds for the specified server principal from * the Subject in the specified AccessControlContext. If not found, and if * useSubjectCredsOnly is false, then obtain from a LoginContext. - * - * NOTE: This method is also used by JSSE Kerberos Cipher Suites */ public static ServiceCreds getServiceCreds(GSSCaller caller, - String serverPrincipal, @SuppressWarnings("removal") AccessControlContext acc) - throws LoginException { + String serverPrincipal) throws LoginException { - @SuppressWarnings("removal") - Subject accSubj = Subject.getSubject(acc); + Subject currSubj = Subject.current(); ServiceCreds sc = null; - if (accSubj != null) { - sc = ServiceCreds.getInstance(accSubj, serverPrincipal); + if (currSubj != null) { + sc = ServiceCreds.getInstance(currSubj, serverPrincipal); } if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) { Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID); diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSCredElement.java b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSCredElement.java index bfe1807935a9ac556d5500b297d43f8fedf4c1df..447b6c947e9c73b4b0ae317e93e676c7d138502c 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSCredElement.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSCredElement.java @@ -132,7 +132,7 @@ public class GSSCredElement implements GSSCredentialSpi { return "N/A"; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { dispose(); } diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSNameElement.java b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSNameElement.java index 54641f2f6e6a7ac00066f40cfa30796d80fa1f9e..b449169c441600952c5cd2b105b91a8bae3093b6 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSNameElement.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/GSSNameElement.java @@ -290,7 +290,7 @@ public class GSSNameElement implements GSSNameSpi { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { dispose(); } diff --git a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java index e89b109250e5ea9878d690c8d0d63a848a799fa3..61640be3507d91ccaa05d672e64457dd20a7610a 100644 --- a/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java +++ b/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java @@ -639,7 +639,7 @@ class NativeGSSContext implements GSSContextSpi { return isInitiator; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { dispose(); } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/Credentials.java b/src/java.security.jgss/share/classes/sun/security/krb5/Credentials.java index d84ccd2b631fead521b3731b5a8b3470e6583602..b4efc5f4db73f20bbd4e2dd0fb333f0d83d80a23 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/Credentials.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/Credentials.java @@ -35,6 +35,8 @@ import sun.security.action.GetPropertyAction; import sun.security.krb5.internal.*; import sun.security.krb5.internal.ccache.CredentialsCache; import sun.security.krb5.internal.crypto.EType; +import sun.security.util.SecurityProperties; + import java.io.IOException; import java.util.Date; import java.util.Locale; @@ -64,6 +66,10 @@ public class Credentials { static boolean alreadyLoaded = false; private static boolean alreadyTried = false; + public static final boolean S4U2PROXY_ACCEPT_NON_FORWARDABLE + = "true".equalsIgnoreCase(SecurityProperties.privilegedGetOverridable( + "jdk.security.krb5.s4u2proxy.acceptNonForwardableServiceTicket")); + private Credentials proxy = null; public Credentials getProxy() { @@ -97,7 +103,7 @@ public class Credentials { this.authzData = authzData; } - // Warning: called by NativeCreds.c and nativeccache.c + // Warning: also called by NativeCreds.c and nativeccache.c public Credentials(Ticket new_ticket, PrincipalName new_client, PrincipalName new_client_alias, @@ -478,7 +484,7 @@ public class Credentials { * * @param service the name of service principal using format * components@realm - * @param ccreds client's initial credential. + * @param initCreds client's initial credential. * @exception IOException if an error occurs in reading the credentials * cache * @exception KrbException if an error occurs specific to Kerberos @@ -486,21 +492,21 @@ public class Credentials { */ public static Credentials acquireServiceCreds(String service, - Credentials ccreds) + Credentials initCreds) throws KrbException, IOException { - return CredentialsUtil.acquireServiceCreds(service, ccreds); + return CredentialsUtil.acquireServiceCreds(service, initCreds); } public static Credentials acquireS4U2selfCreds(PrincipalName user, - Credentials ccreds) throws KrbException, IOException { - return CredentialsUtil.acquireS4U2selfCreds(user, ccreds); + Credentials middleTGT) throws KrbException, IOException { + return CredentialsUtil.acquireS4U2selfCreds(user, middleTGT); } public static Credentials acquireS4U2proxyCreds(String service, - Ticket second, PrincipalName client, Credentials ccreds) + Credentials userCreds, PrincipalName client, Credentials middleTGT) throws KrbException, IOException { return CredentialsUtil.acquireS4U2proxyCreds( - service, second, client, ccreds); + service, userCreds, client, middleTGT); } /* diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java b/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java index 25af49ea451dd364e75dfc7f8396bc869bd8fbfe..5790b06170b9586c139ed770ad2e17e92c5a68a5 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java @@ -188,21 +188,22 @@ public final class KdcComm { this.realm = realm; } - public byte[] send(byte[] obuf) + public byte[] send(KrbKdcReq req) throws IOException, KrbException { int udpPrefLimit = getRealmSpecificValue( realm, "udp_preference_limit", defaultUdpPrefLimit); + byte[] obuf = req.encoding(); boolean useTCP = (udpPrefLimit > 0 && (obuf != null && obuf.length > udpPrefLimit)); - return send(obuf, useTCP); + return send(req, useTCP); } - private byte[] send(byte[] obuf, boolean useTCP) + private byte[] send(KrbKdcReq req, boolean useTCP) throws IOException, KrbException { - if (obuf == null) + if (req == null) return null; Config cfg = Config.getInstance(); @@ -225,12 +226,12 @@ public final class KdcComm { } byte[] ibuf = null; try { - ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP); + ibuf = sendIfPossible(req, tempKdc.next(), useTCP); } catch(Exception first) { boolean ok = false; while(tempKdc.hasNext()) { try { - ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP); + ibuf = sendIfPossible(req, tempKdc.next(), useTCP); ok = true; break; } catch(Exception ignore) {} @@ -243,13 +244,13 @@ public final class KdcComm { return ibuf; } - // send the AS Request to the specified KDC + // send the KDC Request to the specified KDC // failover to using TCP if useTCP is not set and response is too big - private byte[] sendIfPossible(byte[] obuf, String tempKdc, boolean useTCP) + private byte[] sendIfPossible(KrbKdcReq req, String tempKdc, boolean useTCP) throws IOException, KrbException { try { - byte[] ibuf = send(obuf, tempKdc, useTCP); + byte[] ibuf = send(req, tempKdc, useTCP); KRBError ke = null; try { ke = new KRBError(ibuf); @@ -259,10 +260,17 @@ public final class KdcComm { if (ke != null) { if (ke.getErrorCode() == Krb5.KRB_ERR_RESPONSE_TOO_BIG) { - ibuf = send(obuf, tempKdc, true); + ibuf = send(req, tempKdc, true); } else if (ke.getErrorCode() == Krb5.KDC_ERR_SVC_UNAVAILABLE) { throw new KrbException("A service is not available"); + } else if (ke.getErrorCode() == Krb5.KDC_ERR_BADOPTION + && Credentials.S4U2PROXY_ACCEPT_NON_FORWARDABLE + && req instanceof KrbTgsReq tgsReq) { + Credentials extra = tgsReq.getAdditionalCreds(); + if (extra != null && !extra.isForwardable()) { + throw new KrbException("S4U2Proxy with non-forwardable ticket"); + } } } KdcAccessibility.removeBad(tempKdc); @@ -278,12 +286,12 @@ public final class KdcComm { } } - // send the AS Request to the specified KDC + // send the KDC Request to the specified KDC - private byte[] send(byte[] obuf, String tempKdc, boolean useTCP) + private byte[] send(KrbKdcReq req, String tempKdc, boolean useTCP) throws IOException, KrbException { - if (obuf == null) + if (req == null) return null; int port = Krb5.KDC_INET_DEFAULT_PORT; @@ -336,6 +344,7 @@ public final class KdcComm { port = tempPort; } + byte[] obuf = req.encoding(); if (DEBUG) { System.out.println(">>> KrbKdcReq send: kdc=" + kdc + (useTCP ? " TCP:":" UDP:") diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReq.java index 19e3ef61076237894fdb8e6e46791d8c363d1e3a..580beddf21bb9cd21491b603d12b03a0da6a08c7 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReq.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReq.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ import java.util.Arrays; * This class encapsulates the KRB-AS-REQ message that the client * sends to the KDC. */ -public class KrbAsReq { +public class KrbAsReq extends KrbKdcReq { private ASReq asReqMessg; private boolean DEBUG = Krb5.DEBUG; @@ -165,10 +165,7 @@ public class KrbAsReq { asReqMessg = new ASReq( paData, kdc_req_body); - } - - byte[] encoding() throws IOException, Asn1Exception { - return asReqMessg.asn1Encode(); + obuf = asReqMessg.asn1Encode(); } // Used by KrbAsRep to validate AS-REP diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReqBuilder.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReqBuilder.java index bdd70d64911885b1b1956bbeaa96f7241c446251..177f714d1ea9ff5a5713a4d31795c782d4aa3f22 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReqBuilder.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbAsReqBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -342,7 +342,7 @@ public final class KrbAsReqBuilder { } try { req = build(pakey, referralsState); - rep = new KrbAsRep(comm.send(req.encoding())); + rep = new KrbAsRep(comm.send(req)); return this; } catch (KrbException ke) { if (!preAuthFailedOnce && ( diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbKdcReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbKdcReq.java new file mode 100644 index 0000000000000000000000000000000000000000..e64cc977b460bf3718f36a83d17a47cd99ccca63 --- /dev/null +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbKdcReq.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.krb5; + +/** + * Parent class for KrbAsReq and KrbTgsReq. + */ +abstract class KrbKdcReq { + + protected byte[] obuf; + + public byte[] encoding() { + return obuf; + } +} diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsRep.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsRep.java index 356bfe110f7916988dea0b7a21740a790c7bdd60..c9eb9eaf21fc0d9fbb1e9b3da3f2c5047fc0d31a 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsRep.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsRep.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ import java.io.IOException; public class KrbTgsRep extends KrbKdcRep { private TGSRep rep; private Credentials creds; - private Ticket secondTicket; + private Credentials additionalCreds; KrbTgsRep(byte[] ibuf, KrbTgsReq tgsReq) throws KrbException, IOException { @@ -115,7 +115,7 @@ public class KrbTgsRep extends KrbKdcRep { enc_part.caddr ); this.rep = rep; - this.secondTicket = tgsReq.getSecondTicket(); + this.additionalCreds = tgsReq.getAdditionalCreds(); } /** @@ -126,7 +126,8 @@ public class KrbTgsRep extends KrbKdcRep { } sun.security.krb5.internal.ccache.Credentials setCredentials() { - return new sun.security.krb5.internal.ccache.Credentials(rep, secondTicket); + return new sun.security.krb5.internal.ccache.Credentials( + rep, additionalCreds == null ? null : additionalCreds.ticket); } private static boolean isReferralSname(PrincipalName sname) { diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java index cedd612d2c9d481b5fa20ede2171a818c5b5e9e6..8c2b70681116b5165b833ff13cdd70073ad732f4 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/KrbTgsReq.java @@ -42,7 +42,7 @@ import java.util.Arrays; * This class encapsulates a Kerberos TGS-REQ that is sent from the * client to the KDC. */ -public class KrbTgsReq { +public class KrbTgsReq extends KrbKdcReq { private PrincipalName princName; private PrincipalName clientAlias; @@ -50,34 +50,31 @@ public class KrbTgsReq { private PrincipalName serverAlias; private TGSReq tgsReqMessg; private KerberosTime ctime; - private Ticket secondTicket = null; + private Credentials additionalCreds = null; private boolean useSubkey = false; EncryptionKey tgsReqKey; - private byte[] obuf; - private byte[] ibuf; - // Used in CredentialsUtil public KrbTgsReq(KDCOptions options, Credentials asCreds, PrincipalName cname, PrincipalName clientAlias, PrincipalName sname, PrincipalName serverAlias, - Ticket[] additionalTickets, PAData[] extraPAs) - throws KrbException, IOException { + Credentials additionalCreds, PAData[] extraPAs) + throws KrbException, IOException { this(options, - asCreds, - cname, - clientAlias, - sname, - serverAlias, - null, // KerberosTime from - null, // KerberosTime till - null, // KerberosTime rtime - null, // int[] eTypes - null, // HostAddresses addresses - null, // AuthorizationData authorizationData - additionalTickets, - null, // EncryptionKey subKey - extraPAs); + asCreds, + cname, + clientAlias, + sname, + serverAlias, + null, // KerberosTime from + null, // KerberosTime till + null, // KerberosTime rtime + null, // int[] eTypes + null, // HostAddresses addresses + null, // AuthorizationData authorizationData + additionalCreds, + null, // EncryptionKey subKey + extraPAs); } // Called by Credentials, KrbCred @@ -92,11 +89,11 @@ public class KrbTgsReq { int[] eTypes, HostAddresses addresses, AuthorizationData authorizationData, - Ticket[] additionalTickets, + Credentials additionalCreds, EncryptionKey subKey) throws KrbException, IOException { this(options, asCreds, asCreds.getClient(), asCreds.getClientAlias(), sname, serverAlias, from, till, rtime, eTypes, - addresses, authorizationData, additionalTickets, subKey, null); + addresses, authorizationData, additionalCreds, subKey, null); } private KrbTgsReq( @@ -112,7 +109,7 @@ public class KrbTgsReq { int[] eTypes, HostAddresses addresses, AuthorizationData authorizationData, - Ticket[] additionalTickets, + Credentials additionalCreds, EncryptionKey subKey, PAData[] extraPAs) throws KrbException, IOException { @@ -154,24 +151,24 @@ public class KrbTgsReq { if (!(asCreds.flags.get(KDCOptions.POSTDATED))) throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS); } else { - if (from != null) from = null; + if (from != null) from = null; } if (options.get(KDCOptions.RENEWABLE)) { if (!(asCreds.flags.get(KDCOptions.RENEWABLE))) throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS); } else { - if (rtime != null) rtime = null; + if (rtime != null) rtime = null; } if (options.get(KDCOptions.ENC_TKT_IN_SKEY) || options.get(KDCOptions.CNAME_IN_ADDL_TKT)) { - if (additionalTickets == null) + if (additionalCreds == null) throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS); // in TGS_REQ there could be more than one additional // tickets, but in file-based credential cache, // there is only one additional ticket field. - secondTicket = additionalTickets[0]; + this.additionalCreds = additionalCreds; } else { - if (additionalTickets != null) - additionalTickets = null; + if (additionalCreds != null) + additionalCreds = null; } tgsReqMessg = createRequest( @@ -187,7 +184,7 @@ public class KrbTgsReq { eTypes, addresses, authorizationData, - additionalTickets, + additionalCreds, subKey, extraPAs); obuf = tgsReqMessg.asn1Encode(); @@ -206,34 +203,16 @@ public class KrbTgsReq { } - /** - * Sends a TGS request to the realm of the target. - * @throws KrbException - * @throws IOException - */ - public void send() throws IOException, KrbException { - String realmStr = null; - if (servName != null) - realmStr = servName.getRealmString(); - KdcComm comm = new KdcComm(realmStr); - ibuf = comm.send(obuf); - } - - public KrbTgsRep getReply() - throws KrbException, IOException { - return new KrbTgsRep(ibuf, this); - } - /** * Sends the request, waits for a reply, and returns the Credentials. * Used in Credentials, KrbCred, and internal/CredentialsUtil. */ public Credentials sendAndGetCreds() throws IOException, KrbException { - KrbTgsRep tgs_rep = null; - String kdc = null; - send(); - tgs_rep = getReply(); - return tgs_rep.getCreds(); + String realmStr = servName != null + ? servName.getRealmString() + : null; + KdcComm comm = new KdcComm(realmStr); + return new KrbTgsRep(comm.send(this), this).getCreds(); } KerberosTime getCtime() { @@ -253,7 +232,7 @@ public class KrbTgsReq { int[] eTypes, HostAddresses addresses, AuthorizationData authorizationData, - Ticket[] additionalTickets, + Credentials additionalCreds, EncryptionKey subKey, PAData[] extraPAs) throws IOException, KrbException, UnknownHostException { @@ -302,6 +281,8 @@ public class KrbTgsReq { KeyUsage.KU_TGS_REQ_AUTH_DATA_SESSKEY); } + Ticket[] additionalTickets = additionalCreds == null ? null + : new Ticket[] { additionalCreds.getTicket() }; KDCReqBody reqBody = new KDCReqBody( kdc_options, cname, @@ -347,8 +328,8 @@ public class KrbTgsReq { return tgsReqMessg; } - Ticket getSecondTicket() { - return secondTicket; + Credentials getAdditionalCreds() { + return additionalCreds; } PrincipalName getClientAlias() { diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java b/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java index 41d27b0557089c287a42a0a13dbcb904cb43264c..8edf42deddd5bd74f93eb4534b641e3c02b99909 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java @@ -34,7 +34,7 @@ package sun.security.krb5; import sun.security.krb5.internal.*; import sun.security.util.*; import java.net.*; -import java.util.Vector; +import java.util.ArrayList; import java.util.Locale; import java.io.IOException; import java.math.BigInteger; @@ -270,15 +270,14 @@ public class PrincipalName implements Cloneable { if (subDer.getTag() != DerValue.tag_SequenceOf) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); DerValue subSubDer; while(subDer.getData().available() > 0) { subSubDer = subDer.getData().getDerValue(); String namePart = new KerberosString(subSubDer).toString(); - v.addElement(namePart); + v.add(namePart); } - nameStrings = new String[v.size()]; - v.copyInto(nameStrings); + nameStrings = v.toArray(new String[0]); validateNameStrings(nameStrings); } else { throw new Asn1Exception(Krb5.ASN1_BAD_ID); @@ -326,7 +325,7 @@ public class PrincipalName implements Cloneable { // Code repetition, realm parsed again by class Realm private static String[] parseName(String name) { - Vector tempStrings = new Vector<>(); + ArrayList tempStrings = new ArrayList<>(); String temp = name; int i = 0; int componentStart = 0; @@ -346,7 +345,7 @@ public class PrincipalName implements Cloneable { else { if (componentStart <= i) { component = temp.substring(componentStart, i); - tempStrings.addElement(component); + tempStrings.add(component); } componentStart = i + 1; } @@ -363,7 +362,7 @@ public class PrincipalName implements Cloneable { } else { if (componentStart < i) { component = temp.substring(componentStart, i); - tempStrings.addElement(component); + tempStrings.add(component); } componentStart = i + 1; break; @@ -375,11 +374,10 @@ public class PrincipalName implements Cloneable { if (i == temp.length()) { component = temp.substring(componentStart, i); - tempStrings.addElement(component); + tempStrings.add(component); } - String[] result = new String[tempStrings.size()]; - tempStrings.copyInto(result); + String[] result = tempStrings.toArray(new String[0]); return result; } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java index abbac5f95c88386d9508f6d86f459111b4ee57be..a1f9a6ac3cc3a2058619a57848e87f25ba53804e 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java @@ -31,7 +31,7 @@ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; import java.math.BigInteger; @@ -173,33 +173,32 @@ public class Authenticator { * @exception IOException if an I/O error occurs while reading encoded data. */ public byte[] asn1Encode() throws Asn1Exception, IOException { - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); DerOutputStream temp = new DerOutputStream(); temp.putInteger(BigInteger.valueOf(authenticator_vno)); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x00), temp.toByteArray())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x01), cname.getRealm().asn1Encode())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x02), cname.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x00), temp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x01), cname.getRealm().asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x02), cname.asn1Encode())); if (cksum != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x03), cksum.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x03), cksum.asn1Encode())); } temp = new DerOutputStream(); temp.putInteger(BigInteger.valueOf(cusec)); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x04), temp.toByteArray())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x05), ctime.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x04), temp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x05), ctime.asn1Encode())); if (subKey != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x06), subKey.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x06), subKey.asn1Encode())); } if (seqNumber != null) { temp = new DerOutputStream(); // encode as an unsigned integer (UInt32) temp.putInteger(BigInteger.valueOf(seqNumber.longValue())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x07), temp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x07), temp.toByteArray())); } if (authorizationData != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x08), authorizationData.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x08), authorizationData.asn1Encode())); } - DerValue[] der = new DerValue[v.size()]; - v.copyInto(der); + DerValue[] der = v.toArray(new DerValue[0]); temp = new DerOutputStream(); temp.putSequence(der); DerOutputStream out = new DerOutputStream(); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java index 204c8b8e3545a7845f5b9bda9f8de69c6d93d2ab..5325d54bc5c2fdf6656241b4fa3e1d1aa9f56f71 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import sun.security.util.*; import sun.security.krb5.Asn1Exception; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; import sun.security.krb5.internal.ccache.CCacheOutputStream; @@ -99,16 +99,15 @@ public class AuthorizationData implements Cloneable { * @exception IOException if an I/O error occurs while reading encoded data. */ public AuthorizationData(DerValue der) throws Asn1Exception, IOException { - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); if (der.getTag() != DerValue.tag_Sequence) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } while (der.getData().available() > 0) { - v.addElement(new AuthorizationDataEntry(der.getData().getDerValue())); + v.add(new AuthorizationDataEntry(der.getData().getDerValue())); } if (v.size() > 0) { - entry = new AuthorizationDataEntry[v.size()]; - v.copyInto(entry); + entry = v.toArray(new AuthorizationDataEntry[0]); } } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/CredentialsUtil.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/CredentialsUtil.java index 1f5f033c58b1c9eefd5f70742bcdd6e62bfda3f7..223810f67b51a89dd7d0f1844640d28f10514506 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/CredentialsUtil.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/CredentialsUtil.java @@ -32,7 +32,6 @@ package sun.security.krb5.internal; import sun.security.krb5.*; -import sun.security.util.DerValue; import java.io.IOException; import java.util.LinkedList; @@ -55,17 +54,14 @@ public class CredentialsUtil { * Used by a middle server to acquire credentials on behalf of a * user to itself using the S4U2self extension. * @param user the user to impersonate - * @param ccreds the TGT of the middle service + * @param middleTGT the TGT of the middle service * @return the new creds (cname=user, sname=middle) */ public static Credentials acquireS4U2selfCreds(PrincipalName user, - Credentials ccreds) throws KrbException, IOException { - if (!ccreds.isForwardable()) { - throw new KrbException("S4U2self needs a FORWARDABLE ticket"); - } - PrincipalName sname = ccreds.getClient(); + Credentials middleTGT) throws KrbException, IOException { + PrincipalName sname = middleTGT.getClient(); String uRealm = user.getRealmString(); - String localRealm = ccreds.getClient().getRealmString(); + String localRealm = sname.getRealmString(); if (!uRealm.equals(localRealm)) { // Referrals will be required because the middle service // and the user impersonated are on different realms. @@ -73,25 +69,25 @@ public class CredentialsUtil { throw new KrbException("Cross-realm S4U2Self request not" + " possible when referrals are disabled."); } - if (ccreds.getClientAlias() != null) { + if (middleTGT.getClientAlias() != null) { // If the name was canonicalized, the user pick // has preference. This gives the possibility of // using FQDNs that KDCs may use to return referrals. // I.e.: a SVC/host.realm-2.com@REALM-1.COM name // may be used by REALM-1.COM KDC to return a // referral to REALM-2.COM. - sname = ccreds.getClientAlias(); + sname = middleTGT.getClientAlias(); } sname = new PrincipalName(sname.getNameType(), sname.getNameStrings(), new Realm(uRealm)); } Credentials creds = serviceCreds( KDCOptions.with(KDCOptions.FORWARDABLE), - ccreds, ccreds.getClient(), sname, user, + middleTGT, middleTGT.getClient(), sname, user, null, new PAData[] { new PAData(Krb5.PA_FOR_USER, new PAForUserEnc(user, - ccreds.getSessionKey()).asn1Encode()), + middleTGT.getSessionKey()).asn1Encode()), new PAData(Krb5.PA_PAC_OPTIONS, new PaPacOptions() .setResourceBasedConstrainedDelegation(true) @@ -101,7 +97,7 @@ public class CredentialsUtil { if (!creds.getClient().equals(user)) { throw new KrbException("S4U2self request not honored by KDC"); } - if (!creds.isForwardable()) { + if (!creds.isForwardable() && !Credentials.S4U2PROXY_ACCEPT_NON_FORWARDABLE) { throw new KrbException("S4U2self ticket must be FORWARDABLE"); } return creds; @@ -111,17 +107,17 @@ public class CredentialsUtil { * Used by a middle server to acquire a service ticket to a backend * server using the S4U2proxy extension. * @param backend the name of the backend service - * @param second the client's service ticket to the middle server - * @param ccreds the TGT of the middle server - * @return the creds (cname=client, sname=backend) + * @param userCreds containing the user's service ticket to the middle server + * @param middleTGT the TGT of the middle server + * @return the creds (cname=user, sname=backend) */ public static Credentials acquireS4U2proxyCreds( - String backend, Ticket second, - PrincipalName client, Credentials ccreds) + String backend, Credentials userCreds, + PrincipalName client, Credentials middleTGT) throws KrbException, IOException { PrincipalName backendPrincipal = new PrincipalName(backend); String backendRealm = backendPrincipal.getRealmString(); - String localRealm = ccreds.getClient().getRealmString(); + String localRealm = middleTGT.getClient().getRealmString(); if (!backendRealm.equals(localRealm)) { // The middle service and the backend service are on // different realms, so referrals will be required. @@ -136,8 +132,8 @@ public class CredentialsUtil { } Credentials creds = serviceCreds(KDCOptions.with( KDCOptions.CNAME_IN_ADDL_TKT, KDCOptions.FORWARDABLE), - ccreds, ccreds.getClient(), backendPrincipal, null, - new Ticket[] {second}, new PAData[] { + middleTGT, middleTGT.getClient(), backendPrincipal, null, + userCreds, new PAData[] { new PAData(Krb5.PA_PAC_OPTIONS, new PaPacOptions() .setResourceBasedConstrainedDelegation(true) @@ -159,28 +155,30 @@ public class CredentialsUtil { * from the foreign KDC. * * @param service the name of service principal - * @param ccreds client's initial credential + * @param initCreds client's initial credential */ public static Credentials acquireServiceCreds( - String service, Credentials ccreds) + String service, Credentials initCreds) throws KrbException, IOException { - PrincipalName sname = new PrincipalName(service, - PrincipalName.KRB_NT_UNKNOWN); - return serviceCreds(sname, ccreds); + return serviceCreds(new KDCOptions(), initCreds, + initCreds.getClient(), + new PrincipalName(service, PrincipalName.KRB_NT_UNKNOWN), + null, null, + null, S4U2Type.NONE); } /** * Gets a TGT to another realm * @param localRealm this realm * @param serviceRealm the other realm, cannot equals to localRealm - * @param ccreds TGT in this realm + * @param localTGT TGT in this realm * @param okAsDelegate an [out] argument to receive the okAsDelegate * property. True only if all realms allow delegation. * @return the TGT for the other realm, null if cannot find a path * @throws KrbException if something goes wrong */ private static Credentials getTGTforRealm(String localRealm, - String serviceRealm, Credentials ccreds, boolean[] okAsDelegate) + String serviceRealm, Credentials localTGT, boolean[] okAsDelegate) throws KrbException { // Get a list of realms to traverse @@ -192,7 +190,7 @@ public class CredentialsUtil { String newTgtRealm = null; okAsDelegate[0] = true; - for (cTgt = ccreds, i = 0; i < realms.length;) { + for (cTgt = localTGT, i = 0; i < realms.length;) { tempService = PrincipalName.tgsService(serviceRealm, realms[i]); if (DEBUG) { @@ -309,10 +307,10 @@ public class CredentialsUtil { * This method does the real job to request the service credential. */ private static Credentials serviceCreds( - PrincipalName service, Credentials ccreds) + PrincipalName service, Credentials initCreds) throws KrbException, IOException { - return serviceCreds(new KDCOptions(), ccreds, - ccreds.getClient(), service, null, null, + return serviceCreds(new KDCOptions(), initCreds, + initCreds.getClient(), service, null, null, null, S4U2Type.NONE); } @@ -325,13 +323,13 @@ public class CredentialsUtil { private static Credentials serviceCreds( KDCOptions options, Credentials asCreds, PrincipalName cname, PrincipalName sname, - PrincipalName user, Ticket[] additionalTickets, + PrincipalName user, Credentials additionalCreds, PAData[] extraPAs, S4U2Type s4u2Type) throws KrbException, IOException { if (!Config.DISABLE_REFERRALS) { try { return serviceCredsReferrals(options, asCreds, cname, sname, - s4u2Type, user, additionalTickets, extraPAs); + s4u2Type, user, additionalCreds, extraPAs); } catch (KrbException e) { // Server may raise an error if CANONICALIZE is true. // Try CANONICALIZE false. @@ -339,7 +337,7 @@ public class CredentialsUtil { } return serviceCredsSingle(options, asCreds, cname, asCreds.getClientAlias(), sname, sname, s4u2Type, - user, additionalTickets, extraPAs); + user, additionalCreds, extraPAs); } /* @@ -350,7 +348,7 @@ public class CredentialsUtil { KDCOptions options, Credentials asCreds, PrincipalName cname, PrincipalName sname, S4U2Type s4u2Type, PrincipalName user, - Ticket[] additionalTickets, PAData[] extraPAs) + Credentials additionalCreds, PAData[] extraPAs) throws KrbException, IOException { options = new KDCOptions(options.toBooleanArray()); options.set(KDCOptions.CANONICALIZE, true); @@ -363,12 +361,12 @@ public class CredentialsUtil { while (referrals.size() <= Config.MAX_REFERRALS) { ReferralsCache.ReferralCacheEntry ref = ReferralsCache.get(cname, sname, user, - additionalTickets, refSname.getRealmString()); + additionalCreds, refSname.getRealmString()); String toRealm = null; if (ref == null) { creds = serviceCredsSingle(options, asCreds, cname, clientAlias, refSname, cSname, s4u2Type, - user, additionalTickets, extraPAs); + user, additionalCreds, extraPAs); PrincipalName server = creds.getServer(); if (!refSname.equals(server)) { String[] serverNameStrings = server.getNameStrings(); @@ -380,7 +378,7 @@ public class CredentialsUtil { // Server Name (sname) has the following format: // krbtgt/TO-REALM.COM@FROM-REALM.COM ReferralsCache.put(cname, sname, user, - additionalTickets, server.getRealmString(), + additionalCreds, server.getRealmString(), serverNameStrings[1], creds); toRealm = serverNameStrings[1]; isReferral = true; @@ -398,13 +396,11 @@ public class CredentialsUtil { toRealm = handleS4U2ProxyReferral(asCreds, credsInOut, sname); creds = credsInOut[0]; - if (additionalTickets == null || - additionalTickets.length == 0 || - credsInOut[1] == null) { + if (additionalCreds == null || credsInOut[1] == null) { throw new KrbException("Additional tickets expected" + " for S4U2Proxy."); } - additionalTickets[0] = credsInOut[1].getTicket(); + additionalCreds = credsInOut[1]; } else if (s4u2Type == S4U2Type.SELF) { handleS4U2SelfReferral(extraPAs, user, creds); } @@ -436,7 +432,7 @@ public class CredentialsUtil { PrincipalName cname, PrincipalName clientAlias, PrincipalName refSname, PrincipalName sname, S4U2Type s4u2Type, PrincipalName user, - Ticket[] additionalTickets, PAData[] extraPAs) + Credentials additionalCreds, PAData[] extraPAs) throws KrbException, IOException { Credentials theCreds = null; boolean[] okAsDelegate = new boolean[]{true}; @@ -473,7 +469,7 @@ public class CredentialsUtil { " same realm"); } KrbTgsReq req = new KrbTgsReq(options, asCreds, cname, clientAlias, - refSname, sname, additionalTickets, extraPAs); + refSname, sname, additionalCreds, extraPAs); theCreds = req.sendAndGetCreds(); if (theCreds != null) { if (DEBUG) { diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java index ec9d3a24ed17aad6a32e2c57bed2cb6e8ede1116..0ca67450d4291a5f9e0303f3606eabf3cf071c26 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; import java.math.BigInteger; @@ -133,26 +133,25 @@ public class EncAPRepPart { * @exception IOException if an I/O error occurs while reading encoded data. */ public byte[] asn1Encode() throws Asn1Exception, IOException { - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); DerOutputStream temp = new DerOutputStream(); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x00), ctime.asn1Encode())); temp.putInteger(BigInteger.valueOf(cusec)); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x01), temp.toByteArray())); if (subKey != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x02), subKey.asn1Encode())); } if (seqNumber != null) { temp = new DerOutputStream(); // encode as an unsigned integer (UInt32) temp.putInteger(BigInteger.valueOf(seqNumber.longValue())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x03), temp.toByteArray())); } - DerValue[] der = new DerValue[v.size()]; - v.copyInto(der); + DerValue[] der = v.toArray(new DerValue[0]); temp = new DerOutputStream(); temp.putSequence(der); DerOutputStream out = new DerOutputStream(); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java index 5f533c1cc7b88d4cf1916ab5c45c255933b716ed..070ad970bdbd5d470e499964ff7067326ce1e175 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -178,15 +178,14 @@ public class HostAddresses implements Cloneable { */ public HostAddresses(DerValue encoding) throws Asn1Exception, IOException { - Vector tempAddresses = new Vector<>(); + ArrayList tempAddresses = new ArrayList<>(); DerValue der = null; while (encoding.getData().available() > 0) { der = encoding.getData().getDerValue(); - tempAddresses.addElement(new HostAddress(der)); + tempAddresses.add(new HostAddress(der)); } if (tempAddresses.size() > 0) { - addresses = new HostAddress[tempAddresses.size()]; - tempAddresses.copyInto(addresses); + addresses = tempAddresses.toArray(new HostAddress[0]); } } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReq.java index 39e226a8de2dee03e555a45f21f5c1d2500f7bad..fd37366d7b0c2320c9044aca7d4dff865a73495c 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReq.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReq.java @@ -31,7 +31,6 @@ package sun.security.krb5.internal; import sun.security.krb5.*; -import java.util.Vector; import sun.security.util.*; import java.io.IOException; import java.math.BigInteger; @@ -192,8 +191,4 @@ public class KDCReq { true, (byte) msgType), bytes); return out.toByteArray(); } - - public byte[] asn1EncodeReqBody() throws Asn1Exception, IOException { - return reqBody.asn1Encode(msgType); - } } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java index 8c1b246d061bf926a96babda55f37771b731e704..8579dfdac4123377ffc08493a7e2c100ef5d5c6a 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; import java.math.BigInteger; @@ -165,17 +165,17 @@ public class KDCReqBody { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } der = encoding.getData().getDerValue(); - Vector v = new Vector<>(); if ((der.getTag() & (byte)0x1F) == (byte)0x08) { subDer = der.getData().getDerValue(); if (subDer.getTag() == DerValue.tag_SequenceOf) { + ArrayList v = new ArrayList<>(); while(subDer.getData().available() > 0) { - v.addElement(subDer.getData().getBigInteger().intValue()); + v.add(subDer.getData().getBigInteger().intValue()); } eType = new int[v.size()]; for (int i = 0; i < v.size(); i++) { - eType[i] = v.elementAt(i); + eType[i] = v.get(i); } } else { throw new Asn1Exception(Krb5.ASN1_BAD_ID); @@ -190,20 +190,19 @@ public class KDCReqBody { encAuthorizationData = EncryptedData.parse(encoding.getData(), (byte)0x0A, true); } if (encoding.getData().available() > 0) { - Vector tempTickets = new Vector<>(); der = encoding.getData().getDerValue(); if ((der.getTag() & (byte)0x1F) == (byte)0x0B) { + ArrayList tempTickets = new ArrayList<>(); subDer = der.getData().getDerValue(); if (subDer.getTag() == DerValue.tag_SequenceOf) { while (subDer.getData().available() > 0) { - tempTickets.addElement(new Ticket(subDer.getData().getDerValue())); + tempTickets.add(new Ticket(subDer.getData().getDerValue())); } } else { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } if (tempTickets.size() > 0) { - additionalTickets = new Ticket[tempTickets.size()]; - tempTickets.copyInto(additionalTickets); + additionalTickets = tempTickets.toArray(new Ticket[0]); } } else { throw new Asn1Exception(Krb5.ASN1_BAD_ID); @@ -223,29 +222,29 @@ public class KDCReqBody { * */ public byte[] asn1Encode(int msgType) throws Asn1Exception, IOException { - Vector v = new Vector<>(); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), kdcOptions.asn1Encode())); + ArrayList v = new ArrayList<>(); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), kdcOptions.asn1Encode())); if (msgType == Krb5.KRB_AS_REQ) { if (cname != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), cname.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), cname.asn1Encode())); } } if (sname != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), sname.getRealm().asn1Encode())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x03), sname.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), sname.getRealm().asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x03), sname.asn1Encode())); } else if (cname != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), cname.getRealm().asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), cname.getRealm().asn1Encode())); } if (from != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x04), from.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x04), from.asn1Encode())); } - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x05), till.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x05), till.asn1Encode())); if (rtime != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x06), rtime.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x06), rtime.asn1Encode())); } DerOutputStream temp = new DerOutputStream(); temp.putInteger(BigInteger.valueOf(nonce)); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x07), temp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x07), temp.toByteArray())); //revisit, if empty eType sequences are allowed temp = new DerOutputStream(); for (int i = 0; i < eType.length; i++) { @@ -253,12 +252,12 @@ public class KDCReqBody { } DerOutputStream eTypetemp = new DerOutputStream(); eTypetemp.write(DerValue.tag_SequenceOf, temp); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x08), eTypetemp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x08), eTypetemp.toByteArray())); if (addresses != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x09), addresses.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x09), addresses.asn1Encode())); } if (encAuthorizationData != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0A), encAuthorizationData.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0A), encAuthorizationData.asn1Encode())); } if (additionalTickets != null && additionalTickets.length > 0) { temp = new DerOutputStream(); @@ -267,10 +266,9 @@ public class KDCReqBody { } DerOutputStream ticketsTemp = new DerOutputStream(); ticketsTemp.write(DerValue.tag_SequenceOf, temp); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0B), ticketsTemp.toByteArray())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0B), ticketsTemp.toByteArray())); } - DerValue[] der = new DerValue[v.size()]; - v.copyInto(der); + DerValue[] der = v.toArray(new DerValue[0]); temp = new DerOutputStream(); temp.putSequence(der); return temp.toByteArray(); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBCred.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBCred.java index 5ebe985bbed7ce5b32c2d9e40bfcd5b1b34b2198..1b05c0969b7e63254834d571fbdeda5319286a0b 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBCred.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBCred.java @@ -34,7 +34,7 @@ import sun.security.krb5.EncryptedData; import sun.security.krb5.Asn1Exception; import sun.security.krb5.RealmException; import sun.security.util.*; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; import java.math.BigInteger; @@ -134,13 +134,12 @@ public class KRBCred { if (subsubDer.getTag() != DerValue.tag_SequenceOf) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); while (subsubDer.getData().available() > 0) { - v.addElement(new Ticket(subsubDer.getData().getDerValue())); + v.add(new Ticket(subsubDer.getData().getDerValue())); } if (v.size() > 0) { - tickets = new Ticket[v.size()]; - v.copyInto(tickets); + tickets = v.toArray(new Ticket[0]); } } else { throw new Asn1Exception(Krb5.ASN1_BAD_ID); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java index 952506c5b74bc8a38f523dbe602dc880d194fab1..d4aecbeda267605215df82369cb20323282f436d 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; /** @@ -150,30 +150,29 @@ public class KrbCredInfo { * @exception IOException if an I/O error occurs while reading encoded data. */ public byte[] asn1Encode() throws Asn1Exception, IOException { - Vector v = new Vector<>(); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), key.asn1Encode())); + ArrayList v = new ArrayList<>(); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), key.asn1Encode())); if (pname != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), pname.getRealm().asn1Encode())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), pname.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), pname.getRealm().asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), pname.asn1Encode())); } if (flags != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x03), flags.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x03), flags.asn1Encode())); if (authtime != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x04), authtime.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x04), authtime.asn1Encode())); if (starttime != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x05), starttime.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x05), starttime.asn1Encode())); if (endtime != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x06), endtime.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x06), endtime.asn1Encode())); if (renewTill != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x07), renewTill.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x07), renewTill.asn1Encode())); if (sname != null) { - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x08), sname.getRealm().asn1Encode())); - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x09), sname.asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x08), sname.getRealm().asn1Encode())); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x09), sname.asn1Encode())); } if (caddr != null) - v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0A), caddr.asn1Encode())); - DerValue[] der = new DerValue[v.size()]; - v.copyInto(der); + v.add(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0A), caddr.asn1Encode())); + DerValue[] der = v.toArray(new DerValue[0]); DerOutputStream out = new DerOutputStream(); out.putSequence(der); return out.toByteArray(); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/LastReq.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/LastReq.java index 9e160b0cf281e347c267207897cb2eee789263f8..58148d98856b4292ee6049e13065b58f31982cb0 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/LastReq.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/LastReq.java @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import sun.security.util.*; import sun.security.krb5.Asn1Exception; -import java.util.Vector; +import java.util.ArrayList; import java.io.IOException; /** @@ -77,16 +77,15 @@ public class LastReq { */ public LastReq(DerValue encoding) throws Asn1Exception, IOException { - Vector v= new Vector<>(); + ArrayList v = new ArrayList<>(); if (encoding.getTag() != DerValue.tag_Sequence) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } while (encoding.getData().available() > 0) { - v.addElement(new LastReqEntry(encoding.getData().getDerValue())); + v.add(new LastReqEntry(encoding.getData().getDerValue())); } if (v.size() > 0) { - entry = new LastReqEntry[v.size()]; - v.copyInto(entry); + entry = v.toArray(new LastReqEntry[0]); } } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/PAData.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/PAData.java index 602ddf91fb1c905d0ef43a66e20b392288951f2e..bcbae770505de99bc70e295f008faab694d19c3c 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/PAData.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/PAData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ package sun.security.krb5.internal; import java.io.IOException; -import java.util.Vector; +import java.util.ArrayList; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; @@ -167,13 +167,12 @@ public class PAData { if (subsubDer.getTag() != DerValue.tag_SequenceOf) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); while (subsubDer.getData().available() > 0) { - v.addElement(new PAData(subsubDer.getData().getDerValue())); + v.add(new PAData(subsubDer.getData().getDerValue())); } if (v.size() > 0) { - PAData[] pas = new PAData[v.size()]; - v.copyInto(pas); + PAData[] pas = v.toArray(new PAData[0]); return pas; } return null; diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ReferralsCache.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ReferralsCache.java index c8f7414877badee912635783e48852fea11b1b8e..fa68fc42b2e1673a48e41ec0dece6d56c110f572 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ReferralsCache.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ReferralsCache.java @@ -112,10 +112,10 @@ final class ReferralsCache { * REALM-1.COM -> REALM-2.COM referral entry is removed from the cache. */ static synchronized void put(PrincipalName cname, PrincipalName service, - PrincipalName user, Ticket[] userSvcTickets, String fromRealm, + PrincipalName user, Credentials additionalCreds, String fromRealm, String toRealm, Credentials creds) { - Ticket userSvcTicket = (userSvcTickets != null ? - userSvcTickets[0] : null); + Ticket userSvcTicket = (additionalCreds != null ? + additionalCreds.getTicket() : null); ReferralCacheKey k = new ReferralCacheKey(cname, service, user, userSvcTicket); pruneExpired(k); @@ -152,9 +152,9 @@ final class ReferralsCache { */ static synchronized ReferralCacheEntry get(PrincipalName cname, PrincipalName service, PrincipalName user, - Ticket[] userSvcTickets, String fromRealm) { - Ticket userSvcTicket = (userSvcTickets != null ? - userSvcTickets[0] : null); + Credentials additionalCreds, String fromRealm) { + Ticket userSvcTicket = (additionalCreds != null ? + additionalCreds.getTicket() : null); ReferralCacheKey k = new ReferralCacheKey(cname, service, user, userSvcTicket); pruneExpired(k); diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java index e4253d9bcf1eaf2be675b07817d380c7d450f92c..b9268ce2b6c1442e2b87e3a554a220f1d3d11667 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java @@ -85,12 +85,12 @@ public class Ticket implements Cloneable { // Warning: called by NativeCreds.c and nativeccache.c public Ticket(byte[] data) throws Asn1Exception, - RealmException, KrbApErrException, IOException { + RealmException, KrbApErrException, IOException { init(new DerValue(data)); } public Ticket(DerValue encoding) throws Asn1Exception, - RealmException, KrbApErrException, IOException { + RealmException, KrbApErrException, IOException { init(encoding); } diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/FileCredentialsCache.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/FileCredentialsCache.java index f0379c04e915b4b2e7a90c2a9cd6b6075bcac25e..88c755cb4309b8e5eae2f0fb2e2f1cfdb774e59d 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/FileCredentialsCache.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/FileCredentialsCache.java @@ -567,12 +567,11 @@ public class FileCredentialsCache extends CredentialsCache private static String exec(String c) { StringTokenizer st = new StringTokenizer(c); - Vector v = new Vector<>(); + ArrayList v = new ArrayList<>(); while (st.hasMoreTokens()) { - v.addElement(st.nextToken()); + v.add(st.nextToken()); } - final String[] command = new String[v.size()]; - v.copyInto(command); + final String[] command = v.toArray(new String[0]); try { @SuppressWarnings("removal") diff --git a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ktab/KeyTab.java b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ktab/KeyTab.java index 4801d099eb8a09034fcb1c9728ffca979887df5e..a2d2c683b97ad67ff9293ef8c396a0269f459445 100644 --- a/src/java.security.jgss/share/classes/sun/security/krb5/internal/ktab/KeyTab.java +++ b/src/java.security.jgss/share/classes/sun/security/krb5/internal/ktab/KeyTab.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -123,7 +123,7 @@ public class KeyTab implements KeyTabConstants { * @param s file name of keytab, must not be null * @return the keytab object, can be invalid, but never null. */ - private synchronized static KeyTab getInstance0(String s) { + private static synchronized KeyTab getInstance0(String s) { long lm = new File(s).lastModified(); KeyTab old = map.get(s); if (old != null && old.isValid() && old.lastModified == lm) { @@ -429,7 +429,7 @@ public class KeyTab implements KeyTabConstants { /** * Creates a new default key table. */ - public synchronized static KeyTab create() + public static synchronized KeyTab create() throws IOException, RealmException { String dname = getDefaultTabName(); return create(dname); @@ -438,7 +438,7 @@ public class KeyTab implements KeyTabConstants { /** * Creates a new default key table. */ - public synchronized static KeyTab create(String name) + public static synchronized KeyTab create(String name) throws IOException, RealmException { try (KeyTabOutputStream kos = diff --git a/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Base.java b/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Base.java index bbbe88a71e4e1001bbd4bdd92682700600f30137..b59b449e3c5f3136555eab52f5b6dbb695d910e2 100644 --- a/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Base.java +++ b/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Base.java @@ -136,7 +136,7 @@ abstract class CramMD5Base { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() { clearPassword(); } diff --git a/src/java.security.sasl/share/classes/com/sun/security/sasl/PlainClient.java b/src/java.security.sasl/share/classes/com/sun/security/sasl/PlainClient.java index e365e772e6e0547df5f44c9eee4e8de9fe85dce3..04a8d9856c2c6611175621a43fa7570d5158cb85 100644 --- a/src/java.security.sasl/share/classes/com/sun/security/sasl/PlainClient.java +++ b/src/java.security.sasl/share/classes/com/sun/security/sasl/PlainClient.java @@ -195,7 +195,7 @@ final class PlainClient implements SaslClient { } } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() { clearPassword(); } diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/CardNotPresentException.java b/src/java.smartcardio/share/classes/javax/smartcardio/CardNotPresentException.java index 8efae192a0ee5f9360a93d82ab664ed8d4dba12a..6098ae2a40cb78aa0979379f78e0cc1b78373c08 100644 --- a/src/java.smartcardio/share/classes/javax/smartcardio/CardNotPresentException.java +++ b/src/java.smartcardio/share/classes/javax/smartcardio/CardNotPresentException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ package javax.smartcardio; */ public class CardNotPresentException extends CardException { - private final static long serialVersionUID = 1346879911706545215L; + private static final long serialVersionUID = 1346879911706545215L; /** * Constructs a new CardNotPresentException with the specified detail message. diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java b/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java index b70de530cf1825333d0cfdffac6c7c0c9d71f6b6..d8849c38c3de060e38f4dcbc708a0c596e08dd51 100644 --- a/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java +++ b/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,17 +74,17 @@ public class CardPermission extends Permission { private static final long serialVersionUID = 7146787880530705613L; - private final static int A_CONNECT = 0x01; - private final static int A_EXCLUSIVE = 0x02; - private final static int A_GET_BASIC_CHANNEL = 0x04; - private final static int A_OPEN_LOGICAL_CHANNEL = 0x08; - private final static int A_RESET = 0x10; - private final static int A_TRANSMIT_CONTROL = 0x20; + private static final int A_CONNECT = 0x01; + private static final int A_EXCLUSIVE = 0x02; + private static final int A_GET_BASIC_CHANNEL = 0x04; + private static final int A_OPEN_LOGICAL_CHANNEL = 0x08; + private static final int A_RESET = 0x10; + private static final int A_TRANSMIT_CONTROL = 0x20; // sum of all the actions above - private final static int A_ALL = 0x3f; + private static final int A_ALL = 0x3f; - private final static int[] ARRAY_MASKS = { + private static final int[] ARRAY_MASKS = { A_ALL, A_CONNECT, A_EXCLUSIVE, @@ -94,16 +94,16 @@ public class CardPermission extends Permission { A_TRANSMIT_CONTROL, }; - private final static String S_CONNECT = "connect"; - private final static String S_EXCLUSIVE = "exclusive"; - private final static String S_GET_BASIC_CHANNEL = "getBasicChannel"; - private final static String S_OPEN_LOGICAL_CHANNEL = "openLogicalChannel"; - private final static String S_RESET = "reset"; - private final static String S_TRANSMIT_CONTROL = "transmitControl"; + private static final String S_CONNECT = "connect"; + private static final String S_EXCLUSIVE = "exclusive"; + private static final String S_GET_BASIC_CHANNEL = "getBasicChannel"; + private static final String S_OPEN_LOGICAL_CHANNEL = "openLogicalChannel"; + private static final String S_RESET = "reset"; + private static final String S_TRANSMIT_CONTROL = "transmitControl"; - private final static String S_ALL = "*"; + private static final String S_ALL = "*"; - private final static String[] ARRAY_STRINGS = { + private static final String[] ARRAY_STRINGS = { S_ALL, S_CONNECT, S_EXCLUSIVE, diff --git a/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java b/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java index 0d6e7a55a2bd00221ba735ff7ee59275a1fe706e..a2be0caa7ea57dc551aaf42d6d1b37c5d0c656aa 100644 --- a/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java +++ b/src/java.smartcardio/share/classes/javax/smartcardio/TerminalFactory.java @@ -88,12 +88,12 @@ import sun.security.jca.GetInstance.*; */ public final class TerminalFactory { - private final static String PROP_NAME = + private static final String PROP_NAME = "javax.smartcardio.TerminalFactory.DefaultType"; - private final static String defaultType; + private static final String defaultType; - private final static TerminalFactory defaultFactory; + private static final TerminalFactory defaultFactory; static { // lookup up the user specified type, default to PC/SC @@ -133,14 +133,14 @@ public final class TerminalFactory { private static final class NoneProvider extends Provider { private static final long serialVersionUID = 2745808869881593918L; - final static Provider INSTANCE = new NoneProvider(); + static final Provider INSTANCE = new NoneProvider(); private NoneProvider() { super("None", "1.0", "none"); } } private static final class NoneFactorySpi extends TerminalFactorySpi { - final static TerminalFactorySpi INSTANCE = new NoneFactorySpi(); + static final TerminalFactorySpi INSTANCE = new NoneFactorySpi(); private NoneFactorySpi() { // empty } @@ -150,7 +150,7 @@ public final class TerminalFactory { } private static final class NoneCardTerminals extends CardTerminals { - final static CardTerminals INSTANCE = new NoneCardTerminals(); + static final CardTerminals INSTANCE = new NoneCardTerminals(); private NoneCardTerminals() { // empty } diff --git a/src/java.smartcardio/share/classes/sun/security/smartcardio/CardImpl.java b/src/java.smartcardio/share/classes/sun/security/smartcardio/CardImpl.java index 576333a1421cacd83ba74fdb0980a805d6e6edda..b982df5dd07237b66d24b2b553558789213d4e65 100644 --- a/src/java.smartcardio/share/classes/sun/security/smartcardio/CardImpl.java +++ b/src/java.smartcardio/share/classes/sun/security/smartcardio/CardImpl.java @@ -276,7 +276,7 @@ final class CardImpl extends Card { + ", protocol " + getProtocol() + ", state " + state; } - @SuppressWarnings("deprecation") + @SuppressWarnings("removal") protected void finalize() throws Throwable { try { if (state == State.OK) { diff --git a/src/java.smartcardio/share/classes/sun/security/smartcardio/ChannelImpl.java b/src/java.smartcardio/share/classes/sun/security/smartcardio/ChannelImpl.java index ba1d44f20ab770a43054f47c709a1af7a52ce889..b329a140479a7511e1938bd150e4ee006ac467ec 100644 --- a/src/java.smartcardio/share/classes/sun/security/smartcardio/ChannelImpl.java +++ b/src/java.smartcardio/share/classes/sun/security/smartcardio/ChannelImpl.java @@ -114,13 +114,13 @@ final class ChannelImpl extends CardChannel { return responseBytes.length; } - private final static boolean t0GetResponse = + private static final boolean t0GetResponse = getBooleanProperty("sun.security.smartcardio.t0GetResponse", true); - private final static boolean t1GetResponse = + private static final boolean t1GetResponse = getBooleanProperty("sun.security.smartcardio.t1GetResponse", true); - private final static boolean t1StripLe = + private static final boolean t1StripLe = getBooleanProperty("sun.security.smartcardio.t1StripLe", false); private static boolean getBooleanProperty(String name, boolean def) { @@ -151,8 +151,8 @@ final class ChannelImpl extends CardChannel { return res; } - private final static int RESPONSE_ITERATIONS = 256; - private final static byte[] B0 = new byte[0]; + private static final int RESPONSE_ITERATIONS = 256; + private static final byte[] B0 = new byte[0]; private byte[] doTransmit(byte[] command) throws CardException { // note that we modify the 'command' array in some cases, so it must diff --git a/src/java.smartcardio/share/classes/sun/security/smartcardio/PCSC.java b/src/java.smartcardio/share/classes/sun/security/smartcardio/PCSC.java index 708ec34d95577224e4c5bed28a581c9e94397a1f..aca375bd043abb2a7ff3d054664868305f218a98 100644 --- a/src/java.smartcardio/share/classes/sun/security/smartcardio/PCSC.java +++ b/src/java.smartcardio/share/classes/sun/security/smartcardio/PCSC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,83 +93,83 @@ final class PCSC extends PlatformPCSC { throws PCSCException; // PCSC success/error/failure/warning codes - final static int SCARD_S_SUCCESS = 0x00000000; - final static int SCARD_E_CANCELLED = 0x80100002; - final static int SCARD_E_CANT_DISPOSE = 0x8010000E; - final static int SCARD_E_INSUFFICIENT_BUFFER = 0x80100008; - final static int SCARD_E_INVALID_ATR = 0x80100015; - final static int SCARD_E_INVALID_HANDLE = 0x80100003; - final static int SCARD_E_INVALID_PARAMETER = 0x80100004; - final static int SCARD_E_INVALID_TARGET = 0x80100005; - final static int SCARD_E_INVALID_VALUE = 0x80100011; - final static int SCARD_E_NO_MEMORY = 0x80100006; - final static int SCARD_F_COMM_ERROR = 0x80100013; - final static int SCARD_F_INTERNAL_ERROR = 0x80100001; - final static int SCARD_F_UNKNOWN_ERROR = 0x80100014; - final static int SCARD_F_WAITED_TOO_LONG = 0x80100007; - final static int SCARD_E_UNKNOWN_READER = 0x80100009; - final static int SCARD_E_TIMEOUT = 0x8010000A; - final static int SCARD_E_SHARING_VIOLATION = 0x8010000B; - final static int SCARD_E_NO_SMARTCARD = 0x8010000C; - final static int SCARD_E_UNKNOWN_CARD = 0x8010000D; - final static int SCARD_E_PROTO_MISMATCH = 0x8010000F; - final static int SCARD_E_NOT_READY = 0x80100010; - final static int SCARD_E_SYSTEM_CANCELLED = 0x80100012; - final static int SCARD_E_NOT_TRANSACTED = 0x80100016; - final static int SCARD_E_READER_UNAVAILABLE = 0x80100017; - - final static int SCARD_W_UNSUPPORTED_CARD = 0x80100065; - final static int SCARD_W_UNRESPONSIVE_CARD = 0x80100066; - final static int SCARD_W_UNPOWERED_CARD = 0x80100067; - final static int SCARD_W_RESET_CARD = 0x80100068; - final static int SCARD_W_REMOVED_CARD = 0x80100069; - final static int SCARD_W_INSERTED_CARD = 0x8010006A; - - final static int SCARD_E_UNSUPPORTED_FEATURE = 0x8010001F; - final static int SCARD_E_PCI_TOO_SMALL = 0x80100019; - final static int SCARD_E_READER_UNSUPPORTED = 0x8010001A; - final static int SCARD_E_DUPLICATE_READER = 0x8010001B; - final static int SCARD_E_CARD_UNSUPPORTED = 0x8010001C; - final static int SCARD_E_NO_SERVICE = 0x8010001D; - final static int SCARD_E_SERVICE_STOPPED = 0x8010001E; + static final int SCARD_S_SUCCESS = 0x00000000; + static final int SCARD_E_CANCELLED = 0x80100002; + static final int SCARD_E_CANT_DISPOSE = 0x8010000E; + static final int SCARD_E_INSUFFICIENT_BUFFER = 0x80100008; + static final int SCARD_E_INVALID_ATR = 0x80100015; + static final int SCARD_E_INVALID_HANDLE = 0x80100003; + static final int SCARD_E_INVALID_PARAMETER = 0x80100004; + static final int SCARD_E_INVALID_TARGET = 0x80100005; + static final int SCARD_E_INVALID_VALUE = 0x80100011; + static final int SCARD_E_NO_MEMORY = 0x80100006; + static final int SCARD_F_COMM_ERROR = 0x80100013; + static final int SCARD_F_INTERNAL_ERROR = 0x80100001; + static final int SCARD_F_UNKNOWN_ERROR = 0x80100014; + static final int SCARD_F_WAITED_TOO_LONG = 0x80100007; + static final int SCARD_E_UNKNOWN_READER = 0x80100009; + static final int SCARD_E_TIMEOUT = 0x8010000A; + static final int SCARD_E_SHARING_VIOLATION = 0x8010000B; + static final int SCARD_E_NO_SMARTCARD = 0x8010000C; + static final int SCARD_E_UNKNOWN_CARD = 0x8010000D; + static final int SCARD_E_PROTO_MISMATCH = 0x8010000F; + static final int SCARD_E_NOT_READY = 0x80100010; + static final int SCARD_E_SYSTEM_CANCELLED = 0x80100012; + static final int SCARD_E_NOT_TRANSACTED = 0x80100016; + static final int SCARD_E_READER_UNAVAILABLE = 0x80100017; + + static final int SCARD_W_UNSUPPORTED_CARD = 0x80100065; + static final int SCARD_W_UNRESPONSIVE_CARD = 0x80100066; + static final int SCARD_W_UNPOWERED_CARD = 0x80100067; + static final int SCARD_W_RESET_CARD = 0x80100068; + static final int SCARD_W_REMOVED_CARD = 0x80100069; + static final int SCARD_W_INSERTED_CARD = 0x8010006A; + + static final int SCARD_E_UNSUPPORTED_FEATURE = 0x8010001F; + static final int SCARD_E_PCI_TOO_SMALL = 0x80100019; + static final int SCARD_E_READER_UNSUPPORTED = 0x8010001A; + static final int SCARD_E_DUPLICATE_READER = 0x8010001B; + static final int SCARD_E_CARD_UNSUPPORTED = 0x8010001C; + static final int SCARD_E_NO_SERVICE = 0x8010001D; + static final int SCARD_E_SERVICE_STOPPED = 0x8010001E; // MS undocumented - final static int SCARD_E_NO_READERS_AVAILABLE = 0x8010002E; + static final int SCARD_E_NO_READERS_AVAILABLE = 0x8010002E; // std. Windows invalid handle return code, used instead of SCARD code - final static int WINDOWS_ERROR_INVALID_HANDLE = 6; - final static int WINDOWS_ERROR_INVALID_PARAMETER = 87; + static final int WINDOWS_ERROR_INVALID_HANDLE = 6; + static final int WINDOWS_ERROR_INVALID_PARAMETER = 87; // - final static int SCARD_SCOPE_USER = 0x0000; - final static int SCARD_SCOPE_TERMINAL = 0x0001; - final static int SCARD_SCOPE_SYSTEM = 0x0002; - final static int SCARD_SCOPE_GLOBAL = 0x0003; - - final static int SCARD_SHARE_EXCLUSIVE = 0x0001; - final static int SCARD_SHARE_SHARED = 0x0002; - final static int SCARD_SHARE_DIRECT = 0x0003; - - final static int SCARD_LEAVE_CARD = 0x0000; - final static int SCARD_RESET_CARD = 0x0001; - final static int SCARD_UNPOWER_CARD = 0x0002; - final static int SCARD_EJECT_CARD = 0x0003; - - final static int SCARD_STATE_UNAWARE = 0x0000; - final static int SCARD_STATE_IGNORE = 0x0001; - final static int SCARD_STATE_CHANGED = 0x0002; - final static int SCARD_STATE_UNKNOWN = 0x0004; - final static int SCARD_STATE_UNAVAILABLE = 0x0008; - final static int SCARD_STATE_EMPTY = 0x0010; - final static int SCARD_STATE_PRESENT = 0x0020; - final static int SCARD_STATE_ATRMATCH = 0x0040; - final static int SCARD_STATE_EXCLUSIVE = 0x0080; - final static int SCARD_STATE_INUSE = 0x0100; - final static int SCARD_STATE_MUTE = 0x0200; - final static int SCARD_STATE_UNPOWERED = 0x0400; - - final static int TIMEOUT_INFINITE = 0xffffffff; - - private final static char[] hexDigits = "0123456789abcdef".toCharArray(); + static final int SCARD_SCOPE_USER = 0x0000; + static final int SCARD_SCOPE_TERMINAL = 0x0001; + static final int SCARD_SCOPE_SYSTEM = 0x0002; + static final int SCARD_SCOPE_GLOBAL = 0x0003; + + static final int SCARD_SHARE_EXCLUSIVE = 0x0001; + static final int SCARD_SHARE_SHARED = 0x0002; + static final int SCARD_SHARE_DIRECT = 0x0003; + + static final int SCARD_LEAVE_CARD = 0x0000; + static final int SCARD_RESET_CARD = 0x0001; + static final int SCARD_UNPOWER_CARD = 0x0002; + static final int SCARD_EJECT_CARD = 0x0003; + + static final int SCARD_STATE_UNAWARE = 0x0000; + static final int SCARD_STATE_IGNORE = 0x0001; + static final int SCARD_STATE_CHANGED = 0x0002; + static final int SCARD_STATE_UNKNOWN = 0x0004; + static final int SCARD_STATE_UNAVAILABLE = 0x0008; + static final int SCARD_STATE_EMPTY = 0x0010; + static final int SCARD_STATE_PRESENT = 0x0020; + static final int SCARD_STATE_ATRMATCH = 0x0040; + static final int SCARD_STATE_EXCLUSIVE = 0x0080; + static final int SCARD_STATE_INUSE = 0x0100; + static final int SCARD_STATE_MUTE = 0x0200; + static final int SCARD_STATE_UNPOWERED = 0x0400; + + static final int TIMEOUT_INFINITE = 0xffffffff; + + private static final char[] hexDigits = "0123456789abcdef".toCharArray(); public static String toString(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 3); diff --git a/src/java.smartcardio/unix/classes/sun/security/smartcardio/PlatformPCSC.java b/src/java.smartcardio/unix/classes/sun/security/smartcardio/PlatformPCSC.java index 38fa3da9ea769ba8ec7571fa874cf92b4582f2a1..bacff32efbccfa687c373a2869e07d5f369af6f3 100644 --- a/src/java.smartcardio/unix/classes/sun/security/smartcardio/PlatformPCSC.java +++ b/src/java.smartcardio/unix/classes/sun/security/smartcardio/PlatformPCSC.java @@ -44,11 +44,11 @@ class PlatformPCSC { static final Debug debug = Debug.getInstance("pcsc"); - private final static String PROP_NAME = "sun.security.smartcardio.library"; + private static final String PROP_NAME = "sun.security.smartcardio.library"; - private final static String LIB1 = "/usr/$LIBISA/libpcsclite.so"; - private final static String LIB2 = "/usr/local/$LIBISA/libpcsclite.so"; - private final static String PCSC_FRAMEWORK = "/System/Library/Frameworks/PCSC.framework/Versions/Current/PCSC"; + private static final String LIB1 = "/usr/$LIBISA/libpcsclite.so"; + private static final String LIB2 = "/usr/local/$LIBISA/libpcsclite.so"; + private static final String PCSC_FRAMEWORK = "/System/Library/Frameworks/PCSC.framework/Versions/Current/PCSC"; PlatformPCSC() { // empty @@ -138,16 +138,16 @@ class PlatformPCSC { // PCSC constants defined differently under Windows and MUSCLE // MUSCLE version - final static int SCARD_PROTOCOL_T0 = 0x0001; - final static int SCARD_PROTOCOL_T1 = 0x0002; - final static int SCARD_PROTOCOL_RAW = 0x0004; - - final static int SCARD_UNKNOWN = 0x0001; - final static int SCARD_ABSENT = 0x0002; - final static int SCARD_PRESENT = 0x0004; - final static int SCARD_SWALLOWED = 0x0008; - final static int SCARD_POWERED = 0x0010; - final static int SCARD_NEGOTIABLE = 0x0020; - final static int SCARD_SPECIFIC = 0x0040; + static final int SCARD_PROTOCOL_T0 = 0x0001; + static final int SCARD_PROTOCOL_T1 = 0x0002; + static final int SCARD_PROTOCOL_RAW = 0x0004; + + static final int SCARD_UNKNOWN = 0x0001; + static final int SCARD_ABSENT = 0x0002; + static final int SCARD_PRESENT = 0x0004; + static final int SCARD_SWALLOWED = 0x0008; + static final int SCARD_POWERED = 0x0010; + static final int SCARD_NEGOTIABLE = 0x0020; + static final int SCARD_SPECIFIC = 0x0040; } diff --git a/src/java.smartcardio/windows/classes/sun/security/smartcardio/PlatformPCSC.java b/src/java.smartcardio/windows/classes/sun/security/smartcardio/PlatformPCSC.java index 37f4769465d2a14d5a5596f0a57d933496f40ad0..8541b67f613121ec35426c2e51119d04a480492b 100644 --- a/src/java.smartcardio/windows/classes/sun/security/smartcardio/PlatformPCSC.java +++ b/src/java.smartcardio/windows/classes/sun/security/smartcardio/PlatformPCSC.java @@ -58,16 +58,16 @@ class PlatformPCSC { // PCSC constants defined differently under Windows and MUSCLE // Windows version - final static int SCARD_PROTOCOL_T0 = 0x0001; - final static int SCARD_PROTOCOL_T1 = 0x0002; - final static int SCARD_PROTOCOL_RAW = 0x10000; + static final int SCARD_PROTOCOL_T0 = 0x0001; + static final int SCARD_PROTOCOL_T1 = 0x0002; + static final int SCARD_PROTOCOL_RAW = 0x10000; - final static int SCARD_UNKNOWN = 0x0000; - final static int SCARD_ABSENT = 0x0001; - final static int SCARD_PRESENT = 0x0002; - final static int SCARD_SWALLOWED = 0x0003; - final static int SCARD_POWERED = 0x0004; - final static int SCARD_NEGOTIABLE = 0x0005; - final static int SCARD_SPECIFIC = 0x0006; + static final int SCARD_UNKNOWN = 0x0000; + static final int SCARD_ABSENT = 0x0001; + static final int SCARD_PRESENT = 0x0002; + static final int SCARD_SWALLOWED = 0x0003; + static final int SCARD_POWERED = 0x0004; + static final int SCARD_NEGOTIABLE = 0x0005; + static final int SCARD_SPECIFIC = 0x0006; } diff --git a/src/java.sql.rowset/share/classes/javax/sql/rowset/RowSetProvider.java b/src/java.sql.rowset/share/classes/javax/sql/rowset/RowSetProvider.java index bcee82529ea08e1d00d0297de74db18a7d1d3e01..f69ece6e469d395d4c899d214fad445727010013 100644 --- a/src/java.sql.rowset/share/classes/javax/sql/rowset/RowSetProvider.java +++ b/src/java.sql.rowset/share/classes/javax/sql/rowset/RowSetProvider.java @@ -226,7 +226,7 @@ public class RowSetProvider { * */ @SuppressWarnings("removal") - static private ClassLoader getContextClassLoader() throws SecurityException { + private static ClassLoader getContextClassLoader() throws SecurityException { return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { @@ -252,7 +252,7 @@ public class RowSetProvider { * context class loader followed by the current class loader. * @return The class which was loaded */ - static private Class getFactoryClass(String factoryClassName, ClassLoader cl, + private static Class getFactoryClass(String factoryClassName, ClassLoader cl, boolean doFallback) throws ClassNotFoundException { Class factoryClass = null; @@ -284,7 +284,7 @@ public class RowSetProvider { * Use the ServiceLoader mechanism to load the default RowSetFactory * @return default RowSetFactory Implementation */ - static private RowSetFactory loadViaServiceLoader() throws SQLException { + private static RowSetFactory loadViaServiceLoader() throws SQLException { RowSetFactory theFactory = null; try { trace("***in loadViaServiceLoader():"); @@ -310,7 +310,7 @@ public class RowSetProvider { * or a {@code SecurityException} occurs. */ @SuppressWarnings("removal") - static private String getSystemProperty(final String propName) { + private static String getSystemProperty(final String propName) { String property = null; try { property = AccessController.doPrivileged(new PrivilegedAction() { diff --git a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java index ff64e6ccc8646c453a76f9b16ac06d10b0eccb6b..34474deb5933883549b8ff8b264781ef50a3ee97 100644 --- a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java +++ b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -298,22 +298,21 @@ public class SerialBlob implements Blob, Serializable, Cloneable { } /** - * Writes the given array of bytes to the BLOB value that - * this Blob object represents, starting at position - * pos, and returns the number of bytes written. + * Writes the given array of bytes to the {@code BLOB} value that + * this {@code Blob} object represents, starting at position + * {@code pos}, and returns the number of bytes written. * - * @param pos the position in the SQL BLOB value at which - * to start writing. The first position is 1; - * must not be less than 1 nor greater than - * the length of this SerialBlob object. - * @param bytes the array of bytes to be written to the BLOB - * value that this Blob object represents + * @param pos the position in the SQL {@code BLOB} value at which + * to start writing. The first position is {@code 1}; + * must not be less than {@code 1} nor greater than + * the length+1 of this {@code SerialBlob} object. + * @param bytes the array of bytes to be written to the {@code BLOB} + * value that this {@code Blob} object represents * @return the number of bytes written * @throws SerialException if there is an error accessing the - * BLOB value; or if an invalid position is set; if an - * invalid offset value is set; + * {@code BLOB} value; or if an invalid position is set; * if {@code free} had previously been called on this object - * @throws SQLException if there is an error accessing the BLOB + * @throws SQLException if there is an error accessing the {@code BLOB} * value from the database * @see #getBytes */ @@ -323,33 +322,33 @@ public class SerialBlob implements Blob, Serializable, Cloneable { } /** - * Writes all or part of the given byte array to the - * BLOB value that this Blob object represents + * Writes all or part of the given {@code byte} array to the + * {@code BLOB} value that this {@code Blob} object represents * and returns the number of bytes written. - * Writing starts at position pos in the BLOB - * value; len bytes from the given byte array are written. + * Writing starts at position {@code pos} in the {@code BLOB} + * value; {@code length} bytes from the given byte array are written. * - * @param pos the position in the BLOB object at which - * to start writing. The first position is 1; - * must not be less than 1 nor greater than - * the length of this SerialBlob object. - * @param bytes the array of bytes to be written to the BLOB + * @param pos the position in the {@code BLOB} object at which + * to start writing. The first position is {@code 1}; + * must not be less than {@code 1} nor greater than + * the length+1 of this {@code SerialBlob} object. + * @param bytes the array of bytes to be written to the {@code BLOB} * value - * @param offset the offset in the byte array at which - * to start reading the bytes. The first offset position is - * 0; must not be less than 0 nor greater - * than the length of the byte array + * @param offset the offset into the array {@code byte}s at which + * to start reading the bytes to be set. The first offset position is + * {@code 0}; must not be less than {@code 0} nor greater + * than the length of the array {@code byte}s * @param length the number of bytes to be written to the - * BLOB value from the array of bytes bytes. + * {@code BLOB} value from the array of bytes {@code byte}s * * @return the number of bytes written * @throws SerialException if there is an error accessing the - * BLOB value; if an invalid position is set; if an - * invalid offset value is set; if number of bytes to be written - * is greater than the SerialBlob length; or the combined - * values of the length and offset is greater than the Blob buffer; + * {@code BLOB} value; if an invalid position is set; if an + * invalid offset value is set; or the combined values of the + * {@code length} and {@code offset} is greater than the length of + * {@code byte}s; * if {@code free} had previously been called on this object - * @throws SQLException if there is an error accessing the BLOB + * @throws SQLException if there is an error accessing the {@code BLOB} * value from the database. * @see #getBytes */ @@ -361,26 +360,34 @@ public class SerialBlob implements Blob, Serializable, Cloneable { throw new SerialException("Invalid offset in byte array set"); } - if (pos < 1 || pos > this.length()) { - throw new SerialException("Invalid position in BLOB object set"); + if (length < 0) { + throw new SerialException("Invalid arguments: length cannot be " + + "negative"); } - if ((long)(length) > origLen) { - throw new SerialException("Buffer is not sufficient to hold the value"); + if (pos < 1 || pos > len + 1) { + throw new SerialException("Invalid position in BLOB object set"); } - if ((length + offset) > bytes.length) { + if (length > bytes.length - offset) { throw new SerialException("Invalid OffSet. Cannot have combined offset " + - "and length that is greater that the Blob buffer"); + "and length that is greater than the length of bytes"); + } + + if (pos - 1 + length > Integer.MAX_VALUE) { + throw new SerialException("Invalid length. Cannot have combined pos " + + "and length that is greater than Integer.MAX_VALUE"); } - int i = 0; pos--; // correct to array indexing - while ( i < length || (offset + i +1) < (bytes.length-offset) ) { - this.buf[(int)pos + i] = bytes[offset + i ]; - i++; + if (pos + length > len) { + len = pos + length; + byte[] newbuf = new byte[(int)len]; + System.arraycopy(buf, 0, newbuf, 0, (int)pos); + buf = newbuf; } - return i; + System.arraycopy(bytes, offset, buf, (int)pos, length); + return length; } /** diff --git a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialClob.java b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialClob.java index 48ee5ea878fa8a3f33b90ba054b829baea4244fb..e548ba217f730574f14bf9aab0dbdce532187d9a 100644 --- a/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialClob.java +++ b/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialClob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -361,22 +361,19 @@ public class SerialClob implements Clob, Serializable, Cloneable { } /** - * Writes the given Java String to the CLOB - * value that this SerialClob object represents, at the position - * pos. + * Writes the given Java {@code String} to the {@code CLOB} + * value that this {@code SerialClob} object represents, at the position + * {@code pos}. * - * @param pos the position at which to start writing to the CLOB - * value that this SerialClob object represents; the first - * position is 1; must not be less than 1 nor - * greater than the length of this SerialClob object - * @param str the string to be written to the CLOB - * value that this SerialClob object represents + * @param pos the position at which to start writing to the {@code CLOB} + * value that this {@code SerialClob} object represents; the first + * position is {@code 1}; must not be less than {@code 1} nor + * greater than the length+1 of this {@code SerialClob} object + * @param str the string to be written to the {@code CLOB} + * value that this {@code SerialClob} object represents * @return the number of characters written * @throws SerialException if there is an error accessing the - * CLOB value; if an invalid position is set; if an - * invalid offset value is set; if number of bytes to be written - * is greater than the SerialClob length; or the combined - * values of the length and offset is greater than the Clob buffer; + * {@code CLOB} value; if an invalid position is set; * if the {@code free} method had been previously called on this object */ public int setString(long pos, String str) throws SerialException { @@ -384,58 +381,66 @@ public class SerialClob implements Clob, Serializable, Cloneable { } /** - * Writes len characters of str, starting - * at character offset, to the CLOB value - * that this Clob represents. + * Writes {@code len} characters of {@code str}, starting + * at character {@code offset}, to the {@code CLOB} value + * that this {@code Clob} represents. * - * @param pos the position at which to start writing to the CLOB - * value that this SerialClob object represents; the first - * position is 1; must not be less than 1 nor - * greater than the length of this SerialClob object - * @param str the string to be written to the CLOB - * value that this Clob object represents - * @param offset the offset into str to start reading + * @param pos the position at which to start writing to the {@code CLOB} + * value that this {@code SerialClob} object represents; the first + * position is {@code 1}; must not be less than {@code 1} nor + * greater than the length+1 of this {@code SerialClob} object + * @param str the string to be written to the {@code CLOB} + * value that this {@code Clob} object represents + * @param offset the offset into {@code str} to start reading * the characters to be written * @param length the number of characters to be written * @return the number of characters written * @throws SerialException if there is an error accessing the - * CLOB value; if an invalid position is set; if an - * invalid offset value is set; if number of bytes to be written - * is greater than the SerialClob length; or the combined - * values of the length and offset is greater than the Clob buffer; + * {@code CLOB} value; if an invalid position is set; if an + * invalid offset value is set; or the combined values of the + * {@code length} and {@code offset} is greater than the length of + * {@code str}; * if the {@code free} method had been previously called on this object */ public int setString(long pos, String str, int offset, int length) throws SerialException { isValid(); - String temp = str.substring(offset); - char cPattern[] = temp.toCharArray(); - if (offset < 0 || offset > str.length()) { - throw new SerialException("Invalid offset in byte array set"); + throw new SerialException("Invalid offset in String object set"); } - if (pos < 1 || pos > this.length()) { - throw new SerialException("Invalid position in Clob object set"); + if (length < 0) { + throw new SerialException("Invalid arguments: length cannot be " + + "negative"); } - if ((long)(length) > origLen) { - throw new SerialException("Buffer is not sufficient to hold the value"); + if (pos < 1 || pos > len + 1) { + throw new SerialException("Invalid position in Clob object set"); } - if ((length + offset) > str.length()) { - // need check to ensure length + offset !> bytes.length + if (length > str.length() - offset) { + // need check to ensure length + offset !> str.length throw new SerialException("Invalid OffSet. Cannot have combined offset " + - " and length that is greater that the Blob buffer"); + " and length that is greater than the length of str"); + } + + if (pos - 1 + length > Integer.MAX_VALUE) { + throw new SerialException("Invalid length. Cannot have combined pos " + + "and length that is greater than Integer.MAX_VALUE"); } - int i = 0; pos--; //values in the array are at position one less - while ( i < length || (offset + i +1) < (str.length() - offset ) ) { - this.buf[(int)pos + i ] = cPattern[offset + i ]; - i++; + if (pos + length > len) { + len = pos + length; + char[] newbuf = new char[(int)len]; + System.arraycopy(buf, 0, newbuf, 0, (int)pos); + buf = newbuf; } - return i; + + String temp = str.substring(offset, offset + length); + char cPattern[] = temp.toCharArray(); + System.arraycopy(cPattern, 0, buf, (int)pos, length); + return length; } /** diff --git a/src/java.sql/share/classes/java/sql/DriverManager.java b/src/java.sql/share/classes/java/sql/DriverManager.java index 9116e78efaf3e7f67f91f99e5768e14de360ae95..f7733cfb62e39354314238bdf6a9772c9ea59ddc 100644 --- a/src/java.sql/share/classes/java/sql/DriverManager.java +++ b/src/java.sql/share/classes/java/sql/DriverManager.java @@ -37,6 +37,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Stream; import jdk.internal.reflect.CallerSensitive; +import jdk.internal.reflect.CallerSensitiveAdapter; import jdk.internal.reflect.Reflection; @@ -647,6 +648,7 @@ public class DriverManager { // Worker method called by the public getConnection() methods. + @CallerSensitiveAdapter private static Connection getConnection( String url, java.util.Properties info, Class caller) throws SQLException { /* diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java index 4c51e7b5e8397d771f6eda8ec826a6d415335cbe..a35a4699d82a4aee7da45a9882350a95abdf7fba 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java @@ -84,7 +84,7 @@ public class Init { } @SuppressWarnings("removal") - InputStream is = + InputStream is = //NOPMD AccessController.doPrivileged( (PrivilegedAction) () -> { @@ -351,6 +351,9 @@ public class Init { * @param callingClass The Class object of the calling object */ public static URL getResource(String resourceName, Class callingClass) { + if (resourceName == null) { + throw new NullPointerException(); + } URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null && resourceName.charAt(0) == '/') { //certain classloaders need it without the leading / @@ -404,6 +407,9 @@ public class Init { * @param callingClass The Class object of the calling object */ private static List getResources(String resourceName, Class callingClass) { + if (resourceName == null) { + throw new NullPointerException(); + } List ret = new ArrayList<>(); Enumeration urls = new Enumeration() { public boolean hasMoreElements() { @@ -479,7 +485,7 @@ public class Init { } - if (ret.isEmpty() && resourceName != null && resourceName.charAt(0) != '/') { + if (ret.isEmpty() && resourceName.charAt(0) != '/') { return getResources('/' + resourceName, callingClass); } return ret; diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 90302d478446dc9cd6cdbc19bbfcf39418972b3d..fdaf8643279c8d57aa4684cef02007a0fc8dfb6c 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -309,7 +309,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { Node n = XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); if (n != null) { String hmacLength = XMLUtils.getFullTextChildrenFromNode(n); - if (hmacLength != null && !"".equals(hmacLength)) { + if (hmacLength != null && hmacLength.length() != 0) { this.hmacOutputLength = new HMACOutputLength(Integer.parseInt(hmacLength)); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java index 1ed26fea60bc84ef4a6a6372bd496efb3106a6a2..f0cd610b3209a06fa3aa83eb02844c94e867861f 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java @@ -125,7 +125,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * Output the Attr[]s for the given element. *
      * The code of this method is a copy of - * {@link #outputAttributes(Element, NameSpaceSymbTable, Map)}, + * {@link #outputAttributes(Element, NameSpaceSymbTable, Map, OutputStream)}, * whereas it takes into account that subtree-c14n is -- well -- subtree-based. * So if the element in question isRoot of c14n, it's parent is not in the * node set, as well as all other ancestors. diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java index d3b972c95f853ea3ac48db2e1447ca511ff126ba..ce971a45a98101196cd9112dfc4c041021cc64a2 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java @@ -211,7 +211,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { Node sibling = null; Node parentNode = null; Map cache = new HashMap<>(); - do { + do { //NOPMD switch (currentNode.getNodeType()) { case Node.ENTITY_NODE : @@ -338,7 +338,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { Node parentNode = null; int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT; Map cache = new HashMap<>(); - do { + do { //NOPMD switch (currentNode.getNodeType()) { case Node.ENTITY_NODE : @@ -560,7 +560,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { } parents.clear(); Attr nsprefix = ns.getMappingWithoutRendered(XMLNS); - if (nsprefix != null && "".equals(nsprefix.getValue())) { + if (nsprefix != null && nsprefix.getValue().length() == 0) { ns.addMappingAndRender( XMLNS, "", getNullNode(nsprefix.getOwnerDocument())); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java index 4b2333938f5cc7335735420f6da4d9955d136bbf..66ad12029fc0d29f78edff7254c759e711445dd3 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java @@ -110,7 +110,7 @@ public class CanonicalizerPhysical extends CanonicalizerBase { * Output the Attr[]s for the given element. *
      * The code of this method is a copy of - * {@link #outputAttributes(Element, NameSpaceSymbTable, Map)}, + * {@link #outputAttributes(Element, NameSpaceSymbTable, Map, OutputStream)}, * whereas it takes into account that subtree-c14n is -- well -- subtree-based. * So if the element in question isRoot of c14n, it's parent is not in the * node set, as well as all other ancestors. diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java index 2fc853fe6901806728b4ffdab78203b2abae77c1..f0b1903accdcdba0933aa17efb819007fb4bb1e0 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java @@ -348,7 +348,7 @@ class SymbMap implements Cloneable { List entrySet() { List a = new ArrayList<>(); for (int i = 0;i < entries.length;i++) { - if (entries[i] != null && !"".equals(entries[i].uri)) { + if (entries[i] != null && entries[i].uri.length() != 0) { a.add(entries[i]); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java deleted file mode 100644 index 7d17fe867e1ac1d7380b20feae5e24055cb55085..0000000000000000000000000000000000000000 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.exceptions; - -import java.text.MessageFormat; - -import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.I18n; - -/** - * The mother of all runtime Exceptions in this bundle. It allows exceptions to have - * their messages translated to the different locales. - * - * The {@code xmlsecurity_en.properties} file contains this line: - *
      - * xml.WrongElement = Can't create a {0} from a {1} element
      - * 
      - * - * Usage in the Java source is: - *
      - * {
      - *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
      - *
      - *    throw new XMLSecurityException("xml.WrongElement", exArgs);
      - * }
      - * 
      - * - * Additionally, if another Exception has been caught, we can supply it, too - *
      - * try {
      - *    ...
      - * } catch (Exception oldEx) {
      - *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
      - *
      - *    throw new XMLSecurityException("xml.WrongElement", exArgs, oldEx);
      - * }
      - * 
      - * - * - */ -public class XMLSecurityRuntimeException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Field msgID */ - protected String msgID; - - /** - * Constructor XMLSecurityRuntimeException - * - */ - public XMLSecurityRuntimeException() { - super("Missing message string"); - - this.msgID = null; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param msgID - */ - public XMLSecurityRuntimeException(String msgID) { - super(I18n.getExceptionMessage(msgID)); - - this.msgID = msgID; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param msgID - * @param exArgs - */ - public XMLSecurityRuntimeException(String msgID, Object[] exArgs) { - super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - - this.msgID = msgID; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param originalException - */ - public XMLSecurityRuntimeException(Exception originalException) { - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + originalException.getClass().getName() + " and message " - + originalException.getMessage(), originalException); - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param msgID - * @param originalException - */ - public XMLSecurityRuntimeException(String msgID, Exception originalException) { - super(I18n.getExceptionMessage(msgID, originalException), originalException); - - this.msgID = msgID; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param msgID - * @param exArgs - * @param originalException - */ - public XMLSecurityRuntimeException(String msgID, Object[] exArgs, Exception originalException) { - super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); - - this.msgID = msgID; - } - - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** {@inheritDoc} */ - public String toString() { - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (this.getCause() != null) { - message = message + "\nOriginal Exception was " + this.getCause().toString(); - } - - return message; - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - if (this.getCause() instanceof Exception) { - return (Exception)this.getCause(); - } - return null; - } - -} diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java index 7aa9a30128ab7e08850e9faf60bbc2fe0239c9a4..7445013e9cbcc2d7080c123a63258dee02f7a14d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java @@ -170,8 +170,8 @@ public class KeyResolver { ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { JavaUtils.checkRegisterPermission(); - KeyResolverSpi keyResolverSpi = - (KeyResolverSpi) JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class)); + KeyResolverSpi keyResolverSpi = (KeyResolverSpi) + JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class)); register(keyResolverSpi, false); } @@ -193,8 +193,8 @@ public class KeyResolver { KeyResolverSpi keyResolverSpi = null; Exception ex = null; try { - keyResolverSpi = (KeyResolverSpi) JavaUtils.newInstanceWithEmptyConstructor( - ClassLoaderUtils.loadClass(className, KeyResolver.class)); + keyResolverSpi = (KeyResolverSpi) + JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class)); register(keyResolverSpi, true); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) { ex = e; @@ -253,8 +253,8 @@ public class KeyResolver { JavaUtils.checkRegisterPermission(); List keyResolverList = new ArrayList<>(classNames.size()); for (String className : classNames) { - KeyResolverSpi keyResolverSpi = (KeyResolverSpi)JavaUtils - .newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class)); + KeyResolverSpi keyResolverSpi = (KeyResolverSpi) + JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class)); keyResolverList.add(keyResolverSpi); } resolverList.addAll(keyResolverList); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java index fb32875c1b15fcc607ee0180a59d8dddd7425965..101fd2d12a554529d993329d75ffbb9ee41488bb 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -162,6 +162,7 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { validateReference(referentElement, secureValidation); KeyInfo referent = new KeyInfo(referentElement, baseURI); + referent.setSecureValidation(secureValidation); referent.addStorageResolver(storage); return referent; } @@ -181,7 +182,7 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { } KeyInfo referent = new KeyInfo(referentElement, ""); - if (referent.containsKeyInfoReference()) { + if (referent.containsKeyInfoReference() || referent.containsRetrievalMethod()) { if (secureValidation) { throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure"); } else { diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index 603d49e0ad5a4229ec3414f234ce00e238c03bfe..bbd26a399ca5cda99bf767690201f0bfccc2b8ff 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -96,8 +96,6 @@ - ith SignatureProperty. Valid {@code i} - * values are 0 to {@code {link@ getSize}-1}. + * values are 0 to {@code {@link getSize}-1}. * * @param i Index of the requested {@link SignatureProperty} * @return the ith SignatureProperty diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java index a6b1c6cd1704b7b561646d18f0eef7af2630d6fe..165bc98721fb5059331b67a11cb283ccb269fdcf 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java @@ -36,7 +36,6 @@ import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; import com.sun.org.apache.xml.internal.security.parser.XMLParserException; import com.sun.org.apache.xml.internal.security.utils.JavaUtils; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; @@ -141,7 +140,7 @@ public class XMLSignatureInput { /** * Construct a XMLSignatureInput from a subtree rooted by rootNode. This - * method included the node and all his descendants in the output. + * method included the node and all its descendants in the output. * * @param rootNode */ @@ -528,7 +527,7 @@ public class XMLSignatureInput { if (inputOctetStreamProxy == null) { return null; } - try { + try { //NOPMD bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy); } finally { inputOctetStreamProxy.close(); @@ -539,15 +538,9 @@ public class XMLSignatureInput { /** * @param filter */ - public void addNodeFilter(NodeFilter filter) { + public void addNodeFilter(NodeFilter filter) throws XMLParserException, IOException { if (isOctetStream()) { - try { - convertToNodes(); - } catch (Exception e) { - throw new XMLSecurityRuntimeException( - "signature.XMLSignatureInput.nodesetReference", e - ); - } + convertToNodes(); } nodeFilters.add(filter); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java index e0f9b4faa1e3535c088b37363b567abb8ba44d42..6337bc2c201dbe09b54d60a74caddfa9baa693f1 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java @@ -60,7 +60,7 @@ public class TransformC14N extends TransformSpi { Canonicalizer20010315 c14n = getCanonicalizer(); - if (os == null) { + if (os == null && (input.isOctetStream() || input.isElement() || input.isNodeSet())) { try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) { c14n.engineCanonicalize(input, writer, secureValidation); writer.flush(); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java index 5393fa99ac3024f2d67b50b4ce594be3a5802d83..eca648267e1e69ccfaba8c657932e2bfbd3c4e0f 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java @@ -82,7 +82,7 @@ public class TransformC14NExclusive extends TransformSpi { Canonicalizer20010315Excl c14n = getCanonicalizer(); - if (os == null) { + if (os == null && (input.isOctetStream() || input.isElement() || input.isNodeSet())) { try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) { c14n.engineCanonicalize(input, inclusiveNamespaces, writer, secureValidation); writer.flush(); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java index 539590cc84c742d3405598f128a1bd264bfb4efb..030d7063cc30073e8e67397397c305a48386329e 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java @@ -22,8 +22,10 @@ */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.IOException; import java.io.OutputStream; +import com.sun.org.apache.xml.internal.security.parser.XMLParserException; import com.sun.org.apache.xml.internal.security.signature.NodeFilter; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; @@ -71,7 +73,11 @@ public class TransformEnvelopedSignature extends TransformSpi { Node signatureElement = searchSignatureElement(transformElement); input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + try { + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + } catch (XMLParserException | IOException ex) { + throw new TransformationException(ex); + } return input; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java index cdde27c6834c1840286868733249185e21de0dfb..ca844c0068256d628eeeb56000e90d216a24156d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java @@ -22,11 +22,12 @@ */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.TransformerException; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; +import com.sun.org.apache.xml.internal.security.parser.XMLParserException; import com.sun.org.apache.xml.internal.security.signature.NodeFilter; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; @@ -51,6 +52,9 @@ import org.w3c.dom.Node; */ public class TransformXPath extends TransformSpi { + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(TransformXPath.class); + /** * {@inheritDoc} */ @@ -102,7 +106,7 @@ public class TransformXPath extends TransformSpi { input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance)); input.setNodeSet(true); return input; - } catch (DOMException ex) { + } catch (XMLParserException | IOException | DOMException ex) { throw new TransformationException(ex); } } @@ -144,11 +148,8 @@ public class TransformXPath extends TransformSpi { } return 0; } catch (TransformerException e) { - Object[] eArgs = {currentNode}; - throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e); - } catch (Exception e) { - Object[] eArgs = {currentNode, currentNode.getNodeType()}; - throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e); + LOG.debug("Error evaluating XPath expression", e); + return 0; } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java index d9d0e761468f4f67f2b113bd8d82b7e3c8e85446..0534fff3844b90c882ae371df5d20b7a3058fd69 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java @@ -43,6 +43,7 @@ import org.w3c.dom.Text; * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ @Deprecated +@SuppressWarnings("PMD") public final class Base64 { /** Field BASE64DEFAULTLENGTH */ diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java index 116e868834228a1980c8e759c81d520eb767300a..6a2f5d5af260e9cfe3d637a422eb01a50c021707 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java @@ -127,11 +127,11 @@ public class DOMNamespaceContext implements NamespaceContext { return DEFAULT_NS_PREFIX; } } - if (namespaceURI == null) { + if (namespaceURI == null && context != null) { return context.lookupNamespaceURI(null) != null ? null : DEFAULT_NS_PREFIX; - } else if (namespaceURI.equals(XML_NS_URI)) { + } else if (XML_NS_URI.equals(namespaceURI)) { return XML_NS_PREFIX; - } else if (namespaceURI.equals(XMLNS_ATTRIBUTE_NS_URI)) { + } else if (XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) { return XMLNS_ATTRIBUTE; } return null; diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java index 4574e35f76a5d9a193055765c405edadc5cb33d3..552d1330a3f22aa5d87c27b7108354fe3bd7e67b 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java @@ -190,20 +190,21 @@ public class RFC2253Parser { if (value.startsWith("\"")) { StringBuilder sb = new StringBuilder(); - StringReader sr = new StringReader(value.substring(1, value.length() - 1)); - int i = 0; - char c; + try (StringReader sr = new StringReader(value.substring(1, value.length() - 1))) { + int i = 0; + char c; - while ((i = sr.read()) > -1) { - c = (char) i; + while ((i = sr.read()) > -1) { + c = (char) i; - //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 - if (c == ',' || c == '=' || c == '+' || c == '<' - || c == '>' || c == '#' || c == ';') { - sb.append('\\'); - } + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if (c == ',' || c == '=' || c == '+' || c == '<' + || c == '>' || c == '#' || c == ';') { + sb.append('\\'); + } - sb.append(c); + sb.append(c); + } } value = trim(sb.toString()); @@ -263,37 +264,38 @@ public class RFC2253Parser { */ static String changeLess32toRFC(String string) throws IOException { StringBuilder sb = new StringBuilder(); - StringReader sr = new StringReader(string); int i = 0; char c; - while ((i = sr.read()) > -1) { - c = (char) i; - - if (c == '\\') { - sb.append(c); - - char c1 = (char) sr.read(); - char c2 = (char) sr.read(); - - //65 (A) 97 (a) - if ((c1 >= 48 && c1 <= 57 || c1 >= 65 && c1 <= 70 || c1 >= 97 && c1 <= 102) - && (c2 >= 48 && c2 <= 57 - || c2 >= 65 && c2 <= 70 - || c2 >= 97 && c2 <= 102)) { - try { - char ch = (char) Byte.parseByte("" + c1 + c2, 16); + try (StringReader sr = new StringReader(string)) { + while ((i = sr.read()) > -1) { + c = (char) i; - sb.append(ch); - } catch (NumberFormatException ex) { - throw new IOException(ex); + if (c == '\\') { + sb.append(c); + + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); + + //65 (A) 97 (a) + if ((c1 >= 48 && c1 <= 57 || c1 >= 65 && c1 <= 70 || c1 >= 97 && c1 <= 102) + && (c2 >= 48 && c2 <= 57 + || c2 >= 65 && c2 <= 70 + || c2 >= 97 && c2 <= 102)) { + try { + char ch = (char) Byte.parseByte("" + c1 + c2, 16); + + sb.append(ch); + } catch (NumberFormatException ex) { + throw new IOException(ex); + } + } else { + sb.append(c1); + sb.append(c2); } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); } } @@ -309,15 +311,16 @@ public class RFC2253Parser { */ static String changeLess32toXML(String string) throws IOException { StringBuilder sb = new StringBuilder(); - StringReader sr = new StringReader(string); int i = 0; - while ((i = sr.read()) > -1) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); + try (StringReader sr = new StringReader(string)) { + while ((i = sr.read()) > -1) { + if (i < 32) { + sb.append('\\'); + sb.append(Integer.toHexString(i)); + } else { + sb.append((char) i); + } } } @@ -333,28 +336,29 @@ public class RFC2253Parser { */ static String changeWStoXML(String string) throws IOException { StringBuilder sb = new StringBuilder(); - StringReader sr = new StringReader(string); int i = 0; char c; - while ((i = sr.read()) > -1) { - c = (char) i; + try (StringReader sr = new StringReader(string)) { + while ((i = sr.read()) > -1) { + c = (char) i; - if (c == '\\') { - char c1 = (char) sr.read(); + if (c == '\\') { + char c1 = (char) sr.read(); - if (c1 == ' ') { - sb.append('\\'); + if (c1 == ' ') { + sb.append('\\'); - String s = "20"; + String s = "20"; - sb.append(s); + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } } else { - sb.append('\\'); - sb.append(c1); + sb.append(c); } - } else { - sb.append(c); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java index 5eaeda3b5f07d0b0dcebe5706c6615cdd6df60fd..446d640194e0969a147b13d2930e20a66eed8e69 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java @@ -583,7 +583,7 @@ public final class XMLUtils { Node parent = null; Node sibling = null; final String namespaceNs = Constants.NamespaceSpecNS; - do { + do { //NOPMD switch (node.getNodeType()) { case Node.ELEMENT_NODE : Element element = (Element) node; diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java index 1b3f2be87cb216790434c2a09075177b195ec181..42271aa0128951bab1955264353e1a3ed0e0c146 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java @@ -122,8 +122,8 @@ public class ResourceResolver { List resourceResolversToAdd = new ArrayList<>(classNames.size()); for (String className : classNames) { - ResourceResolverSpi resourceResolverSpi = (ResourceResolverSpi)JavaUtils - .newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, ResourceResolver.class)); + ResourceResolverSpi resourceResolverSpi = (ResourceResolverSpi) + JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, ResourceResolver.class)); resourceResolversToAdd.add(resourceResolverSpi); } resolverList.addAll(resourceResolversToAdd); @@ -159,15 +159,6 @@ public class ResourceResolver { LOG.debug("check resolvability by class {}", resolver.getClass().getName()); if (resolver.engineCanResolveURI(context)) { - // Check to see whether the Resolver is allowed - if (context.secureValidation - && (resolver instanceof ResolverLocalFilesystem - || resolver instanceof ResolverDirectHTTP)) { - Object[] exArgs = { resolver.getClass().getName() }; - throw new ResourceResolverException( - "signature.Reference.ForbiddenResolver", exArgs, context.uriToResolve, context.baseUri - ); - } return resolver.engineResolveURI(context); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java index 47d0dbb87a8e4438723c41b228828c3d47642ccf..ef56d435dde2a1a70060ce047651b756fc9e003d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java @@ -54,5 +54,4 @@ public class ResourceResolverContext { public Map getProperties() { return properties; } - } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index 955a42a01cff16c674d151f700d926197d052a7c..c1f9e199fb2c8764b625143e51c36ce4d0c0e165 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -219,7 +219,8 @@ public class ResolverDirectHTTP extends ResourceResolverSpi { LOG.debug("I was asked whether I can resolve {}", context.uriToResolve); if (context.uriToResolve.startsWith("http:") || - context.baseUri != null && context.baseUri.startsWith("http:")) { + context.uriToResolve.startsWith("https:") || + context.baseUri != null && (context.baseUri.startsWith("http:") || context.baseUri.startsWith("https:"))) { LOG.debug("I state that I can resolve {}", context.uriToResolve); return true; } @@ -231,7 +232,7 @@ public class ResolverDirectHTTP extends ResourceResolverSpi { private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { URI newUri = null; - if (baseURI == null || "".equals(baseURI)) { + if (baseURI == null || baseURI.length() == 0) { newUri = new URI(uri); } else { newUri = new URI(baseURI).resolve(uri); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index 7e73ace1b2acdb496b7f62e7b58b011ff11a56d5..9d7e00bdbd6bd5fe6002676933fe0b9fc66cf687 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -38,8 +38,6 @@ import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverS */ public class ResolverLocalFilesystem extends ResourceResolverSpi { - private static final int FILE_URI_LENGTH = "file:/".length(); - private static final com.sun.org.slf4j.internal.Logger LOG = com.sun.org.slf4j.internal.LoggerFactory.getLogger(ResolverLocalFilesystem.class); @@ -53,9 +51,7 @@ public class ResolverLocalFilesystem extends ResourceResolverSpi { // calculate new URI URI uriNew = getNewURI(context.uriToResolve, context.baseUri); - String fileName = - ResolverLocalFilesystem.translateUriToFilename(uriNew.toString()); - InputStream inputStream = Files.newInputStream(Paths.get(fileName)); + InputStream inputStream = Files.newInputStream(Paths.get(uriNew)); //NOPMD XMLSignatureInput result = new XMLSignatureInput(inputStream); result.setSecureValidation(context.secureValidation); @@ -67,41 +63,6 @@ public class ResolverLocalFilesystem extends ResourceResolverSpi { } } - /** - * Method translateUriToFilename - * - * @param uri - * @return the string of the filename - */ - private static String translateUriToFilename(String uri) { - - String subStr = uri.substring(FILE_URI_LENGTH); - - if (subStr.indexOf("%20") > -1) { - int offset = 0; - int index = 0; - StringBuilder temp = new StringBuilder(subStr.length()); - do { - index = subStr.indexOf("%20",offset); - if (index == -1) { - temp.append(subStr.substring(offset)); - } else { - temp.append(subStr.substring(offset, index)); - temp.append(' '); - offset = index + 3; - } - } while(index != -1); - subStr = temp.toString(); - } - - if (subStr.charAt(1) == ':') { - // we're running M$ Windows, so this works fine - return subStr; - } - // we're running some UNIX, so we have to prepend a slash - return "/" + subStr; - } - /** * {@inheritDoc} */ @@ -111,7 +72,7 @@ public class ResolverLocalFilesystem extends ResourceResolverSpi { } if (context.uriToResolve.isEmpty() || context.uriToResolve.charAt(0) == '#' || - context.uriToResolve.startsWith("http:")) { + context.uriToResolve.startsWith("http:") || context.uriToResolve.startsWith("https:")) { return false; } @@ -133,7 +94,7 @@ public class ResolverLocalFilesystem extends ResourceResolverSpi { private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { URI newUri = null; - if (baseURI == null || "".equals(baseURI)) { + if (baseURI == null || baseURI.length() == 0) { newUri = new URI(uri); } else { newUri = new URI(baseURI).resolve(uri); diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java index bb279ecc728817bf6587f942f7029f6960965f71..7655866ad7402618fc11013c570fb79a3707e392 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java @@ -239,9 +239,6 @@ public abstract class ApacheCanonicalizer extends TransformService { try { in = apacheTransform.performTransform(in, os, secVal); - if (!in.isNodeSet() && !in.isElement()) { - return null; - } if (in.isOctetStream()) { return new ApacheOctetStreamData(in); } else { diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java index 0b63c5eba1615eaafde0fdf1a6ef79ac9703517a..d278808ea0572832352e188b6cf1417fc0c9583f 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java @@ -447,7 +447,7 @@ public final class DOMReference extends DOMStructure } Data data = dereferencedData; XMLSignatureInput xi = null; - try (OutputStream os = new UnsyncBufferedOutputStream(dos)) { + try (OutputStream os = new UnsyncBufferedOutputStream(dos)) { //NOPMD for (int i = 0, size = transforms.size(); i < size; i++) { DOMTransform transform = (DOMTransform)transforms.get(i); if (i < size - 1) { diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java index a18b76e81f65af2134d1c31a40f756062ab99add..fd6a89229c49dddea5d40c1aa013aa7e47a4d1b2 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java @@ -116,7 +116,7 @@ public class DOMTransform extends DOMStructure implements Transform { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element transformElem = null; - if (parent.getLocalName().equals("Transforms")) { + if ("Transforms".equals(parent.getLocalName())) { transformElem = DOMUtils.createElement(ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix); diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java index 6b728e236cb91ed12d3e3f14ace09d2b2973bc3e..e72642bbff35570d09bb229e60e75dd86e20a886 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java @@ -21,7 +21,7 @@ * under the License. */ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. */ package org.jcp.xml.dsig.internal.dom; @@ -101,7 +101,9 @@ public final class DOMURIDereferencer implements URIDereferencer { if (id.startsWith("xpointer(id(")) { int i1 = id.indexOf('\''); int i2 = id.indexOf('\'', i1+1); - id = id.substring(i1+1, i2); + if (i1 >= 0 && i2 >= 0) { + id = id.substring(i1 + 1, i2); + } } // check if element is registered by Id @@ -138,7 +140,7 @@ public final class DOMURIDereferencer implements URIDereferencer { } try { - ResourceResolverContext resContext = new ResourceResolverContext(uriAttr, baseURI, false); + ResourceResolverContext resContext = new ResourceResolverContext(uriAttr, baseURI, secVal); XMLSignatureInput in = ResourceResolver.resolve(resContext); if (in.isOctetStream()) { return new ApacheOctetStreamData(in); diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Policy.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Policy.java index f32cf39fd6212cdcb869339b409b955c6af2ad3a..fffca6b38f5262286d7aaedab42c26be1fe7c32a 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Policy.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Policy.java @@ -43,14 +43,13 @@ import java.util.Set; */ public final class Policy { - // all restrictions are initialized to be unconstrained - private static Set disallowedAlgs = new HashSet<>(); - private static int maxTrans = Integer.MAX_VALUE; - private static int maxRefs = Integer.MAX_VALUE; - private static Set disallowedRefUriSchemes = new HashSet<>(); - private static Map minKeyMap = new HashMap<>(); - private static boolean noDuplicateIds = false; - private static boolean noRMLoops = false; + private static Set disallowedAlgs; + private static int maxTrans; + private static int maxRefs; + private static Set disallowedRefUriSchemes; + private static Map minKeyMap; + private static boolean noDuplicateIds; + private static boolean noRMLoops; static { try { @@ -64,6 +63,16 @@ public final class Policy { private Policy() {} private static void initialize() { + // First initialized to be unconstrained and then parse the + // security property "jdk.xml.dsig.secureValidationPolicy" + disallowedAlgs = new HashSet<>(); + maxTrans = Integer.MAX_VALUE; + maxRefs = Integer.MAX_VALUE; + disallowedRefUriSchemes = new HashSet<>(); + minKeyMap = new HashMap<>(); + noDuplicateIds = false; + noRMLoops = false; + @SuppressWarnings("removal") String prop = AccessController.doPrivileged((PrivilegedAction) () -> diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java index 0edb5dd5aff7019b895101a1c889723561a3f058..bcf28d0afe209c934be92db1093b963c227bdb8c 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java @@ -21,7 +21,7 @@ * under the License. */ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. */ package org.jcp.xml.dsig.internal.dom; @@ -94,7 +94,9 @@ public final class Utils { if (id.startsWith("xpointer(id(")) { int i1 = id.indexOf('\''); int i2 = id.indexOf('\'', i1+1); - id = id.substring(i1+1, i2); + if (i1 >= 0 && i2 >= 0) { + id = id.substring(i1 + 1, i2); + } } return id; } @@ -114,7 +116,7 @@ public final class Utils { } private static boolean getBoolean(XMLCryptoContext xc, String name) { - Boolean value = (Boolean)xc.getProperty(name); + Boolean value = (Boolean) xc.getProperty(name); return value != null && value; } } diff --git a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java index f26b6d9940b0e45b898d96ea9c2abbaf69797e4a..65bb25f058ff261393bbf191432ec610a482aeca 100644 --- a/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java +++ b/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java @@ -134,7 +134,7 @@ public final class XMLDSigRI extends Provider { @SuppressWarnings("removal") public XMLDSigRI() { // This is the JDK XMLDSig provider, synced from - // Apache Santuario XML Security for Java, version 2.2.1 + // Apache Santuario XML Security for Java, version 2.3.0 super("XMLDSig", VER, INFO); final Provider p = this; diff --git a/src/java.xml.crypto/share/legal/santuario.md b/src/java.xml.crypto/share/legal/santuario.md index eba3a79e3e9f909de31670820917548d691e9f57..fa87128126d19e089465db75c016bbde4e236e22 100644 --- a/src/java.xml.crypto/share/legal/santuario.md +++ b/src/java.xml.crypto/share/legal/santuario.md @@ -1,4 +1,4 @@ -## Apache Santuario v2.2.1 +## Apache Santuario v2.3.0 ### Apache Santuario Notice
      diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
      index 99d3681c0e7bc26ad43515ecd6fd8a4538b6fe1d..a76dcaf7cdb70b97b0bd28efeb02354d519dc83b 100644
      --- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
      +++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
      @@ -58,7 +58,7 @@ import org.xml.sax.XMLReader;
        * @author G. Todd Miller
        * @author Morten Jorgensen
        * @author John Howard (johnh@schemasoft.com)
      - * @LastModified: May 2021
      + * @LastModified: Nov 2021
        */
       public final class XSLTC {
       
      @@ -460,8 +460,11 @@ public final class XSLTC {
                       if (name != null) {
                           setClassName(name);
                       }
      -                else if (systemId != null && !systemId.equals("")) {
      -                    setClassName(Util.baseName(systemId));
      +                else if (systemId != null && !systemId.isEmpty()) {
      +                    String clsName = Util.baseName(systemId);
      +                    if (clsName != null && !clsName.isEmpty()) {
      +                        setClassName(clsName);
      +                    }
                       }
       
                       // Ensure we have a non-empty class name at this point
      diff --git a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java
      index f5ad625ec17b54f07c968c454091c485df93d6cd..f41615fe6ab1276f7d7d0e38df426413f457cece 100644
      --- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java
      +++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java
      @@ -36,7 +36,7 @@ import jdk.xml.internal.JdkXmlFeatures;
        *
        * @author  Ramesh Mandava
        *
      - * @LastModified: May 2021
      + * @LastModified: Nov 2021
        */
       public  class XPathFactoryImpl extends XPathFactory {
       
      @@ -310,4 +310,38 @@ public  class XPathFactoryImpl extends XPathFactory {
       
                       xPathVariableResolver = resolver;
               }
      +
      +    @Override
      +    public void setProperty(String name, String value) {
      +        // property name cannot be null
      +        if (name == null) {
      +            String fmsg = XSLMessages.createXPATHMessage(
      +                    XPATHErrorResources.ER_PROPERTY_NAME_NULL,
      +                    new Object[] {CLASS_NAME,  value} );
      +            throw new NullPointerException(fmsg);
      +         }
      +
      +        // property name not recognized
      +        String fmsg = XSLMessages.createXPATHMessage(
      +                XPATHErrorResources.ER_PROPERTY_UNKNOWN,
      +                new Object[] {name, CLASS_NAME, value} );
      +        throw new IllegalArgumentException(fmsg);
      +    }
      +
      +    @Override
      +    public String getProperty(String name) {
      +        // property name cannot be null
      +        if (name == null) {
      +            String fmsg = XSLMessages.createXPATHMessage(
      +                    XPATHErrorResources.ER_GETTING_NULL_PROPERTY,
      +                    new Object[] {CLASS_NAME} );
      +            throw new NullPointerException(fmsg);
      +        }
      +
      +        // unknown property
      +        String fmsg = XSLMessages.createXPATHMessage(
      +                XPATHErrorResources.ER_GETTING_UNKNOWN_PROPERTY,
      +                new Object[] {name, CLASS_NAME} );
      +        throw new IllegalArgumentException(fmsg);
      +    }
       }
      diff --git a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java
      index 54e4fe7b64661c70b6fb9c55fb0a1c0511f16abc..2e5f86ee30e8b5fa7d53cfb143d83152ecb46736 100644
      --- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java
      +++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java
      @@ -1,5 +1,5 @@
       /*
      - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
      + * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
        */
       /*
        * Licensed to the Apache Software Foundation (ASF) under one or more
      @@ -31,7 +31,7 @@ import java.util.ListResourceBundle;
         * Also you need to  update the count of messages(MAX_CODE)or
        * the count of warnings(MAX_WARNING) [ Information purpose only]
        * @xsl.usage advanced
      - * @LastModified: May 2019
      + * @LastModified: Nov 2021
        */
       public class XPATHErrorResources extends ListResourceBundle
       {
      @@ -322,6 +322,10 @@ public static final String ER_IGNORABLE_WHITESPACE_NOT_HANDLED =
         public static final String ER_SECUREPROCESSING_FEATURE = "ER_SECUREPROCESSING_FEATURE";
         public static final String ER_NULL_XPATH_FUNCTION_RESOLVER = "ER_NULL_XPATH_FUNCTION_RESOLVER";
         public static final String ER_NULL_XPATH_VARIABLE_RESOLVER = "ER_NULL_XPATH_VARIABLE_RESOLVER";
      +  public static final String ER_PROPERTY_NAME_NULL = "ER_PROPERTY_NAME_NULL";
      +  public static final String ER_PROPERTY_UNKNOWN = "ER_PROPERTY_UNKNOWN";
      +  public static final String ER_GETTING_NULL_PROPERTY = "ER_GETTING_NULL_PROPERTY";
      +  public static final String ER_GETTING_UNKNOWN_PROPERTY = "ER_GETTING_UNKNOWN_PROPERTY";
         //END: Keys needed for exception messages of  JAXP 1.3 XPath API implementation
       
         public static final String WG_LOCALE_NAME_NOT_HANDLED =
      @@ -836,6 +840,26 @@ public static final String ER_IGNORABLE_WHITESPACE_NOT_HANDLED =
         { ER_NULL_XPATH_VARIABLE_RESOLVER,
              "Attempting to set a null XPathVariableResolver:{0}#setXPathVariableResolver(null)"},
       
      +  /** Field ER_PROPERTY_NAME_NULL                       */
      +
      +  { ER_PROPERTY_NAME_NULL,
      +       "Trying to set a property with a null name: {0}#setProperty( null, {1})"},
      +
      +  /** Field ER_PROPERTY_UNKNOWN                       */
      +
      +  { ER_PROPERTY_UNKNOWN,
      +       "Trying to set the unknown property \"{0}\":{1}#setProperty({0},{2})"},
      +
      +  /** Field ER_GETTING_NULL_PROPERTY                       */
      +
      +  { ER_GETTING_NULL_PROPERTY,
      +       "Trying to get a property with a null name: {0}#getProperty(null)"},
      +
      +  /** Field ER_GETTING_NULL_PROPERTY                       */
      +
      +  { ER_GETTING_UNKNOWN_PROPERTY,
      +       "Trying to get the unknown property \"{0}\":{1}#getProperty({0})"},
      +
         //END:  Definitions of error keys used  in exception messages of  JAXP 1.3 XPath API implementation
       
         // Warnings...
      diff --git a/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java b/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java
      index 3e6c7d1d554d1855933ce905957a2a270272dcc7..90004e3169184739185765a3d2c9dbc6a15c70eb 100644
      --- a/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java
      +++ b/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java
      @@ -275,8 +275,9 @@ public abstract class XPathFactory {
           public abstract boolean isObjectModelSupported(String objectModel);
       
           /**
      -     * 

      Set a feature for this {@code XPathFactory} and - * XPaths created by this factory.

      + * Sets a feature for this {@code XPathFactory}. The feature applies to + * {@code XPath} objects that the {@code XPathFactory} creates. It has no + * impact on {@code XPath} objects that are already created. * *

      * Feature names are fully qualified {@link java.net.URI}s. @@ -369,4 +370,60 @@ public abstract class XPathFactory { * @return New instance of an XPath. */ public abstract XPath newXPath(); + + /** + * Sets a property for this {@code XPathFactory}. The property applies to + * {@code XPath} objects that the {@code XPathFactory} creates. It has no + * impact on {@code XPath} objects that are already created. + *

      + * A property can either be defined in this {@code XPathFactory}, or by the + * underlying implementation. + * + * @implSpec + * The default implementation throws + * {@link java.lang.UnsupportedOperationException}. + * + * @param name the property name + * @param value the value for the property + * + * @throws IllegalArgumentException if the property name is not recognized, + * or the value can not be assigned + * @throws UnsupportedOperationException if the implementation does not + * support the method + * @throws NullPointerException if the {@code name} is {@code null} + * + * @since 18 + */ + public void setProperty(String name, String value) { + + if (name == null) { + throw new NullPointerException("the name parameter is null"); + } + throw new UnsupportedOperationException("not implemented"); + } + + /** + * Returns the value of the specified property. + * + * @implSpec + * The default implementation throws + * {@link java.lang.UnsupportedOperationException}. + * + * @param name the property name + * @return the value of the property. + * + * @throws IllegalArgumentException if the property name is not recognized + * @throws UnsupportedOperationException if the implementation does not + * support the method + * @throws NullPointerException if the {@code name} is {@code null} + * + * @since 18 + */ + public String getProperty(String name) { + + if (name == null) { + throw new NullPointerException("the name parameter is null"); + } + throw new UnsupportedOperationException("not implemented"); + } } diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java index 2f6cdbbb2d30572c047670d4cf71b2a58f6c9861..b1b93d795e4a5ae1b5c837446a5e1c6a07572d50 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AWTEventMonitor.java @@ -50,22 +50,22 @@ public class AWTEventMonitor { */ public AWTEventMonitor() {} - static private Component componentWithFocus = null; + private static Component componentWithFocus = null; // Low-level listeners - static private ComponentListener componentListener = null; - static private ContainerListener containerListener = null; - static private FocusListener focusListener = null; - static private KeyListener keyListener = null; - static private MouseListener mouseListener = null; - static private MouseMotionListener mouseMotionListener = null; - static private WindowListener windowListener = null; + private static ComponentListener componentListener = null; + private static ContainerListener containerListener = null; + private static FocusListener focusListener = null; + private static KeyListener keyListener = null; + private static MouseListener mouseListener = null; + private static MouseMotionListener mouseMotionListener = null; + private static WindowListener windowListener = null; // Semantic listeners - static private ActionListener actionListener = null; - static private AdjustmentListener adjustmentListener = null; - static private ItemListener itemListener = null; - static private TextListener textListener = null; + private static ActionListener actionListener = null; + private static AdjustmentListener adjustmentListener = null; + private static ItemListener itemListener = null; + private static TextListener textListener = null; /** * The actual listener that is installed on the component instances. @@ -73,7 +73,7 @@ public class AWTEventMonitor { * occurs. By doing things this way, the actual number of listeners * installed on a component instance is drastically reduced. */ - static private final AWTEventsListener awtListener = new AWTEventsListener(); + private static final AWTEventsListener awtListener = new AWTEventsListener(); /** * Returns the component that currently has keyboard focus. The return @@ -81,14 +81,14 @@ public class AWTEventMonitor { * * @return the component that has keyboard focus */ - static public Component getComponentWithFocus() { + public static Component getComponentWithFocus() { return componentWithFocus; } /* * Check permissions */ - static private void checkInstallPermission() { + private static void checkInstallPermission() { @SuppressWarnings("removal") SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -106,7 +106,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeComponentListener */ - static public void addComponentListener(ComponentListener l) { + public static void addComponentListener(ComponentListener l) { if (componentListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.COMPONENT); @@ -121,7 +121,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addComponentListener */ - static public void removeComponentListener(ComponentListener l) { + public static void removeComponentListener(ComponentListener l) { componentListener = AWTEventMulticaster.remove(componentListener, l); if (componentListener == null) { awtListener.removeListeners(EventID.COMPONENT); @@ -138,7 +138,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeContainerListener */ - static public void addContainerListener(ContainerListener l) { + public static void addContainerListener(ContainerListener l) { containerListener = AWTEventMulticaster.add(containerListener, l); } @@ -149,7 +149,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addContainerListener */ - static public void removeContainerListener(ContainerListener l) { + public static void removeContainerListener(ContainerListener l) { containerListener = AWTEventMulticaster.remove(containerListener, l); } @@ -163,7 +163,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeFocusListener */ - static public void addFocusListener(FocusListener l) { + public static void addFocusListener(FocusListener l) { focusListener = AWTEventMulticaster.add(focusListener, l); } @@ -174,7 +174,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addFocusListener */ - static public void removeFocusListener(FocusListener l) { + public static void removeFocusListener(FocusListener l) { focusListener = AWTEventMulticaster.remove(focusListener, l); } @@ -188,7 +188,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeKeyListener */ - static public void addKeyListener(KeyListener l) { + public static void addKeyListener(KeyListener l) { if (keyListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.KEY); @@ -203,7 +203,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addKeyListener */ - static public void removeKeyListener(KeyListener l) { + public static void removeKeyListener(KeyListener l) { keyListener = AWTEventMulticaster.remove(keyListener, l); if (keyListener == null) { awtListener.removeListeners(EventID.KEY); @@ -220,7 +220,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeMouseListener */ - static public void addMouseListener(MouseListener l) { + public static void addMouseListener(MouseListener l) { if (mouseListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.MOUSE); @@ -235,7 +235,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addMouseListener */ - static public void removeMouseListener(MouseListener l) { + public static void removeMouseListener(MouseListener l) { mouseListener = AWTEventMulticaster.remove(mouseListener, l); if (mouseListener == null) { awtListener.removeListeners(EventID.MOUSE); @@ -252,7 +252,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeMouseMotionListener */ - static public void addMouseMotionListener(MouseMotionListener l) { + public static void addMouseMotionListener(MouseMotionListener l) { if (mouseMotionListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.MOTION); @@ -267,7 +267,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addMouseMotionListener */ - static public void removeMouseMotionListener(MouseMotionListener l) { + public static void removeMouseMotionListener(MouseMotionListener l) { mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l); if (mouseMotionListener == null) { awtListener.removeListeners(EventID.MOTION); @@ -284,7 +284,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeWindowListener */ - static public void addWindowListener(WindowListener l) { + public static void addWindowListener(WindowListener l) { if (windowListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.WINDOW); @@ -299,7 +299,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addWindowListener */ - static public void removeWindowListener(WindowListener l) { + public static void removeWindowListener(WindowListener l) { windowListener = AWTEventMulticaster.remove(windowListener, l); if (windowListener == null) { awtListener.removeListeners(EventID.WINDOW); @@ -316,7 +316,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeActionListener */ - static public void addActionListener(ActionListener l) { + public static void addActionListener(ActionListener l) { if (actionListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.ACTION); @@ -331,7 +331,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addActionListener */ - static public void removeActionListener(ActionListener l) { + public static void removeActionListener(ActionListener l) { actionListener = AWTEventMulticaster.remove(actionListener, l); if (actionListener == null) { awtListener.removeListeners(EventID.ACTION); @@ -349,7 +349,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeAdjustmentListener */ - static public void addAdjustmentListener(AdjustmentListener l) { + public static void addAdjustmentListener(AdjustmentListener l) { if (adjustmentListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.ADJUSTMENT); @@ -364,7 +364,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addAdjustmentListener */ - static public void removeAdjustmentListener(AdjustmentListener l) { + public static void removeAdjustmentListener(AdjustmentListener l) { adjustmentListener = AWTEventMulticaster.remove(adjustmentListener, l); if (adjustmentListener == null) { awtListener.removeListeners(EventID.ADJUSTMENT); @@ -381,7 +381,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeItemListener */ - static public void addItemListener(ItemListener l) { + public static void addItemListener(ItemListener l) { if (itemListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.ITEM); @@ -396,7 +396,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addItemListener */ - static public void removeItemListener(ItemListener l) { + public static void removeItemListener(ItemListener l) { itemListener = AWTEventMulticaster.remove(itemListener, l); if (itemListener == null) { awtListener.removeListeners(EventID.ITEM); @@ -413,7 +413,7 @@ public class AWTEventMonitor { * @param l the listener to add * @see #removeTextListener */ - static public void addTextListener(TextListener l) { + public static void addTextListener(TextListener l) { if (textListener == null) { checkInstallPermission(); awtListener.installListeners(EventID.TEXT); @@ -428,7 +428,7 @@ public class AWTEventMonitor { * @param l the listener to remove * @see #addTextListener */ - static public void removeTextListener(TextListener l) { + public static void removeTextListener(TextListener l) { textListener = AWTEventMulticaster.remove(textListener, l); if (textListener == null) { awtListener.removeListeners(EventID.TEXT); diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityEventMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityEventMonitor.java index 79e0b4d2b09e8c1380c6e02b520b4b0dd0969e6f..a2ebac01279c4d83a82a52f28b9c9cf5789d0d10 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityEventMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityEventMonitor.java @@ -56,7 +56,7 @@ public class AccessibilityEventMonitor { * @see #addPropertyChangeListener * @see #removePropertyChangeListener */ - static protected final AccessibilityListenerList listenerList = + protected static final AccessibilityListenerList listenerList = new AccessibilityListenerList(); @@ -66,7 +66,7 @@ public class AccessibilityEventMonitor { * occurs. By doing things this way, the actual number of listeners * installed on a component instance is drastically reduced. */ - static private final AccessibilityEventListener accessibilityListener = + private static final AccessibilityEventListener accessibilityListener = new AccessibilityEventListener(); /** @@ -80,7 +80,7 @@ public class AccessibilityEventMonitor { * * @see #removePropertyChangeListener */ - static public void addPropertyChangeListener(PropertyChangeListener l) { + public static void addPropertyChangeListener(PropertyChangeListener l) { if (listenerList.getListenerCount(PropertyChangeListener.class) == 0) { accessibilityListener.installListeners(); } @@ -93,7 +93,7 @@ public class AccessibilityEventMonitor { * @see #addPropertyChangeListener * @param l the listener to remove */ - static public void removePropertyChangeListener(PropertyChangeListener l) { + public static void removePropertyChangeListener(PropertyChangeListener l) { listenerList.remove(PropertyChangeListener.class, l); if (listenerList.getListenerCount(PropertyChangeListener.class) == 0) { accessibilityListener.removeListeners(); diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityListenerList.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityListenerList.java index 62133dc6773a51440b6934bb434a60e5fa15ee46..6329ef953015be1aac4350010b8b012b8cb0257f 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityListenerList.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/AccessibilityListenerList.java @@ -39,7 +39,7 @@ import javax.accessibility.*; public class AccessibilityListenerList { /* A null array to be shared by all empty listener lists */ - private final static Object[] NULL_ARRAY = new Object[0]; + private static final Object[] NULL_ARRAY = new Object[0]; /** * The list of listener type, listener pairs diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventID.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventID.java index 4fbf8ee508ae8cc155e88009fd00f1a1e4a6ee10..19ca5f822652804a63f11e711754ef8052c4f197 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventID.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventID.java @@ -45,166 +45,166 @@ public class EventID { /** * Maps to AWT Action support (i.e., ActionListener and ActionEvent) */ - static public final int ACTION = 0; + public static final int ACTION = 0; /** * Maps to AWT Adjustment support (i.e., AdjustmentListener * and AdjustmentEvent) */ - static public final int ADJUSTMENT = 1; + public static final int ADJUSTMENT = 1; /** * Maps to AWT Component support (i.e., ComponentListener * and ComponentEvent) */ - static public final int COMPONENT = 2; + public static final int COMPONENT = 2; /** * Maps to AWT Container support (i.e., ContainerListener * and ContainerEvent) */ - static public final int CONTAINER = 3; + public static final int CONTAINER = 3; /** * Maps to AWT Focus support (i.e., FocusListener and FocusEvent) */ - static public final int FOCUS = 4; + public static final int FOCUS = 4; /** * Maps to AWT Item support (i.e., ItemListener and ItemEvent) */ - static public final int ITEM = 5; + public static final int ITEM = 5; /** * Maps to AWT Key support (i.e., KeyListener and KeyEvent) */ - static public final int KEY = 6; + public static final int KEY = 6; /** * Maps to AWT Mouse support (i.e., MouseListener and MouseEvent) */ - static public final int MOUSE = 7; + public static final int MOUSE = 7; /** * Maps to AWT MouseMotion support (i.e., MouseMotionListener * and MouseMotionEvent) */ - static public final int MOTION = 8; + public static final int MOTION = 8; /** * Maps to AWT Text support (i.e., TextListener and TextEvent) */ - static public final int TEXT = 10; + public static final int TEXT = 10; /** * Maps to AWT Window support (i.e., WindowListener and WindowEvent) */ - static public final int WINDOW = 11; + public static final int WINDOW = 11; /** * Maps to Swing Ancestor support (i.e., AncestorListener and * AncestorEvent) */ - static public final int ANCESTOR = 12; + public static final int ANCESTOR = 12; /** * Maps to Swing Text Caret support (i.e., CaretListener and * CaretEvent) */ - static public final int CARET = 13; + public static final int CARET = 13; /** * Maps to Swing CellEditor support (i.e., CellEditorListener and * CellEditorEvent) */ - static public final int CELLEDITOR = 14; + public static final int CELLEDITOR = 14; /** * Maps to Swing Change support (i.e., ChangeListener and * ChangeEvent) */ - static public final int CHANGE = 15; + public static final int CHANGE = 15; /** * Maps to Swing TableColumnModel support (i.e., * TableColumnModelListener and TableColumnModelEvent) */ - static public final int COLUMNMODEL = 16; + public static final int COLUMNMODEL = 16; /** * Maps to Swing Document support (i.e., DocumentListener and * DocumentEvent) */ - static public final int DOCUMENT = 17; + public static final int DOCUMENT = 17; /** * Maps to Swing ListData support (i.e., ListDataListener and * ListDataEvent) */ - static public final int LISTDATA = 18; + public static final int LISTDATA = 18; /** * Maps to Swing ListSelection support (i.e., ListSelectionListener and * ListSelectionEvent) */ - static public final int LISTSELECTION = 19; + public static final int LISTSELECTION = 19; /** * Maps to Swing Menu support (i.e., MenuListener and * MenuEvent) */ - static public final int MENU = 20; + public static final int MENU = 20; /** * Maps to Swing PopupMenu support (i.e., PopupMenuListener and * PopupMenuEvent) */ - static public final int POPUPMENU = 21; + public static final int POPUPMENU = 21; /** * Maps to Swing TableModel support (i.e., TableModelListener and * TableModelEvent) */ - static public final int TABLEMODEL = 22; + public static final int TABLEMODEL = 22; /** * Maps to Swing TreeExpansion support (i.e., TreeExpansionListener and * TreeExpansionEvent) */ - static public final int TREEEXPANSION = 23; + public static final int TREEEXPANSION = 23; /** * Maps to Swing TreeModel support (i.e., TreeModelListener and * TreeModelEvent) */ - static public final int TREEMODEL = 24; + public static final int TREEMODEL = 24; /** * Maps to Swing TreeSelection support (i.e., TreeSelectionListener and * TreeSelectionEvent) */ - static public final int TREESELECTION = 25; + public static final int TREESELECTION = 25; /** * Maps to Swing UndoableEdit support (i.e., UndoableEditListener and * UndoableEditEvent) */ - static public final int UNDOABLEEDIT = 26; + public static final int UNDOABLEEDIT = 26; /** * Maps to Beans PropertyChange support (i.e., PropertyChangeListener * and PropertyChangeEvent) */ - static public final int PROPERTYCHANGE = 27; + public static final int PROPERTYCHANGE = 27; /** * Maps to Beans VetoableChange support (i.e., VetoableChangeListener * and VetoableChangeEvent) */ - static public final int VETOABLECHANGE = 28; + public static final int VETOABLECHANGE = 28; /** * Maps to Swing InternalFrame support (i.e., InternalFrameListener) */ - static public final int INTERNALFRAME = 29; + public static final int INTERNALFRAME = 29; } diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java index 6f06ceb742b02c57c2d997ea8f17de0964833ece..cb630223c49b720c71aa15b691e7de7ea45581fb 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/EventQueueMonitor.java @@ -86,7 +86,7 @@ public class EventQueueMonitor /** * Class that tells us what the component event dispatch thread is. */ - static private ComponentEvtDispatchThread cedt = null; + private static ComponentEvtDispatchThread cedt = null; /** * Handle the synchronization between the thing that populates the @@ -397,7 +397,7 @@ public class EventQueueMonitor * @param p the point to be accessed * @return the {@code Accessible} at the specified point */ - static public Accessible getAccessibleAt(Point p) { + public static Accessible getAccessibleAt(Point p) { Window w = getTopLevelWindowWithFocus(); Window[] wins = getTopLevelWindows(); Component c = null; @@ -464,7 +464,7 @@ public class EventQueueMonitor * @return true if the GUI subsystem has been initialized * @see #addGUIInitializedListener */ - static public boolean isGUIInitialized() { + public static boolean isGUIInitialized() { maybeInitialize(); return guiInitialized; } @@ -478,7 +478,7 @@ public class EventQueueMonitor * @see #isGUIInitialized * @see #removeTopLevelWindowListener */ - static public void addGUIInitializedListener(GUIInitializedListener l) { + public static void addGUIInitializedListener(GUIInitializedListener l) { maybeInitialize(); guiInitializedListener = GUIInitializedMulticaster.add(guiInitializedListener,l); @@ -491,7 +491,7 @@ public class EventQueueMonitor * @param l the listener to remove * @see #addGUIInitializedListener */ - static public void removeGUIInitializedListener(GUIInitializedListener l) { + public static void removeGUIInitializedListener(GUIInitializedListener l) { guiInitializedListener = GUIInitializedMulticaster.remove(guiInitializedListener,l); } @@ -503,7 +503,7 @@ public class EventQueueMonitor * @param l the listener to add * @see #removeTopLevelWindowListener */ - static public void addTopLevelWindowListener(TopLevelWindowListener l) { + public static void addTopLevelWindowListener(TopLevelWindowListener l) { topLevelWindowListener = TopLevelWindowMulticaster.add(topLevelWindowListener,l); } @@ -515,7 +515,7 @@ public class EventQueueMonitor * @param l the listener to remove * @see #addTopLevelWindowListener */ - static public void removeTopLevelWindowListener(TopLevelWindowListener l) { + public static void removeTopLevelWindowListener(TopLevelWindowListener l) { topLevelWindowListener = TopLevelWindowMulticaster.remove(topLevelWindowListener,l); } @@ -525,7 +525,7 @@ public class EventQueueMonitor * * @return the last recorded position of the mouse in screen coordinates */ - static public Point getCurrentMousePosition() { + public static Point getCurrentMousePosition() { return currentMousePosition; } @@ -534,7 +534,7 @@ public class EventQueueMonitor * * @return an array of top level {@code Window}s in use in the Java Virtual Machine */ - static public Window[] getTopLevelWindows() { + public static Window[] getTopLevelWindows() { // Because this method is static, do not make it synchronized because // it can lock the whole class. Instead, just lock what needs to be @@ -559,7 +559,7 @@ public class EventQueueMonitor * * @return the top level {@code Window} that currently has keyboard focus */ - static public Window getTopLevelWindowWithFocus() { + public static Window getTopLevelWindowWithFocus() { return topLevelWindowWithFocus; } } diff --git a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java index d8d82970ef5cee695960f3799dda619ea4666668..e70ed05e609574eac7f19408536cf4fe9f04a911 100644 --- a/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java +++ b/src/jdk.accessibility/share/classes/com/sun/java/accessibility/util/SwingEventMonitor.java @@ -63,7 +63,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * This can only be publicly modified by calling the add or * remove listener methods in this class. */ - static protected final EventListenerList listenerList = new EventListenerList(); + protected static final EventListenerList listenerList = new EventListenerList(); /** * The actual listener that is installed on the component instances. @@ -71,7 +71,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * occurs. By doing things this way, the actual number of listeners * installed on a component instance is drastically reduced. */ - static private final SwingEventListener swingListener = new SwingEventListener(); + private static final SwingEventListener swingListener = new SwingEventListener(); /** * Constructs a {@code SwingEventMonitor}. @@ -88,7 +88,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeAncestorListener */ - static public void addAncestorListener(AncestorListener l) { + public static void addAncestorListener(AncestorListener l) { if (listenerList.getListenerCount(AncestorListener.class) == 0) { swingListener.installListeners(EventID.ANCESTOR); } @@ -102,7 +102,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addAncestorListener */ - static public void removeAncestorListener(AncestorListener l) { + public static void removeAncestorListener(AncestorListener l) { listenerList.remove(AncestorListener.class, l); if (listenerList.getListenerCount(AncestorListener.class) == 0) { swingListener.removeListeners(EventID.ANCESTOR); @@ -119,7 +119,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeCaretListener */ - static public void addCaretListener(CaretListener l) { + public static void addCaretListener(CaretListener l) { if (listenerList.getListenerCount(CaretListener.class) == 0) { swingListener.installListeners(EventID.CARET); } @@ -133,7 +133,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addCaretListener */ - static public void removeCaretListener(CaretListener l) { + public static void removeCaretListener(CaretListener l) { listenerList.remove(CaretListener.class, l); if (listenerList.getListenerCount(CaretListener.class) == 0) { swingListener.removeListeners(EventID.CARET); @@ -151,7 +151,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeCellEditorListener */ - static public void addCellEditorListener(CellEditorListener l) { + public static void addCellEditorListener(CellEditorListener l) { if (listenerList.getListenerCount(CellEditorListener.class) == 0) { swingListener.installListeners(EventID.CELLEDITOR); } @@ -165,7 +165,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addCellEditorListener */ - static public void removeCellEditorListener(CellEditorListener l) { + public static void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); if (listenerList.getListenerCount(CellEditorListener.class) == 0) { swingListener.removeListeners(EventID.CELLEDITOR); @@ -182,7 +182,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeChangeListener */ - static public void addChangeListener(ChangeListener l) { + public static void addChangeListener(ChangeListener l) { if (listenerList.getListenerCount(ChangeListener.class) == 0) { swingListener.installListeners(EventID.CHANGE); } @@ -196,7 +196,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addChangeListener */ - static public void removeChangeListener(ChangeListener l) { + public static void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); if (listenerList.getListenerCount(ChangeListener.class) == 0) { swingListener.removeListeners(EventID.CHANGE); @@ -213,7 +213,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeColumnModelListener */ - static public void addColumnModelListener(TableColumnModelListener l) { + public static void addColumnModelListener(TableColumnModelListener l) { if (listenerList.getListenerCount(TableColumnModelListener.class) == 0) { swingListener.installListeners(EventID.COLUMNMODEL); } @@ -227,7 +227,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addColumnModelListener */ - static public void removeColumnModelListener(TableColumnModelListener l) { + public static void removeColumnModelListener(TableColumnModelListener l) { listenerList.remove(TableColumnModelListener.class, l); if (listenerList.getListenerCount(TableColumnModelListener.class) == 0) { swingListener.removeListeners(EventID.COLUMNMODEL); @@ -244,7 +244,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeDocumentListener */ - static public void addDocumentListener(DocumentListener l) { + public static void addDocumentListener(DocumentListener l) { if (listenerList.getListenerCount(DocumentListener.class) == 0) { swingListener.installListeners(EventID.DOCUMENT); } @@ -258,7 +258,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addDocumentListener */ - static public void removeDocumentListener(DocumentListener l) { + public static void removeDocumentListener(DocumentListener l) { listenerList.remove(DocumentListener.class, l); if (listenerList.getListenerCount(DocumentListener.class) == 0) { swingListener.removeListeners(EventID.DOCUMENT); @@ -275,7 +275,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeListDataListener */ - static public void addListDataListener(ListDataListener l) { + public static void addListDataListener(ListDataListener l) { if (listenerList.getListenerCount(ListDataListener.class) == 0) { swingListener.installListeners(EventID.LISTDATA); } @@ -289,7 +289,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addListDataListener */ - static public void removeListDataListener(ListDataListener l) { + public static void removeListDataListener(ListDataListener l) { listenerList.remove(ListDataListener.class, l); if (listenerList.getListenerCount(ListDataListener.class) == 0) { swingListener.removeListeners(EventID.LISTDATA); @@ -306,7 +306,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeListSelectionListener */ - static public void addListSelectionListener(ListSelectionListener l) { + public static void addListSelectionListener(ListSelectionListener l) { if (listenerList.getListenerCount(ListSelectionListener.class) == 0) { swingListener.installListeners(EventID.LISTSELECTION); } @@ -320,7 +320,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addListSelectionListener */ - static public void removeListSelectionListener(ListSelectionListener l) { + public static void removeListSelectionListener(ListSelectionListener l) { listenerList.remove(ListSelectionListener.class, l); if (listenerList.getListenerCount(ListSelectionListener.class) == 0) { swingListener.removeListeners(EventID.LISTSELECTION); @@ -337,7 +337,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeMenuListener */ - static public void addMenuListener(MenuListener l) { + public static void addMenuListener(MenuListener l) { if (listenerList.getListenerCount(MenuListener.class) == 0) { swingListener.installListeners(EventID.MENU); } @@ -351,7 +351,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addMenuListener */ - static public void removeMenuListener(MenuListener l) { + public static void removeMenuListener(MenuListener l) { listenerList.remove(MenuListener.class, l); if (listenerList.getListenerCount(MenuListener.class) == 0) { swingListener.removeListeners(EventID.MENU); @@ -368,7 +368,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removePopupMenuListener */ - static public void addPopupMenuListener(PopupMenuListener l) { + public static void addPopupMenuListener(PopupMenuListener l) { if (listenerList.getListenerCount(PopupMenuListener.class) == 0) { swingListener.installListeners(EventID.POPUPMENU); } @@ -382,7 +382,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addPopupMenuListener */ - static public void removePopupMenuListener(PopupMenuListener l) { + public static void removePopupMenuListener(PopupMenuListener l) { listenerList.remove(PopupMenuListener.class, l); if (listenerList.getListenerCount(PopupMenuListener.class) == 0) { swingListener.removeListeners(EventID.POPUPMENU); @@ -399,7 +399,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeTableModelListener */ - static public void addTableModelListener(TableModelListener l) { + public static void addTableModelListener(TableModelListener l) { if (listenerList.getListenerCount(TableModelListener.class) == 0) { swingListener.installListeners(EventID.TABLEMODEL); } @@ -413,7 +413,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addTableModelListener */ - static public void removeTableModelListener(TableModelListener l) { + public static void removeTableModelListener(TableModelListener l) { listenerList.remove(TableModelListener.class, l); if (listenerList.getListenerCount(TableModelListener.class) == 0) { swingListener.removeListeners(EventID.TABLEMODEL); @@ -430,7 +430,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeTreeExpansionListener */ - static public void addTreeExpansionListener(TreeExpansionListener l) { + public static void addTreeExpansionListener(TreeExpansionListener l) { if (listenerList.getListenerCount(TreeExpansionListener.class) == 0) { swingListener.installListeners(EventID.TREEEXPANSION); } @@ -444,7 +444,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addTreeExpansionListener */ - static public void removeTreeExpansionListener(TreeExpansionListener l) { + public static void removeTreeExpansionListener(TreeExpansionListener l) { listenerList.remove(TreeExpansionListener.class, l); if (listenerList.getListenerCount(TreeExpansionListener.class) == 0) { swingListener.removeListeners(EventID.TREEEXPANSION); @@ -461,7 +461,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeTreeModelListener */ - static public void addTreeModelListener(TreeModelListener l) { + public static void addTreeModelListener(TreeModelListener l) { if (listenerList.getListenerCount(TreeModelListener.class) == 0) { swingListener.installListeners(EventID.TREEMODEL); } @@ -475,7 +475,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addTreeModelListener */ - static public void removeTreeModelListener(TreeModelListener l) { + public static void removeTreeModelListener(TreeModelListener l) { listenerList.remove(TreeModelListener.class, l); if (listenerList.getListenerCount(TreeModelListener.class) == 0) { swingListener.removeListeners(EventID.TREEMODEL); @@ -492,7 +492,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeTreeSelectionListener */ - static public void addTreeSelectionListener(TreeSelectionListener l) { + public static void addTreeSelectionListener(TreeSelectionListener l) { if (listenerList.getListenerCount(TreeSelectionListener.class) == 0) { swingListener.installListeners(EventID.TREESELECTION); } @@ -505,7 +505,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @see #addTreeSelectionListener * @param l the listener to remove */ - static public void removeTreeSelectionListener(TreeSelectionListener l) { + public static void removeTreeSelectionListener(TreeSelectionListener l) { listenerList.remove(TreeSelectionListener.class, l); if (listenerList.getListenerCount(TreeSelectionListener.class) == 0) { swingListener.removeListeners(EventID.TREESELECTION); @@ -522,7 +522,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeUndoableEditListener */ - static public void addUndoableEditListener(UndoableEditListener l) { + public static void addUndoableEditListener(UndoableEditListener l) { if (listenerList.getListenerCount(UndoableEditListener.class) == 0) { swingListener.installListeners(EventID.UNDOABLEEDIT); } @@ -536,7 +536,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addUndoableEditListener */ - static public void removeUndoableEditListener(UndoableEditListener l) { + public static void removeUndoableEditListener(UndoableEditListener l) { listenerList.remove(UndoableEditListener.class, l); if (listenerList.getListenerCount(UndoableEditListener.class) == 0) { swingListener.removeListeners(EventID.UNDOABLEEDIT); @@ -553,7 +553,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeInternalFrameListener */ - static public void addInternalFrameListener(InternalFrameListener l) { + public static void addInternalFrameListener(InternalFrameListener l) { if (listenerList.getListenerCount(InternalFrameListener.class) == 0) { swingListener.installListeners(EventID.INTERNALFRAME); } @@ -567,7 +567,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addInternalFrameListener */ - static public void removeInternalFrameListener(InternalFrameListener l) { + public static void removeInternalFrameListener(InternalFrameListener l) { listenerList.remove(InternalFrameListener.class, l); if (listenerList.getListenerCount(InternalFrameListener.class) == 0) { swingListener.removeListeners(EventID.INTERNALFRAME); @@ -584,7 +584,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removePropertyChangeListener */ - static public void addPropertyChangeListener(PropertyChangeListener l) { + public static void addPropertyChangeListener(PropertyChangeListener l) { if (listenerList.getListenerCount(PropertyChangeListener.class) == 0) { swingListener.installListeners(EventID.PROPERTYCHANGE); } @@ -597,7 +597,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @see #addPropertyChangeListener * @param l the listener to remove */ - static public void removePropertyChangeListener(PropertyChangeListener l) { + public static void removePropertyChangeListener(PropertyChangeListener l) { listenerList.remove(PropertyChangeListener.class, l); if (listenerList.getListenerCount(PropertyChangeListener.class) == 0) { swingListener.removeListeners(EventID.PROPERTYCHANGE); @@ -614,7 +614,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to add * @see #removeVetoableChangeListener */ - static public void addVetoableChangeListener(VetoableChangeListener l) { + public static void addVetoableChangeListener(VetoableChangeListener l) { if (listenerList.getListenerCount(VetoableChangeListener.class) == 0) { swingListener.installListeners(EventID.VETOABLECHANGE); } @@ -628,7 +628,7 @@ public class SwingEventMonitor extends AWTEventMonitor { * @param l the listener to remove * @see #addVetoableChangeListener */ - static public void removeVetoableChangeListener(VetoableChangeListener l) { + public static void removeVetoableChangeListener(VetoableChangeListener l) { listenerList.remove(VetoableChangeListener.class, l); if (listenerList.getListenerCount(VetoableChangeListener.class) == 0) { swingListener.removeListeners(EventID.VETOABLECHANGE); diff --git a/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java b/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java index faf041e269ff23d43a6722389865f63e672fc47d..853be1977546357ad702ceb5c8029fdb3e85d18f 100644 --- a/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java +++ b/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java @@ -53,7 +53,7 @@ import java.util.concurrent.ConcurrentHashMap; * Note: This class has to be public. It's loaded from the VM like this: * Class.forName(atName).newInstance(); */ -final public class AccessBridge { +public final class AccessBridge { private static AccessBridge theAccessBridge; private ObjectReferences references; @@ -314,15 +314,15 @@ final public class AccessBridge { } // hash table of native window handle to AccessibleContext mappings - static private ConcurrentHashMap windowHandleToContextMap = new ConcurrentHashMap<>(); + private static ConcurrentHashMap windowHandleToContextMap = new ConcurrentHashMap<>(); // hash table of AccessibleContext to native window handle mappings - static private ConcurrentHashMap contextToWindowHandleMap = new ConcurrentHashMap<>(); + private static ConcurrentHashMap contextToWindowHandleMap = new ConcurrentHashMap<>(); /* * adds a virtual window handler to our hash tables */ - static private void registerVirtualFrame(final Accessible a, + private static void registerVirtualFrame(final Accessible a, Integer nativeWindowHandle ) { if (a != null) { AccessibleContext ac = InvocationUtils.invokeAndWait(new Callable() { @@ -339,7 +339,7 @@ final public class AccessBridge { /* * removes a virtual window handler to our hash tables */ - static private void revokeVirtualFrame(final Accessible a, + private static void revokeVirtualFrame(final Accessible a, Integer nativeWindowHandle ) { AccessibleContext ac = InvocationUtils.invokeAndWait(new Callable() { @Override diff --git a/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java b/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java index 78450b8053ef4618048a21d1db49c0e0c56f79b3..cd54a6a2ff87ade27ffa57f5466ebe6edcac1e57 100644 --- a/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java +++ b/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java @@ -135,10 +135,10 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { } // protocol version - private final static String PROTOCOL_VERSION = "1"; + private static final String PROTOCOL_VERSION = "1"; // known errors - private final static int ATTACH_ERROR_BADVERSION = 101; + private static final int ATTACH_ERROR_BADVERSION = 101; /** * Execute the given command in the target VM. diff --git a/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java b/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java index 402cc10b67b7bc1c6dcd38752137f450e4de40b8..7ac440d947d23e9d56f56888a2037baf4c06dd7c 100644 --- a/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java +++ b/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java @@ -139,10 +139,10 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { } // protocol version - private final static String PROTOCOL_VERSION = "1"; + private static final String PROTOCOL_VERSION = "1"; // known errors - private final static int ATTACH_ERROR_BADVERSION = 101; + private static final int ATTACH_ERROR_BADVERSION = 101; /** * Execute the given command in the target VM. diff --git a/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java b/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java index e484ddd1bc0d20b335ad90881b9641c187148b44..6d05e1158ef70bd1b6b33010ae4b208be940fd22 100644 --- a/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java +++ b/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java @@ -135,10 +135,10 @@ public class VirtualMachineImpl extends HotSpotVirtualMachine { } // protocol version - private final static String PROTOCOL_VERSION = "1"; + private static final String PROTOCOL_VERSION = "1"; // known errors - private final static int ATTACH_ERROR_BADVERSION = 101; + private static final int ATTACH_ERROR_BADVERSION = 101; /** * Execute the given command in the target VM. diff --git a/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template b/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template index 96e9067cbfd904f1bc7eed1fa20a62bb90a82f93..0ade0e9459d8c3acee66e614876de17c7d1d8024 100644 --- a/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template +++ b/src/jdk.charsets/share/classes/sun/nio/cs/ext/EUC_JP.java.template @@ -25,6 +25,9 @@ package $PACKAGE$; +import jdk.internal.access.JavaLangAccess; +import jdk.internal.access.SharedSecrets; + import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; @@ -43,6 +46,8 @@ public class EUC_JP extends Charset implements HistoricallyNamedCharset { + private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess(); + public EUC_JP() { super("EUC-JP", $ALIASES$); } @@ -303,6 +308,11 @@ public class EUC_JP byte[] tmpBuf = new byte[3]; try { + if (enc0201.isASCIICompatible()) { + int n = JLA.encodeASCII(sa, sp, da, dp, Math.min(dl - dp, sl - sp)); + sp += n; + dp += n; + } while (sp < sl) { outputByte = tmpBuf; char c = sa[sp]; diff --git a/src/jdk.charsets/share/classes/sun/nio/cs/ext/IBM964.java.template b/src/jdk.charsets/share/classes/sun/nio/cs/ext/IBM964.java.template index 63615c2bd5599256b0c367d43c97166d29f84a07..6e44dd6fce82d096ffe9248bfb985be814f7b389 100644 --- a/src/jdk.charsets/share/classes/sun/nio/cs/ext/IBM964.java.template +++ b/src/jdk.charsets/share/classes/sun/nio/cs/ext/IBM964.java.template @@ -203,7 +203,7 @@ public class IBM964 } protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) { - if (true && src.hasArray() && dst.hasArray()) + if (src.hasArray() && dst.hasArray()) return decodeArrayLoop(src, dst); else return decodeBufferLoop(src, dst); diff --git a/src/jdk.charsets/share/classes/sun/nio/cs/ext/SimpleEUCEncoder.java.template b/src/jdk.charsets/share/classes/sun/nio/cs/ext/SimpleEUCEncoder.java.template index 0811087cd21d1a9becdb459321f5af40ec350e35..235bba0bb98d852b6a22ab8457b861b54449cf2d 100644 --- a/src/jdk.charsets/share/classes/sun/nio/cs/ext/SimpleEUCEncoder.java.template +++ b/src/jdk.charsets/share/classes/sun/nio/cs/ext/SimpleEUCEncoder.java.template @@ -260,7 +260,7 @@ public abstract class SimpleEUCEncoder } protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) { - if (true && src.hasArray() && dst.hasArray()) + if (src.hasArray() && dst.hasArray()) return encodeArrayLoop(src, dst); else return encodeBufferLoop(src, dst); diff --git a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java index b0375d200c3f88c00529698a1b8676aa869a2d95..4dea3d09bf46de415cb38df714c6d7714766f044 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java +++ b/src/jdk.compiler/share/classes/com/sun/source/doctree/DocTree.java @@ -80,6 +80,8 @@ public interface DocTree { /** * Used for instances of {@link DocTypeTree} * representing an HTML DocType declaration. + * + * @since 10 */ DOC_TYPE, @@ -122,6 +124,8 @@ public interface DocTree { /** * Used for instances of {@link IndexTree} * representing an {@code @index} tag. + * + * @since 9 */ INDEX("index"), @@ -158,6 +162,8 @@ public interface DocTree { /** * Used for instances of {@link ProvidesTree} * representing an {@code @provides} tag. + * + * @since 9 */ PROVIDES("provides"), @@ -207,6 +213,8 @@ public interface DocTree { /** * Used for instances of {@link SnippetTree} * representing an {@code @snippet} tag. + * + * @since 18 */ SNIPPET("snippet"), @@ -219,12 +227,16 @@ public interface DocTree { /** * Used for instances of {@link SystemPropertyTree} * representing an {@code @systemProperty} tag. + * + * @since 12 */ SYSTEM_PROPERTY("systemProperty"), /** * Used for instances of {@link SummaryTree} * representing an {@code @summary} tag. + * + * @since 10 */ SUMMARY("summary"), @@ -255,6 +267,8 @@ public interface DocTree { /** * Used for instances of {@link UsesTree} * representing an {@code @uses} tag. + * + * @since 9 */ USES("uses"), diff --git a/src/jdk.compiler/share/classes/com/sun/source/util/Trees.java b/src/jdk.compiler/share/classes/com/sun/source/util/Trees.java index b33117bc541af0f01beefbcec5104f8546ce3948..e4228d37bd5a7772eb393aeacb480365a7af4b08 100644 --- a/src/jdk.compiler/share/classes/com/sun/source/util/Trees.java +++ b/src/jdk.compiler/share/classes/com/sun/source/util/Trees.java @@ -72,7 +72,7 @@ public abstract class Trees { } /** - * Returns a {code Trees} object for a given {@code ProcessingEnvironment}. + * Returns a {@code Trees} object for a given {@code ProcessingEnvironment}. * @param env the processing environment for which to get the {@code Trees} object * @throws IllegalArgumentException if the env does not support the Tree API. * @return the {@code Trees} object diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java index a26345ead881e63390ac63b5919bfc2542ba4d46..643d5bbee1f22cd52bb29c8e7c3c264f8a318ed7 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java @@ -305,6 +305,17 @@ public class ClientCodeWrapper { } } + @Override @DefinedBy(Api.COMPILER) + public JavaFileObject getJavaFileForOutputForOriginatingFiles(Location location, String className, Kind kind, FileObject... originatingFiles) throws IOException { + try { + return wrap(clientJavaFileManager.getJavaFileForOutputForOriginatingFiles(location, className, kind, originatingFiles)); + } catch (ClientCodeException e) { + throw e; + } catch (RuntimeException | Error e) { + throw new ClientCodeException(e); + } + } + @Override @DefinedBy(Api.COMPILER) public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { try { @@ -316,6 +327,17 @@ public class ClientCodeWrapper { } } + @Override @DefinedBy(Api.COMPILER) + public FileObject getFileForOutputForOriginatingFiles(Location location, String packageName, String relativeName, FileObject... originatingFiles) throws IOException { + try { + return wrap(clientJavaFileManager.getFileForOutputForOriginatingFiles(location, packageName, relativeName, originatingFiles)); + } catch (ClientCodeException e) { + throw e; + } catch (RuntimeException | Error e) { + throw new ClientCodeException(e); + } + } + @Override @DefinedBy(Api.COMPILER) public boolean contains(Location location, FileObject file) throws IOException { try { diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java index 3b189799368b7cae9ef29d20b63d54b1a1a69013..75926c1b0d0cd2119b10d1e59a250d1bb584e142 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java @@ -980,7 +980,7 @@ public class JavacTrees extends DocTrees { } }.scan(env.enclClass); //revert changes done by the visitor: - toClear.stream().forEach(c -> { + toClear.forEach(c -> { chk.clearLocalClassNameIndexes(c); chk.removeCompiled(c); }); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java index 617d891fb7ce496e264ece81e5c36c835796e664..a6dddba278c468cc634df5970cb441dbba5b7d20 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java @@ -117,7 +117,12 @@ public enum Source { /** * 18, tbd */ - JDK18("18"); + JDK18("18"), + + /** + * 19, tbd + */ + JDK19("19"); private static final Context.Key sourceKey = new Context.Key<>(); @@ -169,6 +174,7 @@ public enum Source { public Target requiredTarget() { return switch(this) { + case JDK19 -> Target.JDK1_19; case JDK18 -> Target.JDK1_18; case JDK17 -> Target.JDK1_17; case JDK16 -> Target.JDK1_16; @@ -313,6 +319,7 @@ public enum Source { case JDK16 -> RELEASE_16; case JDK17 -> RELEASE_17; case JDK18 -> RELEASE_18; + case JDK19 -> RELEASE_19; default -> null; }; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java index 17dc60c1a882f5b4169f6d7f36a77e38f701a59d..f72a943a2a2307dc3ae6df1a07f8bb371155ac33 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java @@ -794,7 +794,7 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem /** A base class for Symbols representing types. */ - public static abstract class TypeSymbol extends Symbol { + public abstract static class TypeSymbol extends Symbol { public TypeSymbol(Kind kind, long flags, Name name, Type type, Symbol owner) { super(kind, flags, name, type, owner); } @@ -2278,6 +2278,11 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem this.staticArgs = staticArgs; } + @Override + public Name name() { + return name; + } + @Override public boolean isDynamic() { return true; @@ -2316,6 +2321,11 @@ public abstract class Symbol extends AnnoConstruct implements PoolConstant, Elem this.staticArgs = staticArgs; } + @Override + public Name name() { + return name; + } + @Override public boolean isDynamic() { return true; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java index e7008a2bfdd22b836c8bd5f3d98d225262298291..97240a45d6f5808272b2b7ffb8b2827bbc3edd09 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java @@ -224,6 +224,14 @@ public class Symtab { public final Type valueBasedType; public final Type valueBasedInternalType; + // For serialization lint checking + public final Type objectStreamFieldType; + public final Type objectInputStreamType; + public final Type objectOutputStreamType; + public final Type ioExceptionType; + public final Type objectStreamExceptionType; + public final Type externalizableType; + /** The symbol representing the length field of an array. */ public final VarSymbol lengthVar; @@ -590,6 +598,13 @@ public class Symtab { switchBootstrapsType = enterClass("java.lang.runtime.SwitchBootstraps"); valueBasedType = enterClass("jdk.internal.ValueBased"); valueBasedInternalType = enterSyntheticAnnotation("jdk.internal.ValueBased+Annotation"); + // For serialization lint checking + objectStreamFieldType = enterClass("java.io.ObjectStreamField"); + objectInputStreamType = enterClass("java.io.ObjectInputStream"); + objectOutputStreamType = enterClass("java.io.ObjectOutputStream"); + ioExceptionType = enterClass("java.io.IOException"); + objectStreamExceptionType = enterClass("java.io.ObjectStreamException"); + externalizableType = enterClass("java.io.Externalizable"); synthesizeEmptyInterfaceIfMissing(autoCloseableType); synthesizeEmptyInterfaceIfMissing(cloneableType); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Type.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Type.java index c559f8c5be5f890989703d1fa6ecdf674c7169e2..3cf340523002c44ab68495b2d51474e42f485265 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Type.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Type.java @@ -241,7 +241,7 @@ public abstract class Type extends AnnoConstruct implements TypeMirror, PoolCons * of a given type expression. This mapping returns the original type is no changes occurred * when recursively mapping the original type's subterms. */ - public static abstract class StructuralTypeMapping extends Types.TypeMapping { + public abstract static class StructuralTypeMapping extends Types.TypeMapping { @Override public Type visitClassType(ClassType t, S s) { @@ -1786,7 +1786,7 @@ public abstract class Type extends AnnoConstruct implements TypeMirror, PoolCons } } - public static abstract class DelegatedType extends Type { + public abstract static class DelegatedType extends Type { public Type qtype; public TypeTag tag; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java index 0343f826eac014f7ea7850dbccf031e61a1695f1..ae80d86625e9bb636af3670df034b105a719213c 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/TypeAnnotations.java @@ -56,18 +56,27 @@ import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.resources.CompilerProperties.Errors; import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.TreeInfo; +import com.sun.tools.javac.tree.JCTree.JCAnnotatedType; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCLambda; +import com.sun.tools.javac.tree.JCTree.JCMemberReference; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; +import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCTypeApply; +import com.sun.tools.javac.tree.JCTree.JCTypeIntersection; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCTypeUnion; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.JCTree.Tag; +import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeScanner; -import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; @@ -1132,7 +1141,7 @@ public class TypeAnnotations { } scan(tree.defs); if (tree.sym.isRecord()) { - tree.sym.getRecordComponents().stream().forEach(rc -> scan(rc.accessorMeth)); + tree.sym.getRecordComponents().forEach(rc -> scan(rc.accessorMeth)); } } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java index 9d182a4c0766bfefda1bb913412c1aa236651fe5..51926a70529a0690d1dc7943d84edf87884394ad 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java @@ -4896,7 +4896,7 @@ public class Types { * type itself) of the operation implemented by this visitor; use * Void if a second argument is not needed. */ - public static abstract class DefaultTypeVisitor implements Type.Visitor { + public abstract static class DefaultTypeVisitor implements Type.Visitor { public final R visit(Type t, S s) { return t.accept(this, s); } public R visitClassType(ClassType t, S s) { return visitType(t, s); } public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); } @@ -4923,7 +4923,7 @@ public class Types { * symbol itself) of the operation implemented by this visitor; use * Void if a second argument is not needed. */ - public static abstract class DefaultSymbolVisitor implements Symbol.Visitor { + public abstract static class DefaultSymbolVisitor implements Symbol.Visitor { public final R visit(Symbol s, S arg) { return s.accept(this, arg); } public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); } public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); } @@ -4946,7 +4946,7 @@ public class Types { * type itself) of the operation implemented by this visitor; use * Void if a second argument is not needed. */ - public static abstract class SimpleVisitor extends DefaultTypeVisitor { + public abstract static class SimpleVisitor extends DefaultTypeVisitor { @Override public R visitCapturedType(CapturedType t, S s) { return visitTypeVar(t, s); @@ -4966,7 +4966,7 @@ public class Types { * form Type × Type → Boolean. * */ - public static abstract class TypeRelation extends SimpleVisitor {} + public abstract static class TypeRelation extends SimpleVisitor {} /** * A convenience visitor for implementing operations that only @@ -4976,7 +4976,7 @@ public class Types { * @param the return type of the operation implemented by this * visitor; use Void if no return type is needed. */ - public static abstract class UnaryVisitor extends SimpleVisitor { + public abstract static class UnaryVisitor extends SimpleVisitor { public final R visit(Type t) { return t.accept(this, null); } } @@ -5041,7 +5041,7 @@ public class Types { // - public static abstract class SignatureGenerator { + public abstract static class SignatureGenerator { public static class InvalidSignatureException extends RuntimeException { private static final long serialVersionUID = 0; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java index d391ff38dc4f4ea972f6a39f6c87d4991b426a47..fdf91e6f423aead8eec0aa8cbaefde874ccf8680 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Annotate.java @@ -345,7 +345,7 @@ public class Annotate { Assert.checkNonNull(c, "Failed to create annotation"); - if (a.type.tsym.isAnnotationType()) { + if (a.type.isErroneous() || a.type.tsym.isAnnotationType()) { if (annotated.containsKey(a.type.tsym)) { if (!allowRepeatedAnnos) { log.error(DiagnosticFlag.SOURCE_LEVEL, a.pos(), Feature.REPEATED_ANNOTATIONS.error(sourceName)); @@ -672,6 +672,12 @@ public class Annotate { log.error(tree.pos(), Errors.AttributeValueMustBeConstant); return new Attribute.Error(expectedElementType); } + + // Scan the annotation element value and then attribute nested annotations if present + if (tree.type != null && tree.type.tsym != null) { + queueScanTreeAndTypeAnnotate(tree, env, tree.type.tsym, tree.pos()); + } + result = cfolder.coerce(result, expectedElementType); return new Attribute.Constant(expectedElementType, result.constValue()); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index df50d2486a184b18c9c85d0063bb6a07e576b647..7bd813cddb73abb43d14c71051acfdaca111cb56 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -1680,7 +1680,8 @@ public class Attr extends JCTree.Visitor { // Attribute all cases and // check that there are no duplicate case labels or default clauses. Set labels = new HashSet<>(); // The set of case labels. - List coveredTypes = List.nil(); + List coveredTypesForPatterns = List.nil(); + List coveredTypesForConstants = List.nil(); boolean hasDefault = false; // Is there a default label? boolean hasTotalPattern = false; // Is there a total pattern? boolean hasNullPattern = false; // Is there a null pattern? @@ -1718,7 +1719,7 @@ public class Attr extends JCTree.Visitor { } else if (!labels.add(sym)) { log.error(pat.pos(), Errors.DuplicateCaseLabel); } else { - checkCaseLabelDominated(pat.pos(), coveredTypes, sym.type); + checkCaseLabelDominated(pat.pos(), coveredTypesForConstants, sym.type); } } else if (errorEnumSwitch) { //error recovery: the selector is erroneous, and all the case labels @@ -1751,7 +1752,7 @@ public class Attr extends JCTree.Visitor { } else if (!labels.add(pattype.constValue())) { log.error(c.pos(), Errors.DuplicateCaseLabel); } else { - checkCaseLabelDominated(pat.pos(), coveredTypes, types.boxedTypeOrType(pattype)); + checkCaseLabelDominated(pat.pos(), coveredTypesForConstants, types.boxedTypeOrType(pattype)); } } } @@ -1784,9 +1785,12 @@ public class Attr extends JCTree.Visitor { } hasTotalPattern = true; } - checkCaseLabelDominated(pat.pos(), coveredTypes, patternType); - if (primary.unconditional() && !patternType.isErroneous()) { - coveredTypes = coveredTypes.prepend(patternType); + checkCaseLabelDominated(pat.pos(), coveredTypesForPatterns, patternType); + if (!patternType.isErroneous()) { + coveredTypesForConstants = coveredTypesForConstants.prepend(patternType); + if (primary.unconditional()) { + coveredTypesForPatterns = coveredTypesForPatterns.prepend(patternType); + } } } currentBindings = matchBindingsComputer.switchCase(pat, currentBindings, matchBindings); @@ -2955,7 +2959,7 @@ public class Attr extends JCTree.Visitor { } if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && - isSerializable(clazztype)) { + rs.isSerializable(clazztype)) { localEnv.info.isSerializable = true; } @@ -3080,7 +3084,7 @@ public class Attr extends JCTree.Visitor { boolean needsRecovery = resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; try { - if (needsRecovery && isSerializable(pt())) { + if (needsRecovery && rs.isSerializable(pt())) { localEnv.info.isSerializable = true; localEnv.info.isSerializableLambda = true; } @@ -3581,7 +3585,7 @@ public class Attr extends JCTree.Visitor { boolean isTargetSerializable = resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK && - isSerializable(pt()); + rs.isSerializable(pt()); TargetInfo targetInfo = getTargetInfo(that, resultInfo, null); Type currentTarget = targetInfo.target; Type desc = targetInfo.descriptor; @@ -3950,14 +3954,14 @@ public class Attr extends JCTree.Visitor { : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); // Find operator. - Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); + OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype); Type owntype = types.createErrorType(tree.type); if (operator != operators.noOpSymbol && !argtype.isErroneous()) { owntype = (tree.getTag().isIncOrDecUnaryOp()) ? tree.arg.type : operator.type.getReturnType(); - int opc = ((OperatorSymbol)operator).opcode; + int opc = operator.opcode; // If the argument is constant, fold it. if (argtype.constValue() != null) { @@ -4004,13 +4008,13 @@ public class Attr extends JCTree.Visitor { matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings); // Find operator. - Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); + OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right); Type owntype = types.createErrorType(tree.type); if (operator != operators.noOpSymbol && !left.isErroneous() && !right.isErroneous()) { owntype = operator.type.getReturnType(); - int opc = ((OperatorSymbol)operator).opcode; + int opc = operator.opcode; // If both arguments are constants, fold them. if (left.constValue() != null && right.constValue() != null) { Type ctype = cfolder.fold2(opc, left, right); @@ -4344,7 +4348,8 @@ public class Attr extends JCTree.Visitor { if (env.info.isSelfCall && ((sym.name == names._this && site.tsym == env.enclClass.sym) || - sym.name == names._super && env.info.constructorArgs)) { + sym.name == names._super && env.info.constructorArgs && + (sitesym.isInterface() || site.tsym == env.enclClass.sym))) { chk.earlyRefError(tree.pos(), sym); } } else { @@ -5098,6 +5103,14 @@ public class Attr extends JCTree.Visitor { Assert.error("should be handled in annotate"); } + @Override + public void visitModifiers(JCModifiers tree) { + //error recovery only: + Assert.check(resultInfo.pkind == KindSelector.ERR); + + attribAnnotationTypes(tree.annotations, env); + } + public void visitAnnotatedType(JCAnnotatedType tree) { attribAnnotationTypes(tree.annotations, env); Type underlyingType = attribType(tree.underlyingType, env); @@ -5366,7 +5379,7 @@ public class Attr extends JCTree.Visitor { log.error(env.tree.pos(), Errors.EnumTypesNotExtensible); } - if (isSerializable(c.type)) { + if (rs.isSerializable(c.type)) { env.info.isSerializable = true; } @@ -5486,11 +5499,11 @@ public class Attr extends JCTree.Visitor { c.owner.kind != PCK && ((c.flags() & STATIC) == 0 || c.name == names.empty) && (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { - Symbol sym = null; + VarSymbol sym = null; if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; if (sym == null || sym.kind != VAR || - ((VarSymbol) sym).getConstValue() == null) + sym.getConstValue() == null) log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c)); } } @@ -5501,12 +5514,12 @@ public class Attr extends JCTree.Visitor { // Check for cycles among annotation elements. chk.checkNonCyclicElements(tree); - // Check for proper use of serialVersionUID + // Check for proper use of serialVersionUID and other + // serialization-related fields and methods if (env.info.lint.isEnabled(LintCategory.SERIAL) - && isSerializable(c.type) - && (c.flags() & (Flags.ENUM | Flags.INTERFACE)) == 0 + && rs.isSerializable(c.type) && !c.isAnonymous()) { - checkSerialVersionUID(tree, c, env); + chk.checkSerialStructure(tree, c); } if (allowTypeAnnos) { // Correctly organize the positions of the type annotations @@ -5527,59 +5540,6 @@ public class Attr extends JCTree.Visitor { return null; } - /** check if a type is a subtype of Serializable, if that is available. */ - boolean isSerializable(Type t) { - try { - syms.serializableType.complete(); - } - catch (CompletionFailure e) { - return false; - } - return types.isSubtype(t, syms.serializableType); - } - - /** Check that an appropriate serialVersionUID member is defined. */ - private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c, Env env) { - - // check for presence of serialVersionUID - VarSymbol svuid = null; - for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { - if (sym.kind == VAR) { - svuid = (VarSymbol)sym; - break; - } - } - - if (svuid == null) { - if (!c.isRecord()) - log.warning(LintCategory.SERIAL, tree.pos(), Warnings.MissingSVUID(c)); - return; - } - - // Check if @SuppressWarnings("serial") is an annotation of serialVersionUID. - // See JDK-8231622 for more information. - Lint lint = env.info.lint.augment(svuid); - if (lint.isSuppressed(LintCategory.SERIAL)) { - return; - } - - // check that it is static final - if ((svuid.flags() & (STATIC | FINAL)) != - (STATIC | FINAL)) - log.warning(LintCategory.SERIAL, - TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ImproperSVUID(c)); - - // check that it is long - else if (!svuid.type.hasTag(LONG)) - log.warning(LintCategory.SERIAL, - TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.LongSVUID(c)); - - // check constant - else if (svuid.getConstValue() == null) - log.warning(LintCategory.SERIAL, - TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ConstantSVUID(c)); - } - private Type capture(Type type) { return types.capture(type); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java index dc9684827fd7d3d4886405bbe7b0802503440af3..f95be28973f3661576c988c03557abe4bcac63a7 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrRecover.java @@ -193,7 +193,7 @@ public class AttrRecover { attr.new ResultInfo(todo.resultInfo.pkind, todo.resultInfo.pt.getReturnType(), todo.resultInfo.checkContext, todo.resultInfo.checkMode), todo.env, args, pats, todo.resultInfo.pt.getTypeArguments()); - rollback.stream().forEach(Runnable::run); + rollback.forEach(Runnable::run); } else { owntype = basicMethodInvocationRecovery(todo.tree, todo.site, todo.errSym, todo.env, todo.resultInfo); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 55fe5101f61e003c8f44ae905655f640e7ff1caa..55f71a2b8716ffb17879d96d4d11080d6eb78631 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -26,6 +26,7 @@ package com.sun.tools.javac.comp; import java.util.*; +import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -71,6 +72,13 @@ import static com.sun.tools.javac.code.TypeTag.*; import static com.sun.tools.javac.code.TypeTag.WILDCARD; import static com.sun.tools.javac.tree.JCTree.Tag.*; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; +import javax.lang.model.util.ElementKindVisitor14; /** Type checking helper class for the attribution phase. * @@ -4342,4 +4350,693 @@ public class Check { wasNonEmptyFallThrough = c.stats.nonEmpty() && completesNormally; } } + + /** check if a type is a subtype of Externalizable, if that is available. */ + boolean isExternalizable(Type t) { + try { + syms.externalizableType.complete(); + } + catch (CompletionFailure e) { + return false; + } + return types.isSubtype(t, syms.externalizableType); + } + + /** + * Check structure of serialization declarations. + */ + public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) { + (new SerialTypeVisitor()).visit(c, tree); + } + + /** + * This visitor will warn if a serialization-related field or + * method is declared in a suspicious or incorrect way. In + * particular, it will warn for cases where the runtime + * serialization mechanism will silently ignore a mis-declared + * entity. + * + * Distinguished serialization-related fields and methods: + * + * Methods: + * + * private void writeObject(ObjectOutputStream stream) throws IOException + * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException + * + * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException + * private void readObjectNoData() throws ObjectStreamException + * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException + * + * Fields: + * + * private static final long serialVersionUID + * private static final ObjectStreamField[] serialPersistentFields + * + * Externalizable: methods defined on the interface + * public void writeExternal(ObjectOutput) throws IOException + * public void readExternal(ObjectInput) throws IOException + */ + private class SerialTypeVisitor extends ElementKindVisitor14 { + SerialTypeVisitor() { + this.lint = Check.this.lint; + } + + private static final Set serialMethodNames = + Set.of("writeObject", "writeReplace", + "readObject", "readObjectNoData", + "readResolve"); + + private static final Set serialFieldNames = + Set.of("serialVersionUID", "serialPersistentFields"); + + // Type of serialPersistentFields + private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass); + + Lint lint; + + @Override + public Void defaultAction(Element e, JCClassDecl p) { + throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), "")); + } + + @Override + public Void visitType(TypeElement e, JCClassDecl p) { + runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param)); + return null; + } + + @Override + public Void visitTypeAsClass(TypeElement e, + JCClassDecl p) { + // Anonymous classes filtered out by caller. + + ClassSymbol c = (ClassSymbol)e; + + checkCtorAccess(p, c); + + // Check for missing serialVersionUID; check *not* done + // for enums or records. + VarSymbol svuidSym = null; + for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) { + if (sym.kind == VAR) { + svuidSym = (VarSymbol)sym; + break; + } + } + + if (svuidSym == null) { + log.warning(LintCategory.SERIAL, p.pos(), Warnings.MissingSVUID(c)); + } + + // Check for serialPersistentFields to gate checks for + // non-serializable non-transient instance fields + boolean serialPersistentFieldsPresent = + c.members() + .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR) + .iterator() + .hasNext(); + + // Check declarations of serialization-related methods and + // fields + for(Symbol el : c.getEnclosedElements()) { + runUnderLint(el, p, (enclosed, tree) -> { + String name = null; + switch(enclosed.getKind()) { + case FIELD -> { + if (!serialPersistentFieldsPresent) { + var flags = enclosed.flags(); + if ( ((flags & TRANSIENT) == 0) && + ((flags & STATIC) == 0)) { + Type varType = enclosed.asType(); + if (!canBeSerialized(varType)) { + // Note per JLS arrays are + // serializable even if the + // component type is not. + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(enclosed, tree), + Warnings.NonSerializableInstanceField); + } else if (varType.hasTag(ARRAY)) { + ArrayType arrayType = (ArrayType)varType; + Type elementType = arrayType.elemtype; + while (elementType.hasTag(ARRAY)) { + arrayType = (ArrayType)elementType; + elementType = arrayType.elemtype; + } + if (!canBeSerialized(elementType)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(enclosed, tree), + Warnings.NonSerializableInstanceFieldArray(elementType)); + } + } + } + } + + name = enclosed.getSimpleName().toString(); + if (serialFieldNames.contains(name)) { + VarSymbol field = (VarSymbol)enclosed; + switch (name) { + case "serialVersionUID" -> checkSerialVersionUID(tree, e, field); + case "serialPersistentFields" -> checkSerialPersistentFields(tree, e, field); + default -> throw new AssertionError(); + } + } + } + + // Correctly checking the serialization-related + // methods is subtle. For the methods declared to be + // private or directly declared in the class, the + // enclosed elements of the class can be checked in + // turn. However, writeReplace and readResolve can be + // declared in a superclass and inherited. Note that + // the runtime lookup walks the superclass chain + // looking for writeReplace/readResolve via + // Class.getDeclaredMethod. This differs from calling + // Elements.getAllMembers(TypeElement) as the latter + // will also pull in default methods from + // superinterfaces. In other words, the runtime checks + // (which long predate default methods on interfaces) + // do not admit the possibility of inheriting methods + // this way, a difference from general inheritance. + + // The current implementation just checks the enclosed + // elements and does not directly check the inherited + // methods. If all the types are being checked this is + // less of a concern; however, there are cases that + // could be missed. In particular, readResolve and + // writeReplace could, in principle, by inherited from + // a non-serializable superclass and thus not checked + // even if compiled with a serializable child class. + case METHOD -> { + var method = (MethodSymbol)enclosed; + name = method.getSimpleName().toString(); + if (serialMethodNames.contains(name)) { + switch (name) { + case "writeObject" -> checkWriteObject(tree, e, method); + case "writeReplace" -> checkWriteReplace(tree,e, method); + case "readObject" -> checkReadObject(tree,e, method); + case "readObjectNoData" -> checkReadObjectNoData(tree, e, method); + case "readResolve" -> checkReadResolve(tree, e, method); + default -> throw new AssertionError(); + } + } + } + } + }); + } + + return null; + } + + boolean canBeSerialized(Type type) { + return type.isPrimitive() || rs.isSerializable(type); + } + + /** + * Check that Externalizable class needs a public no-arg + * constructor. + * + * Check that a Serializable class has access to the no-arg + * constructor of its first nonserializable superclass. + */ + private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) { + if (isExternalizable(c.type)) { + for(var sym : c.getEnclosedElements()) { + if (sym.isConstructor() && + ((sym.flags() & PUBLIC) == PUBLIC)) { + if (((MethodSymbol)sym).getParameters().isEmpty()) { + return; + } + } + } + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.ExternalizableMissingPublicNoArgCtor); + } else { + // Approximate access to the no-arg constructor up in + // the superclass chain by checking that the + // constructor is not private. This may not handle + // some cross-package situations correctly. + Type superClass = c.getSuperclass(); + // java.lang.Object is *not* Serializable so this loop + // should terminate. + while (rs.isSerializable(superClass) ) { + try { + superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass(); + } catch(ClassCastException cce) { + return ; // Don't try to recover + } + } + // Non-Serializable super class + try { + ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement())); + for(var sym : supertype.getEnclosedElements()) { + if (sym.isConstructor()) { + MethodSymbol ctor = (MethodSymbol)sym; + if (ctor.getParameters().isEmpty()) { + if (((ctor.flags() & PRIVATE) == PRIVATE) || + // Handle nested classes and implicit this$0 + (supertype.getNestingKind() == NestingKind.MEMBER && + ((supertype.flags() & STATIC) == 0))) + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName())); + } + } + } + } catch (ClassCastException cce) { + return ; // Don't try to recover + } + return; + } + } + + private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) { + // To be effective, serialVersionUID must be marked static + // and final, but private is recommended. But alas, in + // practice there are many non-private serialVersionUID + // fields. + if ((svuid.flags() & (STATIC | FINAL)) != + (STATIC | FINAL)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(svuid, tree), + Warnings.ImproperSVUID((Symbol)e)); + } + + // check svuid has type long + if (!svuid.type.hasTag(LONG)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(svuid, tree), + Warnings.LongSVUID((Symbol)e)); + } + + if (svuid.getConstValue() == null) + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(svuid, tree), + Warnings.ConstantSVUID((Symbol)e)); + } + + private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) { + // To be effective, serialPersisentFields must be private, static, and final. + if ((spf.flags() & (PRIVATE | STATIC | FINAL)) != + (PRIVATE | STATIC | FINAL)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(spf, tree), Warnings.ImproperSPF); + } + + if (!types.isSameType(spf.type, OSF_TYPE)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(spf, tree), Warnings.OSFArraySPF); + } + + if (isExternalizable((Type)(e.asType()))) { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialFieldExternalizable); + } + + // Warn if serialPersistentFields is initialized to a + // literal null. + JCTree spfDecl = TreeInfo.declarationFor(spf, tree); + if (spfDecl != null && spfDecl.getTag() == VARDEF) { + JCVariableDecl variableDef = (JCVariableDecl) spfDecl; + JCExpression initExpr = variableDef.init; + if (initExpr != null && TreeInfo.isNull(initExpr)) { + log.warning(LintCategory.SERIAL, initExpr.pos(), + Warnings.SPFNullInit); + } + } + } + + private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) { + // The "synchronized" modifier is seen in the wild on + // readObject and writeObject methods and is generally + // innocuous. + + // private void writeObject(ObjectOutputStream stream) throws IOException + checkPrivateNonStaticMethod(tree, method); + checkReturnType(tree, e, method, syms.voidType); + checkOneArg(tree, e, method, syms.objectOutputStreamType); + checkExceptions(tree, e, method, syms.ioExceptionType); + checkExternalizable(tree, e, method); + } + + private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) { + // ANY-ACCESS-MODIFIER Object writeReplace() throws + // ObjectStreamException + + // Excluding abstract, could have a more complicated + // rule based on abstract-ness of the class + checkConcreteInstanceMethod(tree, e, method); + checkReturnType(tree, e, method, syms.objectType); + checkNoArgs(tree, e, method); + checkExceptions(tree, e, method, syms.objectStreamExceptionType); + } + + private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) { + // The "synchronized" modifier is seen in the wild on + // readObject and writeObject methods and is generally + // innocuous. + + // private void readObject(ObjectInputStream stream) + // throws IOException, ClassNotFoundException + checkPrivateNonStaticMethod(tree, method); + checkReturnType(tree, e, method, syms.voidType); + checkOneArg(tree, e, method, syms.objectInputStreamType); + checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType); + checkExternalizable(tree, e, method); + } + + private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) { + // private void readObjectNoData() throws ObjectStreamException + checkPrivateNonStaticMethod(tree, method); + checkReturnType(tree, e, method, syms.voidType); + checkNoArgs(tree, e, method); + checkExceptions(tree, e, method, syms.objectStreamExceptionType); + checkExternalizable(tree, e, method); + } + + private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) { + // ANY-ACCESS-MODIFIER Object readResolve() + // throws ObjectStreamException + + // Excluding abstract, could have a more complicated + // rule based on abstract-ness of the class + checkConcreteInstanceMethod(tree, e, method); + checkReturnType(tree,e, method, syms.objectType); + checkNoArgs(tree, e, method); + checkExceptions(tree, e, method, syms.objectStreamExceptionType); + } + + void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) { + var flags = method.flags(); + if ((flags & PRIVATE) == 0) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodNotPrivate(method.getSimpleName())); + } + + if ((flags & STATIC) != 0) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodStatic(method.getSimpleName())); + } + } + + /** + * Per section 1.12 "Serialization of Enum Constants" of + * the serialization specification, due to the special + * serialization handling of enums, any writeObject, + * readObject, writeReplace, and readResolve methods are + * ignored as are serialPersistentFields and + * serialVersionUID fields. + */ + @Override + public Void visitTypeAsEnum(TypeElement e, + JCClassDecl p) { + for(Element el : e.getEnclosedElements()) { + runUnderLint(el, p, (enclosed, tree) -> { + String name = enclosed.getSimpleName().toString(); + switch(enclosed.getKind()) { + case FIELD -> { + if (serialFieldNames.contains(name)) { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialFieldEnum(name)); + } + } + + case METHOD -> { + if (serialMethodNames.contains(name)) { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialMethodEnum(name)); + } + } + } + }); + } + return null; + } + + /** + * Most serialization-related fields and methods on interfaces + * are ineffectual or problematic. + */ + @Override + public Void visitTypeAsInterface(TypeElement e, + JCClassDecl p) { + for(Element el : e.getEnclosedElements()) { + runUnderLint(el, p, (enclosed, tree) -> { + String name = null; + switch(enclosed.getKind()) { + case FIELD -> { + var field = (VarSymbol)enclosed; + name = field.getSimpleName().toString(); + switch(name) { + case "serialPersistentFields" -> { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(field, tree), + Warnings.IneffectualSerialFieldInterface); + } + + case "serialVersionUID" -> { + checkSerialVersionUID(tree, e, field); + } + } + } + + case METHOD -> { + var method = (MethodSymbol)enclosed; + name = enclosed.getSimpleName().toString(); + if (serialMethodNames.contains(name)) { + switch (name) { + case + "readObject", + "readObjectNoData", + "writeObject" -> checkPrivateMethod(tree, e, method); + + case + "writeReplace", + "readResolve" -> checkDefaultIneffective(tree, e, method); + + default -> throw new AssertionError(); + } + + } + } + } + }); + } + + return null; + } + + private void checkPrivateMethod(JCClassDecl tree, + Element e, + MethodSymbol method) { + if ((method.flags() & PRIVATE) == 0) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.NonPrivateMethodWeakerAccess); + } + } + + private void checkDefaultIneffective(JCClassDecl tree, + Element e, + MethodSymbol method) { + if ((method.flags() & DEFAULT) == DEFAULT) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.DefaultIneffective); + + } + } + + @Override + public Void visitTypeAsAnnotationType(TypeElement e, + JCClassDecl p) { + // Per the JLS, annotation types are not serializeable + return null; + } + + /** + * From the Java Object Serialization Specification, 1.13 + * Serialization of Records: + * + * "The process by which record objects are serialized or + * externalized cannot be customized; any class-specific + * writeObject, readObject, readObjectNoData, writeExternal, + * and readExternal methods defined by record classes are + * ignored during serialization and deserialization. However, + * a substitute object to be serialized or a designate + * replacement may be specified, by the writeReplace and + * readResolve methods, respectively. Any + * serialPersistentFields field declaration is + * ignored. Documenting serializable fields and data for + * record classes is unnecessary, since there is no variation + * in the serial form, other than whether a substitute or + * replacement object is used. The serialVersionUID of a + * record class is 0L unless explicitly declared. The + * requirement for matching serialVersionUID values is waived + * for record classes." + */ + @Override + public Void visitTypeAsRecord(TypeElement e, + JCClassDecl p) { + for(Element el : e.getEnclosedElements()) { + runUnderLint(el, p, (enclosed, tree) -> { + String name = enclosed.getSimpleName().toString(); + switch(enclosed.getKind()) { + case FIELD -> { + switch(name) { + case "serialPersistentFields" -> { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialFieldRecord); + } + + case "serialVersionUID" -> { + // Could generate additional warning that + // svuid value is not checked to match for + // records. + checkSerialVersionUID(tree, e, (VarSymbol)enclosed); + } + + } + } + + case METHOD -> { + var method = (MethodSymbol)enclosed; + switch(name) { + case "writeReplace" -> checkWriteReplace(tree, e, method); + case "readResolve" -> checkReadResolve(tree, e, method); + default -> { + if (serialMethodNames.contains(name)) { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialMethodRecord(name)); + } + } + } + + } + } + }); + } + return null; + } + + void checkConcreteInstanceMethod(JCClassDecl tree, + Element enclosing, + MethodSymbol method) { + if ((method.flags() & (STATIC | ABSTRACT)) != 0) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialConcreteInstanceMethod(method.getSimpleName())); + } + } + + private void checkReturnType(JCClassDecl tree, + Element enclosing, + MethodSymbol method, + Type expectedReturnType) { + // Note: there may be complications checking writeReplace + // and readResolve since they return Object and could, in + // principle, have covariant overrides and any synthetic + // bridge method would not be represented here for + // checking. + Type rtype = method.getReturnType(); + if (!types.isSameType(expectedReturnType, rtype)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(), + rtype, expectedReturnType)); + } + } + + private void checkOneArg(JCClassDecl tree, + Element enclosing, + MethodSymbol method, + Type expectedType) { + String name = method.getSimpleName().toString(); + + var parameters= method.getParameters(); + + if (parameters.size() != 1) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size())); + return; + } + + Type parameterType = parameters.get(0).asType(); + if (!types.isSameType(parameterType, expectedType)) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodParameterType(method.getSimpleName(), + expectedType, + parameterType)); + } + } + + private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) { + var parameters = method.getParameters(); + if (!parameters.isEmpty()) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(parameters.get(0), tree), + Warnings.SerialMethodNoArgs(method.getSimpleName())); + } + } + + private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) { + // If the enclosing class is externalizable, warn for the method + if (isExternalizable((Type)enclosing.asType())) { + log.warning(LintCategory.SERIAL, tree.pos(), + Warnings.IneffectualSerialMethodExternalizable(method.getSimpleName())); + } + return; + } + + private void checkExceptions(JCClassDecl tree, + Element enclosing, + MethodSymbol method, + Type... declaredExceptions) { + for (Type thrownType: method.getThrownTypes()) { + // For each exception in the throws clause of the + // method, if not an Error and not a RuntimeException, + // check if the exception is a subtype of a declared + // exception from the throws clause of the + // serialization method in question. + if (types.isSubtype(thrownType, syms.runtimeExceptionType) || + types.isSubtype(thrownType, syms.errorType) ) { + continue; + } else { + boolean declared = false; + for (Type declaredException : declaredExceptions) { + if (types.isSubtype(thrownType, declaredException)) { + declared = true; + continue; + } + } + if (!declared) { + log.warning(LintCategory.SERIAL, + TreeInfo.diagnosticPositionFor(method, tree), + Warnings.SerialMethodUnexpectedException(method.getSimpleName(), + thrownType)); + } + } + } + return; + } + + private Void runUnderLint(E symbol, JCClassDecl p, BiConsumer task) { + Lint prevLint = lint; + try { + lint = lint.augment((Symbol) symbol); + + if (lint.isEnabled(LintCategory.SERIAL)) { + task.accept(symbol, p); + } + + return null; + } finally { + lint = prevLint; + } + } + + } + } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java index 0fd0ea7858e636647f49e27954f80d4d4285da78..5cf8c5d5387f733eb2209ebc772fd6333721a88c 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -376,7 +376,7 @@ public class Enter extends JCTree.Visitor { Name name = names.package_info; ClassSymbol c = syms.enterClass(tree.modle, name, tree.packge); c.flatname = names.fromString(tree.packge + "." + name); - c.sourcefile = tree.sourcefile; + c.classfile = c.sourcefile = tree.sourcefile; c.completer = Completer.NULL_COMPLETER; c.members_field = WriteableScope.create(c); tree.packge.package_info = c; @@ -495,7 +495,7 @@ public class Enter extends JCTree.Visitor { // Fill out class fields. c.completer = Completer.NULL_COMPLETER; // do not allow the initial completer linger on. c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree); - c.sourcefile = env.toplevel.sourcefile; + c.classfile = c.sourcefile = env.toplevel.sourcefile; c.members_field = WriteableScope.create(c); c.clearAnnotationMetadata(); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java index d14756759b7ac744d734ef8d4bad4c320fce50bd..1346d141bb76740e6d3b0be4712b061cfedf9ce5 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java @@ -207,7 +207,6 @@ public class Flow { private final JCDiagnostic.Factory diags; private Env attrEnv; private Lint lint; - private final DeferredCompletionFailureHandler dcfh; private final boolean allowEffectivelyFinalInInnerClasses; public static Flow instance(Context context) { @@ -332,7 +331,6 @@ public class Flow { lint = Lint.instance(context); rs = Resolve.instance(context); diags = JCDiagnostic.Factory.instance(context); - dcfh = DeferredCompletionFailureHandler.instance(context); Source source = Source.instance(context); allowEffectivelyFinalInInnerClasses = Feature.EFFECTIVELY_FINAL_IN_INNER_CLASSES.allowedInSource(source); } @@ -341,7 +339,7 @@ public class Flow { * Base visitor class for all visitors implementing dataflow analysis logic. * This class define the shared logic for handling jumps (break/continue statements). */ - static abstract class BaseAnalyzer extends TreeScanner { + abstract static class BaseAnalyzer extends TreeScanner { enum JumpKind { BREAK(JCTree.Tag.BREAK) { @@ -693,7 +691,7 @@ public class Flow { } if (!tree.hasTotalPattern && exhaustiveSwitch && !TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases) && - (constants == null || !isExhaustive(tree.selector.type, constants))) { + (constants == null || !isExhaustive(tree.selector.pos(), tree.selector.type, constants))) { log.error(tree, Errors.NotExhaustiveStatement); } if (!tree.hasTotalPattern) { @@ -728,7 +726,7 @@ public class Flow { } } if (!tree.hasTotalPattern && !TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases) && - !isExhaustive(tree.selector.type, constants)) { + !isExhaustive(tree.selector.pos(), tree.selector.type, constants)) { log.error(tree, Errors.NotExhaustive); } alive = prevAlive; @@ -751,7 +749,7 @@ public class Flow { } } - private void transitiveCovers(Set covered) { + private void transitiveCovers(DiagnosticPosition pos, Type seltype, Set covered) { List todo = List.from(covered); while (todo.nonEmpty()) { Symbol sym = todo.head; @@ -773,7 +771,7 @@ public class Flow { case TYP -> { for (Type sup : types.directSupertypes(sym.type)) { if (sup.tsym.kind == TYP) { - if (isTransitivelyCovered(sup.tsym, covered) && + if (isTransitivelyCovered(pos, seltype, sup.tsym, covered) && covered.add(sup.tsym)) { todo = todo.prepend(sup.tsym); } @@ -784,39 +782,41 @@ public class Flow { } } - private boolean isTransitivelyCovered(Symbol sealed, Set covered) { - DeferredCompletionFailureHandler.Handler prevHandler = - dcfh.setHandler(dcfh.speculativeCodeHandler); + private boolean isTransitivelyCovered(DiagnosticPosition pos, Type seltype, + Symbol sealed, Set covered) { try { if (covered.stream().anyMatch(c -> sealed.isSubClass(c, types))) return true; if (sealed.kind == TYP && sealed.isAbstract() && sealed.isSealed()) { return ((ClassSymbol) sealed).permitted .stream() - .allMatch(s -> isTransitivelyCovered(s, covered)); + .filter(s -> { + return types.isCastable(seltype, s.type/*, types.noWarnings*/); + }) + .allMatch(s -> isTransitivelyCovered(pos, seltype, s, covered)); } return false; } catch (CompletionFailure cf) { - //safe to ignore, the symbol will be un-completed when the speculative handler is removed. - return false; - } finally { - dcfh.setHandler(prevHandler); + chk.completionError(pos, cf); + return true; } } - private boolean isExhaustive(Type seltype, Set covered) { - transitiveCovers(covered); + private boolean isExhaustive(DiagnosticPosition pos, Type seltype, Set covered) { + transitiveCovers(pos, seltype, covered); return switch (seltype.getTag()) { case CLASS -> { if (seltype.isCompound()) { if (seltype.isIntersection()) { - yield ((Type.IntersectionClassType) seltype).getComponents().stream().anyMatch(t -> isExhaustive(t, covered)); + yield ((Type.IntersectionClassType) seltype).getComponents() + .stream() + .anyMatch(t -> isExhaustive(pos, t, covered)); } yield false; } yield covered.contains(seltype.tsym); } - case TYPEVAR -> isExhaustive(((TypeVar) seltype).getUpperBound(), covered); + case TYPEVAR -> isExhaustive(pos, ((TypeVar) seltype).getUpperBound(), covered); default -> false; }; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java index 94d95069c03060d10294e1b827ce1b0dc222a418..d88b36abcdbf1f559ca7c65396a97fd0e5d65294 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/InferenceContext.java @@ -28,7 +28,6 @@ package com.sun.tools.javac.comp; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; @@ -393,7 +392,7 @@ public class InferenceContext { Map> minMap = new LinkedHashMap<>(); void scan(List roots) { - roots.stream().forEach(this::visit); + roots.forEach(this::visit); } @Override diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java index c48ac804ac850c5ec34b53eaa4a19454cd25763e..0638da66a8969191b572a18375af6bee01790718 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java @@ -165,9 +165,14 @@ public class LambdaToMethod extends TreeTranslator { dumpLambdaToMethodStats = options.isSet("debug.dumpLambdaToMethodStats"); attr = Attr.instance(context); forceSerializable = options.isSet("forceSerializable"); - debugLinesOrVars = options.isSet(Option.G) - || options.isSet(Option.G_CUSTOM, "lines") - || options.isSet(Option.G_CUSTOM, "vars"); + boolean lineDebugInfo = + options.isUnset(Option.G_CUSTOM) || + options.isSet(Option.G_CUSTOM, "lines"); + boolean varDebugInfo = + options.isUnset(Option.G_CUSTOM) + ? options.isSet(Option.G) + : options.isSet(Option.G_CUSTOM, "vars"); + debugLinesOrVars = lineDebugInfo || varDebugInfo; verboseDeduplication = options.isSet("debug.dumpLambdaToMethodDeduplication"); deduplicateLambdas = options.getBoolean("deduplicateLambdas", true); nestmateLambdas = Target.instance(context).runtimeUseNestAccess(); @@ -424,14 +429,14 @@ public class LambdaToMethod extends TreeTranslator { //add captured locals for (Symbol fv : localContext.getSymbolMap(CAPTURED_VAR).keySet()) { if (fv != localContext.self) { - JCTree captured_local = make.Ident(fv).setType(fv.type); - syntheticInits.append((JCExpression) captured_local); + JCExpression captured_local = make.Ident(fv).setType(fv.type); + syntheticInits.append(captured_local); } } // add captured outer this instances (used only when `this' capture itself is illegal) for (Symbol fv : localContext.getSymbolMap(CAPTURED_OUTER_THIS).keySet()) { - JCTree captured_local = make.QualThis(fv.type); - syntheticInits.append((JCExpression) captured_local); + JCExpression captured_local = make.QualThis(fv.type); + syntheticInits.append(captured_local); } //then, determine the arguments to the indy call @@ -1184,13 +1189,13 @@ public class LambdaToMethod extends TreeTranslator { syms.stringType, syms.methodTypeType).appendList(staticArgs.map(types::constantType)); - Symbol bsm = rs.resolveInternalMethod(pos, attrEnv, site, + MethodSymbol bsm = rs.resolveInternalMethod(pos, attrEnv, site, bsmName, bsm_staticArgs, List.nil()); DynamicMethodSymbol dynSym = new DynamicMethodSymbol(methName, syms.noSymbol, - ((MethodSymbol)bsm).asHandle(), + bsm.asHandle(), indyType, staticArgs.toArray(new LoadableConstant[staticArgs.length()])); JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), bsmName); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java index dd9f550771852c979c34c3aec1b4a3313cd9ab39..7b2ccb7f426b5ca098b4db158b045d1474a0244f 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java @@ -98,6 +98,7 @@ public class Lower extends TreeTranslator { private final boolean debugLower; private final boolean disableProtectedAccessors; // experimental private final PkgInfo pkginfoOpt; + private final boolean optimizeOuterThis; protected Lower(Context context) { context.put(lowerKey, this); @@ -119,6 +120,9 @@ public class Lower extends TreeTranslator { Options options = Options.instance(context); debugLower = options.isSet("debuglower"); pkginfoOpt = PkgInfo.get(options); + optimizeOuterThis = + target.optimizeOuterThis() || + options.getBoolean("optimizeOuterThis", false); disableProtectedAccessors = options.isSet("disableProtectedAccessors"); } @@ -1480,8 +1484,12 @@ public class Lower extends TreeTranslator { private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) { Type target = types.erasure(owner.enclClass().type.getEnclosingType()); + // Set NOOUTERTHIS for all synthetic outer instance variables, and unset + // it when the variable is accessed. If the variable is never accessed, + // we skip creating an outer instance field and saving the constructor + // parameter to it. VarSymbol outerThis = - new VarSymbol(flags, outerThisName(target, owner), target, owner); + new VarSymbol(flags | NOOUTERTHIS, outerThisName(target, owner), target, owner); outerThisStack = outerThisStack.prepend(outerThis); return outerThis; } @@ -1728,6 +1736,7 @@ public class Lower extends TreeTranslator { } VarSymbol ot = ots.head; JCExpression tree = access(make.at(pos).Ident(ot)); + ot.flags_field &= ~NOOUTERTHIS; TypeSymbol otc = ot.type.tsym; while (otc != c) { do { @@ -1745,6 +1754,7 @@ public class Lower extends TreeTranslator { return makeNull(); } tree = access(make.at(pos).Select(tree, ot)); + ot.flags_field &= ~NOOUTERTHIS; otc = ot.type.tsym; } return tree; @@ -1784,6 +1794,7 @@ public class Lower extends TreeTranslator { } VarSymbol ot = ots.head; JCExpression tree = access(make.at(pos).Ident(ot)); + ot.flags_field &= ~NOOUTERTHIS; TypeSymbol otc = ot.type.tsym; while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) { do { @@ -1796,6 +1807,7 @@ public class Lower extends TreeTranslator { ot = ots.head; } while (ot.owner != otc); tree = access(make.at(pos).Select(tree, ot)); + ot.flags_field &= ~NOOUTERTHIS; otc = ot.type.tsym; } return tree; @@ -1817,10 +1829,9 @@ public class Lower extends TreeTranslator { /** Return tree simulating the assignment {@code this.this$n = this$n}. */ - JCStatement initOuterThis(int pos) { - VarSymbol rhs = outerThisStack.head; + JCStatement initOuterThis(int pos, VarSymbol rhs) { Assert.check(rhs.owner.kind == MTH); - VarSymbol lhs = outerThisStack.tail.head; + VarSymbol lhs = outerThisStack.head; Assert.check(rhs.owner.owner == lhs.owner); make.at(pos); return @@ -2224,15 +2235,25 @@ public class Lower extends TreeTranslator { // Convert name to flat representation, replacing '.' by '$'. tree.name = Convert.shortName(currentClass.flatName()); - // Add this$n and free variables proxy definitions to class. + // Add free variables proxy definitions to class. for (List l = fvdefs; l.nonEmpty(); l = l.tail) { tree.defs = tree.defs.prepend(l.head); enterSynthetic(tree.pos(), l.head.sym, currentClass.members()); } - if (currentClass.hasOuterInstance()) { + // If this$n was accessed, add the field definition and + // update initial constructors to initialize it + if (currentClass.hasOuterInstance() && shouldEmitOuterThis(currentClass)) { tree.defs = tree.defs.prepend(otdef); enterSynthetic(tree.pos(), otdef.sym, currentClass.members()); + + for (JCTree def : tree.defs) { + if (TreeInfo.isInitialConstructor(def)) { + JCMethodDecl mdef = (JCMethodDecl) def; + mdef.body.stats = mdef.body.stats.prepend( + initOuterThis(mdef.body.pos, mdef.params.head.sym)); + } + } } proxies = prevProxies; @@ -2249,6 +2270,22 @@ public class Lower extends TreeTranslator { result = make_at(tree.pos()).Block(SYNTHETIC, List.nil()); } + private boolean shouldEmitOuterThis(ClassSymbol sym) { + if (!optimizeOuterThis) { + // Optimization is disabled + return true; + } + if ((outerThisStack.head.flags_field & NOOUTERTHIS) == 0) { + // Enclosing instance field is used + return true; + } + if (rs.isSerializable(sym.type)) { + // Class is serializable + return true; + } + return false; + } + List generateMandatedAccessors(JCClassDecl tree) { List fields = TreeInfo.recordFields(tree); return tree.sym.getRecordComponents().stream() @@ -2315,7 +2352,7 @@ public class Lower extends TreeTranslator { enumDefs.append(make.VarDef(valuesVar, make.App(make.QualIdent(valuesMethod)))); tree.sym.members().enter(valuesVar); - Symbol valuesSym = lookupMethod(tree.pos(), names.values, + MethodSymbol valuesSym = lookupMethod(tree.pos(), names.values, tree.type, List.nil()); List valuesBody; if (useClone()) { @@ -2366,7 +2403,7 @@ public class Lower extends TreeTranslator { } JCMethodDecl valuesDef = - make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody)); + make.MethodDef(valuesSym, make.Block(0, valuesBody)); enumDefs.append(valuesDef); @@ -2581,7 +2618,7 @@ public class Lower extends TreeTranslator { Name bootstrapName, Name argName, boolean isStatic) { - Symbol bsm = rs.resolveInternalMethod(tree.pos(), attrEnv, site, + MethodSymbol bsm = rs.resolveInternalMethod(tree.pos(), attrEnv, site, bootstrapName, staticArgTypes, List.nil()); MethodType indyType = msym.type.asMethodType(); @@ -2593,7 +2630,7 @@ public class Lower extends TreeTranslator { ); DynamicMethodSymbol dynSym = new DynamicMethodSymbol(argName, syms.noSymbol, - ((MethodSymbol)bsm).asHandle(), + bsm.asHandle(), indyType, staticArgValues); JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), argName); @@ -2703,11 +2740,6 @@ public class Lower extends TreeTranslator { olderasure.getThrownTypes(), syms.methodClass); } - if (currentClass.hasOuterInstance() && - TreeInfo.isInitialConstructor(tree)) - { - added = added.prepend(initOuterThis(tree.body.pos)); - } // pop local variables from proxy stack proxies = prevProxies; diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java index e88f46c297ea8194b0fabc1b29c808a993273bef..6197e9fd22e4c250041d9c9609c4e95bdf9a238f 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java @@ -329,7 +329,7 @@ public class Modules extends JCTree.Visitor { } } sym.completer = getSourceCompleter(toplevel); - sym.module_info.sourcefile = toplevel.sourcefile; + sym.module_info.classfile = sym.module_info.sourcefile = toplevel.sourcefile; decl.sym = sym; if (multiModuleMode || modules.isEmpty()) { diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java index a9d47bf7ca7d85cd5f4aeccd088e9469f1167e54..7c912dcc877cd1f069c625d4211046bcef00748b 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java @@ -1301,7 +1301,7 @@ public class Resolve { @Override void skip(JCTree tree) { - result &= false; + result = false; } @Override @@ -1313,9 +1313,9 @@ public class Resolve { @Override public void visitReference(JCMemberReference tree) { if (sRet.hasTag(VOID)) { - result &= true; + // do nothing } else if (tRet.hasTag(VOID)) { - result &= false; + result = false; } else if (tRet.isPrimitive() != sRet.isPrimitive()) { boolean retValIsPrimitive = tree.refPolyKind == PolyKind.STANDALONE && @@ -1335,9 +1335,9 @@ public class Resolve { @Override public void visitLambda(JCLambda tree) { if (sRet.hasTag(VOID)) { - result &= true; + // do nothing } else if (tRet.hasTag(VOID)) { - result &= false; + result = false; } else { List lambdaResults = lambdaResults(tree); if (!lambdaResults.isEmpty() && unrelatedFunctionalInterfaces(tRet, sRet)) { @@ -2942,9 +2942,6 @@ public class Resolve { sym.kind != WRONG_MTHS) { sym = super.access(env, pos, location, sym); } else { - final JCDiagnostic details = sym.kind == WRONG_MTH ? - ((InapplicableSymbolError)sym.baseSymbol()).errCandidate().snd : - null; sym = new DiamondError(sym, currentResolutionContext); sym = accessMethod(sym, pos, site, names.init, true, argtypes, typeargtypes); env.info.pendingResolutionPhase = currentResolutionContext.step; @@ -3908,6 +3905,17 @@ public class Resolve { } } + /** check if a type is a subtype of Serializable, if that is available.*/ + boolean isSerializable(Type t) { + try { + syms.serializableType.complete(); + } + catch (CompletionFailure e) { + return false; + } + return types.isSubtype(t, syms.serializableType); + } + /** * Root class for resolution errors. Subclass of ResolveError * represent a different kinds of resolution error - as such they must diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java index fda59d6ddaadfe5c6ffd0e505e9b339e10e1ed70..56fdc73e02e6da351dc1019a00b2f4c2cce06328 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TransPatterns.java @@ -347,8 +347,9 @@ public class TransPatterns extends TreeTranslator { } } selector = translate(selector); - statements.append(make.at(tree.pos).VarDef(temp, !hasNullCase ? attr.makeNullCheck(selector) - : selector)); + boolean needsNullCheck = !hasNullCase && !seltype.isPrimitive(); + statements.append(make.at(tree.pos).VarDef(temp, needsNullCheck ? attr.makeNullCheck(selector) + : selector)); VarSymbol index = new VarSymbol(Flags.SYNTHETIC, names.fromString(tree.pos + target.syntheticNameChar() + "index"), syms.intType, @@ -371,7 +372,7 @@ public class TransPatterns extends TreeTranslator { boolean enumSelector = seltype.tsym.isEnum(); Name bootstrapName = enumSelector ? names.enumSwitch : names.typeSwitch; - Symbol bsm = rs.resolveInternalMethod(tree.pos(), env, syms.switchBootstrapsType, + MethodSymbol bsm = rs.resolveInternalMethod(tree.pos(), env, syms.switchBootstrapsType, bootstrapName, staticArgTypes, List.nil()); MethodType indyType = new MethodType( @@ -382,7 +383,7 @@ public class TransPatterns extends TreeTranslator { ); DynamicMethodSymbol dynSym = new DynamicMethodSymbol(bootstrapName, syms.noSymbol, - ((MethodSymbol)bsm).asHandle(), + bsm.asHandle(), indyType, staticArgValues); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java index b94c52cc6d610b76bf39a87a19defbaa3645f9ef..3a763cbe0343617aaef9b30968db4161680c8b0c 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java @@ -356,8 +356,10 @@ public class TypeEnter implements Completer { // Import-on-demand java.lang. PackageSymbol javaLang = syms.enterPackage(syms.java_base, names.java_lang); - if (javaLang.members().isEmpty() && !javaLang.exists()) - throw new FatalError(diags.fragment(Fragments.FatalErrNoJavaLang)); + if (javaLang.members().isEmpty() && !javaLang.exists()) { + log.error(Errors.NoJavaLang); + throw new Abort(); + } importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env); JCModuleDecl decl = tree.getModuleDecl(); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JRTIndex.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JRTIndex.java index cc1568ad7da3527b58a0274b1fd3e8735d5e8de0..eb6cd76d7889221cbdd3efae8818a2fb4cb8a1ec 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JRTIndex.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JRTIndex.java @@ -56,7 +56,7 @@ import com.sun.tools.javac.util.Context; public class JRTIndex { /** Get a shared instance of the cache. */ private static JRTIndex sharedInstance; - public synchronized static JRTIndex getSharedInstance() { + public static synchronized JRTIndex getSharedInstance() { if (sharedInstance == null) { try { sharedInstance = new JRTIndex(); diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java index c539c72d6276220dc0269cdfc3797687f0e14059..f64f19c305495d015202a1ad5e877e2cd5641704 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java @@ -444,7 +444,7 @@ public class Locations { * @see #initHandlers * @see #getHandler */ - protected static abstract class LocationHandler { + protected abstract static class LocationHandler { /** * @see JavaFileManager#handleOption @@ -513,7 +513,7 @@ public class Locations { /** * A LocationHandler for a given Location, and associated set of options. */ - private static abstract class BasicLocationHandler extends LocationHandler { + private abstract static class BasicLocationHandler extends LocationHandler { final Location location; final Set