├── .gitignore ├── .java-version ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java ├── io │ └── vproxy │ │ └── jdkman │ │ ├── Main.java │ │ ├── action │ │ ├── Action.java │ │ ├── AddAction.java │ │ ├── DefaultAction.java │ │ ├── InitAction.java │ │ ├── ListAction.java │ │ ├── RefreshAction.java │ │ ├── RemoveAction.java │ │ └── WhichAction.java │ │ ├── entity │ │ ├── JDKInfo.java │ │ ├── JDKInfoMatcher.java │ │ ├── JDKManConfig.java │ │ └── MatchOptions.java │ │ ├── ex │ │ └── ErrorResult.java │ │ ├── res │ │ ├── Feature.java │ │ └── ResConsts.java │ │ └── util │ │ ├── CommentLogHandler.java │ │ └── Utils.java └── module-info.java ├── resources └── io │ └── vproxy │ └── jdkman │ └── res │ └── jdkman_proxy-windows-x86_64.exe └── rust ├── Cargo.lock ├── Cargo.toml └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/ 9 | *.iws 10 | *.iml 11 | *.ipr 12 | out/ 13 | !**/src/main/**/out/ 14 | !**/src/test/**/out/ 15 | 16 | ### Eclipse ### 17 | .apt_generated 18 | .classpath 19 | .factorypath 20 | .project 21 | .settings 22 | .springBeans 23 | .sts4-cache 24 | bin/ 25 | !**/src/main/**/bin/ 26 | !**/src/test/**/bin/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ 37 | 38 | ### Mac OS ### 39 | .DS_Store 40 | 41 | ### Build Output ### 42 | /jdkman 43 | /jdkman-linux 44 | /jdkman.exe 45 | !/src/main/java/io/vproxy/jdkman/res/jdkman_proxy-windows-x86_64.exe 46 | 47 | ### Rust ### 48 | src/main/rust/target 49 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 21 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jdkman 2 | 3 | ## What is `jdkman` 4 | 5 | `jdkman` is a command line tool which helps you manage multiple JDK instances. 6 | 7 | [An asciinema cast](https://asciinema.org/a/625934) shows how to use `jdkman`. 8 | [This video](https://www.bilibili.com/video/BV1Gu4y137cg/) shows how to configure `jdkman` on Windows. 9 | 10 | ## How to install 11 | 12 | ### 1. Download 13 | 14 | Download the pre-built binary from the [release page](https://github.com/wkgcass/jdkman/releases). 15 | You will need to download the binary corresponding to your operating system and cpu architecture. 16 | 17 | Rename the downloaded file `jdkman-$os-$arch` to `jdkman` 18 | You will also need to run `chmod +x jdkman` on Linux or macOS. 19 | 20 | ### 2. Configure 21 | 22 | #### bash or zsh 23 | 24 | Add the following lines in your `~/.bashrc` or `~/.bash_profile` or `~/.zshrc` 25 | 26 | ```shell 27 | ## add jdkman to your PATH environment variable. 28 | export PATH="$PATH:/path/to/jdkman" 29 | eval "`jdkman init sh`" 30 | ``` 31 | 32 | #### Powershell 33 | 34 | Add `\path\to\jdkman` to your PATH environment variable. 35 | 36 | Then configure the profile script by entering the following lines in powershell: 37 | 38 | ```powershell 39 | echo $profile ## show the profile script location 40 | New-Item -ItemType Directory -Path (Split-Path $profile) -Force 41 | 'Invoke-Expression -Command (jdkman init pwsh)' | Out-File -FilePath $profile -Append 42 | ``` 43 | 44 | #### Windows cmd 45 | 46 | Since cmd doesn't support `eval` nor `source`, there's very little that `jdkman` could provide. 47 | 48 | Add `\path\to\jdkman` to your PATH environment variable. 49 | Add `\YourHomePath\jdkman-scripts` to your PATH environment variable. 50 | 51 | Then in cmd, run once (for each time you upgrades `jdkman`): 52 | 53 | ```cmd 54 | jdkman init 55 | ``` 56 | 57 | > You can ignore the init output. 58 | 59 | ## How to use 60 | 61 | ### 1. Add JDKs 62 | 63 | ```shell 64 | jdkman add /Library/Java/JavaVirtualMachines/jdk-21.jdk/Contents/Home 65 | ``` 66 | 67 | ### 2. Show JDKs 68 | 69 | ```shell 70 | jdkman list 71 | ``` 72 | 73 | ### 3. Set JDK version for each project 74 | 75 | Add a file `.java-version` in the root directory of your project with the following content: 76 | 77 | ``` 78 | 21 79 | ``` 80 | 81 | `21` could be changed to any JDK versions, e.g. `11`, `11.0.2`, `1.8`. 82 | `jdkman` will find the most appropriate JDK version for you. 83 | 84 | You could also specify the `implementor` (or `vendor`) of the JDK: 85 | Specify the vendor name, add a colon, then specify the jdk version: 86 | 87 | ``` 88 | Oracle Corporation:21.0.1+12-29 89 | ``` 90 | 91 | ### 4. Use java 92 | 93 | ```shell 94 | java -version 95 | echo $JAVA_HOME 96 | ``` 97 | 98 | ### 5. The `cd` command and `JAVA_HOME` 99 | 100 | For `bash|zsh|powershell`, the `cd` command is replaced with a convenient function: `cdjh` 101 | it will `cd` into the specified directory, and configure `JAVA_HOME` environment variable automatically. 102 | 103 | You could also instead explicitly call the `cdjh` function. 104 | 105 | Note: This feature is not provided for `cmd`, you have to set it manually by executing the following command: 106 | ```cmd 107 | for /f "delims=" %%i in ('jdkman which') do set "JAVA_HOME=%%i" 108 | ``` 109 | 110 | ## How to build 111 | 112 | ### 1. Prerequisites 113 | 114 | * JDK 21 115 | * GraalVM Native Image for JDK 21 116 | 117 | To build `jdkman-proxy`, you will need `rust|cargo`. 118 | It's already built and placed in resource folder, so you can skip `rust`. 119 | 120 | ### 2. Build 121 | 122 | #### Linux or macOS 123 | 124 | ```shell 125 | ./gradlew clean shadowJar 126 | native-image \ 127 | --enable-preview \ 128 | -jar build/libs/jdkman.jar \ 129 | -Ob -march=compatibility \ 130 | --no-fallback \ 131 | -o jdkman 132 | ``` 133 | 134 | #### Windows (using powershell) 135 | 136 | ```powershell 137 | # build `jdkman-proxy` 138 | $arch="x86_64" # change to aarch64 if running arm windows 139 | cd .\src\main\rust\ 140 | cargo build --release 141 | Copy-Item .\target\release\jdkman-proxy.exe ..\resources\io\vproxy\jdkman\res\jdkman_proxy-windows-$arch.exe 142 | cd ..\..\..\ 143 | 144 | # build jdkman 145 | .\gradlew.bat clean shadowJar 146 | native-image ` 147 | --enable-preview ` 148 | -jar build\libs\jdkman.jar ` 149 | --features=io.vproxy.jdkman.res.Feature ` 150 | --static ` 151 | -Ob -march=compatibility ` 152 | --no-fallback ` 153 | -o jdkman 154 | ``` 155 | 156 | #### Linux static image in docker 157 | 158 | You can build a linux static native image using `vproxyio/graalvm-jdk-21` 159 | 160 | ```shell 161 | docker run --name jdkman-build -it -v `pwd`:/workdir vproxyio/graalvm-jdk-21 /bin/bash 162 | ## inside docker 163 | ./gradlew clean shadowJar 164 | LIBC="musl" ## or glibc 165 | native-image \ 166 | --enable-preview \ 167 | -jar build/libs/jdkman.jar \ 168 | --static --libc=$LIBC \ 169 | -Ob -march=compatibility \ 170 | --no-fallback \ 171 | -o jdkman 172 | ``` 173 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'com.github.johnrengelman.shadow' version '8.1.1' 4 | } 5 | 6 | group = 'io.vproxy' 7 | version = '1' 8 | 9 | java { 10 | sourceCompatibility = 21 11 | targetCompatibility = 21 12 | } 13 | 14 | tasks.withType(JavaCompile) { 15 | options.encoding = "UTF-8" 16 | options.compilerArgs += '--enable-preview' 17 | } 18 | tasks.withType(JavaExec) { 19 | jvmArgs += '--enable-preview' 20 | } 21 | tasks.withType(Test) { 22 | jvmArgs += '--enable-preview' 23 | } 24 | 25 | repositories { 26 | mavenCentral() 27 | } 28 | 29 | dependencies { 30 | implementation 'io.vproxy:commons:1.2.2' 31 | compileOnly 'org.graalvm.sdk:nativeimage:23.1.1' 32 | 33 | testImplementation platform('org.junit:junit-bom:5.9.1') 34 | testImplementation 'org.junit.jupiter:junit-jupiter' 35 | } 36 | 37 | test { 38 | useJUnitPlatform() 39 | } 40 | 41 | shadowJar { 42 | archiveBaseName = 'jdkman' 43 | archiveClassifier = '' 44 | archiveVersion = '' 45 | manifest { 46 | attributes 'Main-Class': 'io.vproxy.jdkman.Main' 47 | } 48 | exclude "module-info.class" 49 | } 50 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wkgcass/jdkman/85c6d62fac5e504f334572034069afacd51ecfbd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 04 00:12:58 CST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'jdkman' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/Main.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman; 2 | 3 | import io.vproxy.base.Config; 4 | import io.vproxy.base.util.LogType; 5 | import io.vproxy.base.util.Logger; 6 | import io.vproxy.commons.util.IOUtils; 7 | import io.vproxy.jdkman.action.*; 8 | import io.vproxy.jdkman.entity.JDKManConfig; 9 | import io.vproxy.jdkman.ex.ErrorResult; 10 | import io.vproxy.jdkman.util.CommentLogHandler; 11 | import vjson.JSON; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.nio.file.Files; 16 | import java.util.*; 17 | 18 | public class Main { 19 | public static final String VERSION = "1.0.4"; 20 | private static final String HELP_STR = """ 21 | Usage: 22 | jdkman [action] [options] 23 | Actions: 24 | help Show this page 25 | version Show version 26 | list [verbose] Show registered jdk list 27 | add Add a new jdk 28 | remove Remove an existing jdk 29 | default Set default jdk 30 | refresh Update jdk info and remove invalid ones 31 | which Print current JAVA_HOME 32 | init [sh|pwsh] Print shell script to eval 33 | """.trim(); 34 | private static final Map ACTIONS = new HashMap<>() {{ 35 | var ls = new ListAction(); 36 | put("list", ls); 37 | put("ls", ls); 38 | put("add", new AddAction()); 39 | var rm = new RemoveAction(); 40 | put("remove", rm); 41 | put("rm", rm); 42 | put("default", new DefaultAction()); 43 | put("refresh", new RefreshAction()); 44 | put("which", new WhichAction()); 45 | put("init", new InitAction()); 46 | }}; 47 | 48 | public static void main(String[] args) { 49 | Logger.logDispatcher.removeLogHandler(Logger.stdoutLogHandler); 50 | Logger.logDispatcher.addLogHandler(CommentLogHandler.get()); 51 | var exitCode = main0(args); 52 | System.exit(exitCode); 53 | } 54 | 55 | private static int main0(String[] args) { 56 | if (args.length == 0) { 57 | System.out.println(STR."Version: \{VERSION}"); 58 | System.out.println(HELP_STR); 59 | return 0; 60 | } 61 | var action = args[0]; 62 | var options = new String[args.length - 1]; 63 | System.arraycopy(args, 1, options, 0, options.length); 64 | switch (action) { 65 | case "help": 66 | return help(options); 67 | case "version": 68 | return version(options); 69 | } 70 | 71 | var jdkmanFile = new File(Config.workingDirectoryFile("jdkman")); 72 | JDKManConfig config; 73 | if (jdkmanFile.exists()) { 74 | String str; 75 | try { 76 | str = Files.readString(jdkmanFile.toPath()); 77 | } catch (IOException e) { 78 | Logger.error(LogType.FILE_ERROR, "failed to read jdkman config file", e); 79 | return 1; 80 | } 81 | try { 82 | config = JSON.deserialize(str, JDKManConfig.rule); 83 | } catch (Exception e) { 84 | Logger.error(LogType.INVALID_EXTERNAL_DATA, "invalid jdkman config file", e); 85 | return 1; 86 | } 87 | } else { 88 | config = new JDKManConfig(); 89 | Logger.logDispatcher.removeLogHandler(CommentLogHandler.get()); 90 | try { 91 | try { 92 | IOUtils.writeFileWithBackup(jdkmanFile.getAbsolutePath(), config.toJson().pretty()); 93 | } finally { 94 | Logger.logDispatcher.addLogHandler(CommentLogHandler.get()); 95 | } 96 | } catch (Exception e) { 97 | Logger.error(LogType.FILE_ERROR, "failed to create jdkman config file", e); 98 | return 1; 99 | } 100 | } 101 | 102 | var act = ACTIONS.get(action); 103 | if (act == null) { 104 | System.out.println(STR."unknown action `\{action}`"); 105 | return 1; 106 | } 107 | var err = act.validate(options); 108 | if (err != null) { 109 | System.out.println(err); 110 | return 1; 111 | } 112 | boolean isModified; 113 | try { 114 | isModified = act.execute(config, options); 115 | } catch (ErrorResult e) { 116 | System.out.println(e.getMessage()); 117 | return 1; 118 | } catch (Exception e) { 119 | Logger.error(LogType.SYS_ERROR, STR."failed to execute \{action} \{Arrays.toString(options)}", e); 120 | return 1; 121 | } 122 | 123 | if (isModified) { 124 | Logger.logDispatcher.removeLogHandler(CommentLogHandler.get()); 125 | try { 126 | try { 127 | IOUtils.writeFileWithBackup(jdkmanFile.getAbsolutePath(), config.toJson().pretty()); 128 | } finally { 129 | Logger.logDispatcher.addLogHandler(CommentLogHandler.get()); 130 | } 131 | } catch (Exception e) { 132 | Logger.error(LogType.FILE_ERROR, "failed to persist jdkman config", e); 133 | return 1; 134 | } 135 | } 136 | return 0; 137 | } 138 | 139 | private static int help(String[] options) { 140 | if (options.length != 0) { 141 | System.out.println(STR."unknown options for `help`: \{Arrays.toString(options)}"); 142 | return 1; 143 | } 144 | System.out.println(HELP_STR); 145 | return 0; 146 | } 147 | 148 | private static int version(String[] options) { 149 | if (options.length != 0) { 150 | System.out.println(STR."unknown options for `version`: \{Arrays.toString(options)}"); 151 | return 1; 152 | } 153 | System.out.println(VERSION); 154 | return 0; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/Action.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.jdkman.entity.JDKManConfig; 4 | 5 | public interface Action { 6 | String validate(String[] options); 7 | 8 | boolean execute(JDKManConfig config, String[] options) throws Exception; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/AddAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.base.util.LogType; 4 | import io.vproxy.base.util.Logger; 5 | import io.vproxy.jdkman.entity.JDKInfo; 6 | import io.vproxy.jdkman.entity.JDKInfoMatcher; 7 | import io.vproxy.jdkman.entity.JDKManConfig; 8 | import io.vproxy.jdkman.ex.ErrorResult; 9 | import io.vproxy.jdkman.util.Utils; 10 | import vjson.JSON; 11 | import vjson.ex.JsonParseException; 12 | 13 | import java.io.File; 14 | import java.io.FileInputStream; 15 | import java.nio.file.Path; 16 | import java.util.*; 17 | 18 | public class AddAction implements Action { 19 | @Override 20 | public String validate(String[] options) { 21 | if (options.length == 0) { 22 | return "missing JAVA_HOME for `add`"; 23 | } 24 | if (options.length > 1) { 25 | return STR."unknown options for `add`: \{Arrays.toString(options)}"; 26 | } 27 | return Utils.validateJavaHome(options[0]); 28 | } 29 | 30 | @Override 31 | public boolean execute(JDKManConfig config, String[] options) throws Exception { 32 | var javaHome = new File(options[0]).getCanonicalPath(); 33 | for (var jdk : config.getJdks()) { 34 | if (javaHome.equals(jdk.getHome())) { 35 | throw new ErrorResult(STR."JDK with JAVA_HOME \{javaHome} is already registered"); 36 | } 37 | } 38 | 39 | var javaPath = Path.of(javaHome, "bin", "java").toAbsolutePath(); 40 | var process = new ProcessBuilder() 41 | .command(javaPath.toString(), "-version") 42 | .start(); 43 | 44 | var exitCode = process.waitFor(); 45 | var stdout = Utils.readInputStream(process.getInputStream()); 46 | var stderr = Utils.readInputStream(process.getErrorStream()); 47 | if (exitCode != 0) { 48 | throw new ErrorResult(STR.""" 49 | unable to retrieve java version: exit code: \{exitCode} 50 | stdout: 51 | \{stdout} 52 | stderr: 53 | \{stderr}"""); 54 | } 55 | 56 | var lines = stderr.split("\n"); 57 | if (lines.length == 0) { 58 | throw new ErrorResult(STR.""" 59 | missing java version: empty output 60 | stdout: 61 | \{stdout} 62 | stderr: 63 | \{stderr}"""); 64 | } 65 | var firstLine = lines[0].trim(); 66 | if (!firstLine.contains("\"")) { 67 | throw new ErrorResult(STR.""" 68 | missing java version: first line doesn't contain `"` 69 | stdout: 70 | \{stdout} 71 | stderr: 72 | \{stderr}"""); 73 | } 74 | var split = firstLine.split("\""); 75 | if (split.length < 2) { 76 | throw new ErrorResult(STR.""" 77 | missing java version: invalid first line 78 | stdout: 79 | \{stdout} 80 | stderr: 81 | \{stderr}"""); 82 | } 83 | var versionStr = split[1]; 84 | var versionInfo = Utils.parseVersion(versionStr); 85 | 86 | if (lines.length >= 2) { 87 | var detailedVersionInfo = parseLine2(lines[1]); 88 | if (detailedVersionInfo != null) { 89 | if (versionInfo.majorVersion != detailedVersionInfo.majorVersion) { 90 | throw new ErrorResult(STR.""" 91 | major version mismatch: 92 | \{stderr}"""); 93 | } 94 | if (!Objects.equals(versionInfo.minorVersion, detailedVersionInfo.minorVersion)) { 95 | throw new ErrorResult(STR.""" 96 | minor version mismatch: 97 | \{stderr}"""); 98 | } 99 | if (!Objects.equals(versionInfo.patchVersion, detailedVersionInfo.patchVersion)) { 100 | throw new ErrorResult(STR.""" 101 | patch version mismatch: 102 | \{stderr}"""); 103 | } 104 | versionInfo = detailedVersionInfo; 105 | } 106 | } 107 | 108 | // check release file 109 | String implementor = null; 110 | var releaseFile = Path.of(javaHome, "release").toFile(); 111 | if (releaseFile.exists() && releaseFile.isFile()) { 112 | var p = new Properties(); 113 | try (var input = new FileInputStream(releaseFile)) { 114 | p.load(input); 115 | } 116 | implementor = p.getProperty("IMPLEMENTOR"); 117 | if (implementor != null && implementor.startsWith("\"")) { 118 | JSON.String jsonStr = null; 119 | try { 120 | var o = JSON.parse(implementor); 121 | if (o instanceof JSON.String s) { 122 | jsonStr = s; 123 | } 124 | } catch (JsonParseException e) { 125 | Logger.warn(LogType.ALERT, STR."implementor field is not a valid json string: \{implementor}", e); 126 | } 127 | if (jsonStr != null) { 128 | implementor = jsonStr.toJavaObject(); 129 | } 130 | } 131 | } 132 | 133 | var uuid = UUID.randomUUID().toString(); 134 | var version = new JDKInfo(versionInfo); 135 | version.setId(uuid); 136 | version.setHome(javaHome); 137 | version.setImplementor(implementor); 138 | config.getJdks().add(version); 139 | 140 | config.getJdks().sort(Comparator.reverseOrder()); 141 | 142 | if (config.getDefaultJDK() == null) { 143 | config.setDefaultJDK(uuid); 144 | } 145 | 146 | return true; 147 | } 148 | 149 | private JDKInfoMatcher parseLine2(String secondLine) throws ErrorResult { 150 | if (!secondLine.contains("(")) { 151 | return null; 152 | } 153 | secondLine = secondLine.substring(secondLine.lastIndexOf("(") + 1); 154 | if (!secondLine.contains(")")) { 155 | return null; 156 | } 157 | secondLine = secondLine.substring(0, secondLine.indexOf(")")); 158 | if (!secondLine.startsWith("build ")) { 159 | return null; 160 | } 161 | secondLine = secondLine.substring("build ".length()); 162 | return Utils.parseVersion(secondLine); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/DefaultAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.jdkman.entity.JDKManConfig; 4 | import io.vproxy.jdkman.ex.ErrorResult; 5 | 6 | import java.util.Arrays; 7 | 8 | public class DefaultAction implements Action { 9 | @Override 10 | public String validate(String[] options) { 11 | if (options.length == 0) { 12 | return "missing id for `default`"; 13 | } 14 | if (options.length > 1) { 15 | return STR."unknown options for `default`: \{Arrays.toString(options)}"; 16 | } 17 | return null; 18 | } 19 | 20 | @Override 21 | public boolean execute(JDKManConfig config, String[] options) throws Exception { 22 | var uuid = options[0]; 23 | for (var jdk : config.getJdks()) { 24 | if (jdk.getId().equals(uuid)) { 25 | config.setDefaultJDK(uuid); 26 | return true; 27 | } 28 | } 29 | throw new ErrorResult(STR."unable to find jdk with id \{uuid}"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/InitAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.base.util.LogType; 4 | import io.vproxy.base.util.Logger; 5 | import io.vproxy.base.util.OS; 6 | import io.vproxy.base.util.Utils; 7 | import io.vproxy.jdkman.Main; 8 | import io.vproxy.jdkman.entity.JDKManConfig; 9 | import io.vproxy.jdkman.ex.ErrorResult; 10 | import io.vproxy.jdkman.res.ResConsts; 11 | 12 | import java.io.*; 13 | import java.nio.charset.StandardCharsets; 14 | import java.nio.file.Files; 15 | import java.nio.file.Path; 16 | import java.util.Arrays; 17 | import java.util.HashSet; 18 | import java.util.Set; 19 | 20 | public class InitAction implements Action { 21 | private static final Set EXECUTABLES = new HashSet<>() {{ 22 | addAll(Arrays.asList( 23 | "jar", "jarsigner", "java", "javac", 24 | "javadoc", "javap", "jcmd", "jconsole", 25 | "jdb", "jdeprscan", "jdeps", "jfr", 26 | "jhsdb", "jimage", "jinfo", "jlink", 27 | "jmap", "jmod", "jpackage", "jps", 28 | "jrunscript", "jshell", "jstack", 29 | "jstat", "jstatd", "jwebserver", 30 | "keytool", "rmiregistry", "serialver")); 31 | addAll(Arrays.asList( 32 | "jaotc", "jpackager" 33 | )); 34 | addAll(Arrays.asList( 35 | "appletviewer", "extcheck", "idlj", 36 | "javafxpackager", "javah", "javapackager", 37 | "jhat", "jjs", "jmc", "jsadebugd", 38 | "jvisualvm", "native2ascii", "orbd", 39 | "pack200", "policytool", "rmic", "rmid", 40 | "schemagen", "servertool", "tnameserv", 41 | "unpack200", "wsgen", "wsimport", "xjc")); 42 | addAll(Arrays.asList( 43 | "javaws", "jcontrol", "jweblauncher" 44 | )); 45 | addAll(Arrays.asList( 46 | "jabswitch", "jaccessinspector", "jaccesswalker", 47 | "javaw", "kinit", "klist", "ktab" 48 | )); 49 | }}; 50 | private static final String VERSION_FILE = "version.txt"; 51 | 52 | @Override 53 | public String validate(String[] options) { 54 | if (options.length != 0 && options.length != 1) { 55 | return STR."unknown options for `init`: \{Arrays.toString(options)}"; 56 | } 57 | if (options.length > 0 && !Set.of("sh", "pwsh").contains(options[0])) { 58 | return STR."the first option must be 'sh|pwsh': \{options[0]}"; 59 | } 60 | return null; 61 | } 62 | 63 | private enum ShellType { 64 | shell, 65 | pwsh, 66 | } 67 | 68 | @Override 69 | public boolean execute(JDKManConfig config, String[] options) throws Exception { 70 | var shellType = OS.isWindows() ? ShellType.pwsh : ShellType.shell; 71 | for (var o : options) { 72 | switch (o) { 73 | case "sh" -> shellType = ShellType.shell; 74 | case "pwsh" -> shellType = ShellType.pwsh; 75 | } 76 | } 77 | 78 | var jdkmanScriptDir = jdkmanScriptPathFile(); 79 | var versionFilePath = Path.of(jdkmanScriptDir.getAbsolutePath(), VERSION_FILE); 80 | boolean versionMatches = false; 81 | if (versionFilePath.toFile().isFile()) { 82 | var version = Files.readString(versionFilePath).trim(); 83 | if (version.equals(Main.VERSION)) { 84 | versionMatches = true; 85 | } 86 | } 87 | 88 | for (var exe : EXECUTABLES) { 89 | var suffix = ""; 90 | if (OS.isWindows()) { 91 | suffix = ".exe"; // use jdkman-proxy binary 92 | } 93 | var path = Path.of(jdkmanScriptDir.getAbsolutePath(), exe + suffix); 94 | var file = path.toFile(); 95 | if (file.exists()) { 96 | if (!file.isFile()) { 97 | Logger.error(LogType.INVALID_EXTERNAL_DATA, STR."\{file} is not a valid file"); 98 | continue; 99 | } 100 | if (versionMatches) { 101 | // no need to release the file because version matches 102 | continue; 103 | } 104 | if (OS.isWindows()) { 105 | // check file md5 for windows, because windows doesn't allow files to be deleted while they are running 106 | var md5 = io.vproxy.jdkman.util.Utils.fileMD5(file); 107 | if (md5.equals(ResConsts.MD5_JDKMAN_PROXY_WINDOWS_X86_64)) { 108 | // the file is the latest, no need to release it again 109 | continue; 110 | } 111 | } 112 | var ok = file.delete(); 113 | if (!ok) { 114 | Logger.error(LogType.FILE_ERROR, STR."failed to delete file: \{file}"); 115 | continue; 116 | } 117 | } 118 | var ok = file.createNewFile(); 119 | if (!ok) { 120 | Logger.error(LogType.INVALID_EXTERNAL_DATA, STR."failed to create file: \{file}"); 121 | continue; 122 | } 123 | 124 | var scriptContent = getScriptContent(exe); 125 | try (scriptContent; var fos = new FileOutputStream(file)) { 126 | scriptContent.transferTo(fos); 127 | //noinspection ResultOfMethodCallIgnored 128 | file.setExecutable(true); 129 | } catch (IOException e) { 130 | Logger.error(LogType.FILE_ERROR, STR."failed to create file \{path}", e); 131 | } 132 | } 133 | 134 | Files.writeString(versionFilePath, Main.VERSION); 135 | 136 | var scriptToEval = getScriptToEval(jdkmanScriptDir, shellType); 137 | System.out.println(scriptToEval.trim()); 138 | 139 | return false; 140 | } 141 | 142 | private File jdkmanScriptPathFile() throws ErrorResult { 143 | var jdkmanScriptDir = Path.of(Utils.homedir(), "jdkman-scripts").toFile(); 144 | if (jdkmanScriptDir.exists()) { 145 | if (!jdkmanScriptDir.isDirectory()) { 146 | throw new ErrorResult(STR."\{jdkmanScriptDir} is not a directory"); 147 | } 148 | } else { 149 | var ok = jdkmanScriptDir.mkdirs(); 150 | if (!ok) { 151 | throw new ErrorResult(STR."failed to create directory: \{jdkmanScriptDir}"); 152 | } 153 | } 154 | return jdkmanScriptDir; 155 | } 156 | 157 | private static InputStream getScriptContent(String exe) { 158 | if (OS.isWindows()) { 159 | // use jdkman-proxy 160 | return InitAction.class.getResourceAsStream("/io/vproxy/jdkman/res/jdkman_proxy-windows-x86_64.exe"); 161 | } else { 162 | // use shell scripts 163 | return new ByteArrayInputStream(STR.""" 164 | #!/bin/bash 165 | set -e 166 | export JAVA_HOME=`jdkman which` 167 | exec "$JAVA_HOME/bin/\{exe}" "$@" 168 | """.getBytes(StandardCharsets.UTF_8)); 169 | } 170 | } 171 | 172 | private static String getScriptToEval(File jdkmanScriptDir, ShellType shellType) throws ErrorResult { 173 | if (shellType == ShellType.pwsh) { 174 | return buildPowershellEval(jdkmanScriptDir); 175 | } else { 176 | return buildBashEval(jdkmanScriptDir); 177 | } 178 | } 179 | 180 | private static String writeJDKManScriptDirPathToTmpFile(File jdkmanScriptDir) throws ErrorResult { 181 | try { 182 | var file = File.createTempFile("jdkman-script-dir-path", ".txt"); 183 | Files.writeString(file.toPath(), jdkmanScriptDir.getAbsolutePath()); 184 | return file.getAbsolutePath(); 185 | } catch (IOException e) { 186 | throw new ErrorResult("failed to create temporary file for jdkman-script path", e); 187 | } 188 | } 189 | 190 | private static String buildBashEval(File jdkmanScriptDir) throws ErrorResult { 191 | var jdkmanScriptDirPathTmpFile = writeJDKManScriptDirPathToTmpFile(jdkmanScriptDir); 192 | return STR.""" 193 | JDKMAN_SCRIPT_PATH=`cat \{jdkmanScriptDirPathTmpFile}` 194 | export PATH="$JDKMAN_SCRIPT_PATH:$PATH" 195 | function cdjh() { 196 | builtin cd "$@" 197 | export JAVA_HOME="`jdkman which`" 198 | } 199 | alias cd=cdjh 200 | export JAVA_HOME="`jdkman which`" 201 | rm -f \{jdkmanScriptDirPathTmpFile} 202 | """; 203 | } 204 | 205 | private static String buildPowershellEval(File jdkmanScriptDir) throws ErrorResult { 206 | var jdkmanScriptDirPathTmpFile = writeJDKManScriptDirPathToTmpFile(jdkmanScriptDir); 207 | Path initPs1File; 208 | try { 209 | initPs1File = Files.createTempFile("jdkman-init", ".ps1"); 210 | } catch (IOException e) { 211 | Logger.error(LogType.FILE_ERROR, "failed to create jdkman-init.ps1 tmp file", e); 212 | throw new ErrorResult("failed to create jdkman-init.ps1 file"); 213 | } 214 | 215 | var sb = new StringBuilder(); 216 | for (var exe : EXECUTABLES) { 217 | sb.append("function ").append(exe).append(" {\n"); 218 | sb.append(" $JAVA_HOME = jdkman which\n"); 219 | sb.append(" $env:JAVA_HOME = $JAVA_HOME\n"); 220 | sb.append(" & \"$JAVA_HOME\\bin\\").append(exe); 221 | if (OS.isWindows()) { 222 | sb.append(".exe"); 223 | } 224 | sb.append("\" $args"); 225 | sb.append("\n"); 226 | sb.append("}\n"); 227 | } 228 | sb.append("$JDKMAN_SCRIPT_PATH = (Get-Content ") 229 | .append(jdkmanScriptDirPathTmpFile) 230 | .append(")\n"); 231 | sb.append(STR.""" 232 | $env:PATH = "$JDKMAN_SCRIPT_PATH\{pathSeparatorInPSStr()}${env:PATH}" 233 | $env:JAVA_HOME = jdkman which 234 | function cdjh { 235 | param([string]$path) 236 | Set-Location $path 237 | $env:JAVA_HOME = jdkman which 238 | } 239 | Set-Alias -Name cd -Value cdjh -Option AllScope 240 | Remove-Item \{initPs1File} 241 | Remove-Item \{jdkmanScriptDirPathTmpFile} 242 | """); 243 | 244 | try { 245 | Files.writeString(initPs1File, sb.toString()); 246 | } catch (IOException e) { 247 | Logger.error(LogType.FILE_ERROR, "failed to release jdkman-init.ps1 tmp file", e); 248 | throw new ErrorResult("failed to release jdkman-init.ps1 file"); 249 | } 250 | return STR.". \{initPs1File}"; 251 | } 252 | 253 | private static String pathSeparatorInPSStr() { 254 | var s = File.pathSeparator; 255 | if (s.equals(":")) { 256 | return "\\:"; 257 | } 258 | return s; 259 | } 260 | } 261 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/ListAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.base.util.OS; 4 | import io.vproxy.base.util.display.TableBuilder; 5 | import io.vproxy.jdkman.entity.JDKManConfig; 6 | import io.vproxy.jdkman.util.Utils; 7 | 8 | import java.util.Arrays; 9 | 10 | public class ListAction implements Action { 11 | @Override 12 | public String validate(String[] options) { 13 | if (options.length == 0) { 14 | return null; 15 | } 16 | if (options.length == 1) { 17 | if (options[0].equals("verbose")) { 18 | return null; 19 | } 20 | } 21 | return STR."unknown options for `list`: \{Arrays.toString(options)}"; 22 | } 23 | 24 | @SuppressWarnings("StringTemplateMigration") 25 | @Override 26 | public boolean execute(JDKManConfig config, String[] options) { 27 | var table = new TableBuilder(); 28 | var tr = table.tr(); 29 | tr.td("id").td("version").td("build").td("full").td("vendor") 30 | .td("default").td("current"); 31 | var isVerbose = Arrays.asList(options).contains("verbose"); 32 | if (isVerbose) { 33 | tr.td("home"); 34 | } 35 | 36 | var current = Utils.currentVersion(config); 37 | 38 | for (var jdk : config.getJdks()) { 39 | tr = table.tr(); 40 | tr.td(jdk.getId()); 41 | 42 | var version = "" + jdk.getMajorVersion(); 43 | boolean minorAdded = false; 44 | if (jdk.getMinorVersion() != 0) { 45 | version += "." + jdk.getMinorVersion(); 46 | minorAdded = true; 47 | } 48 | if (jdk.getPatchVersion() != 0) { 49 | if (!minorAdded) { 50 | version += ".0"; 51 | } 52 | version += "." + jdk.getPatchVersion(); 53 | } 54 | tr.td(version); 55 | 56 | if (jdk.getBuildVersion() == null) { 57 | tr.td(""); 58 | } else { 59 | tr.td(jdk.getBuildVersion()); 60 | } 61 | 62 | tr.td(jdk.getFullVersion()); 63 | 64 | if (jdk.getImplementor() == null) { 65 | tr.td(""); 66 | } else { 67 | tr.td(jdk.getImplementor()); 68 | } 69 | 70 | if (jdk.getId().equals(config.getDefaultJDK())) { 71 | if (OS.isWindows()) { 72 | tr.td(" *"); 73 | } else { 74 | tr.td(" ○"); 75 | } 76 | } else { 77 | tr.td(""); 78 | } 79 | 80 | if (current == jdk) { 81 | if (OS.isWindows()) { 82 | tr.td(" *"); 83 | } else { 84 | tr.td(" ●"); 85 | } 86 | } else { 87 | tr.td(""); 88 | } 89 | 90 | if (isVerbose) { 91 | tr.td(jdk.getHome()); 92 | } 93 | } 94 | 95 | System.out.println(table.toString().trim()); 96 | return false; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/RefreshAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.base.util.LogType; 4 | import io.vproxy.base.util.Logger; 5 | import io.vproxy.jdkman.entity.JDKInfo; 6 | import io.vproxy.jdkman.entity.JDKManConfig; 7 | 8 | import java.io.File; 9 | import java.util.ArrayList; 10 | import java.util.Arrays; 11 | 12 | public class RefreshAction implements Action { 13 | @Override 14 | public String validate(String[] options) { 15 | if (options.length == 0) { 16 | return null; 17 | } 18 | return STR."unknown options for `refresh`: \{Arrays.toString(options)}"; 19 | } 20 | 21 | @Override 22 | public boolean execute(JDKManConfig config, String[] options) { 23 | var homes = new ArrayList(); 24 | JDKInfo oldDefault = null; 25 | for (var jdk : config.getJdks()) { 26 | if (new File(jdk.getHome()).exists()) { 27 | homes.add(jdk.getHome()); 28 | if (jdk.getId().equals(config.getDefaultJDK())) { 29 | oldDefault = jdk; 30 | } 31 | } else { 32 | Logger.info(LogType.ALERT, STR."jdk \{jdk} is removed"); 33 | } 34 | } 35 | 36 | config.setDefaultJDK(null); 37 | config.setJdks(new ArrayList<>()); 38 | var addAction = new AddAction(); 39 | for (var home : homes) { 40 | try { 41 | addAction.execute(config, new String[]{home}); 42 | Logger.alert(STR."jdk \{home} is re-added"); 43 | } catch (Exception e) { 44 | Logger.error(LogType.ALERT, STR."failed to re-add jdk: \{home}", e); 45 | } 46 | } 47 | 48 | if (oldDefault != null) { 49 | for (var jdk : config.getJdks()) { 50 | if (oldDefault.getHome().equals(jdk.getHome())) { 51 | config.setDefaultJDK(jdk.getId()); 52 | break; 53 | } 54 | } 55 | } 56 | 57 | return true; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/RemoveAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.jdkman.entity.JDKManConfig; 4 | import io.vproxy.jdkman.ex.ErrorResult; 5 | 6 | import java.util.Arrays; 7 | 8 | public class RemoveAction implements Action { 9 | @Override 10 | public String validate(String[] options) { 11 | if (options.length == 0) { 12 | return "missing id for `remove`"; 13 | } 14 | if (options.length > 1) { 15 | return STR."unknown options for `remove`: \{Arrays.toString(options)}"; 16 | } 17 | return null; 18 | } 19 | 20 | @Override 21 | public boolean execute(JDKManConfig config, String[] options) throws Exception { 22 | var uuid = options[0]; 23 | var removed = config.getJdks().removeIf(e -> uuid.equals(e.getId())); 24 | if (!removed) { 25 | throw new ErrorResult(STR."\{options[0]} not found"); 26 | } 27 | 28 | if (uuid.equals(config.getDefaultJDK())) { 29 | if (config.getJdks().isEmpty()) { 30 | config.setDefaultJDK(null); 31 | } else { 32 | config.setDefaultJDK(config.getJdks().getFirst().getId()); 33 | } 34 | } 35 | return true; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/action/WhichAction.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.action; 2 | 3 | import io.vproxy.jdkman.entity.JDKManConfig; 4 | import io.vproxy.jdkman.util.Utils; 5 | 6 | import java.util.Arrays; 7 | 8 | public class WhichAction implements Action { 9 | @Override 10 | public String validate(String[] options) { 11 | if (options.length == 0) { 12 | return null; 13 | } 14 | return STR."unknown options for `which`: \{Arrays.toString(options)}"; 15 | } 16 | 17 | @Override 18 | public boolean execute(JDKManConfig config, String[] options) { 19 | var jdk = Utils.currentVersion(config); 20 | if (jdk == null) { 21 | // not found, so print nothing 22 | return false; 23 | } 24 | System.out.println(jdk.getHome()); 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/entity/JDKInfo.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.entity; 2 | 3 | import vjson.JSON; 4 | import vjson.JSONObject; 5 | import vjson.deserializer.rule.*; 6 | import vjson.util.ObjectBuilder; 7 | 8 | public class JDKInfo implements JSONObject, Comparable { 9 | private String id; 10 | private int majorVersion; 11 | private int minorVersion; 12 | private int patchVersion; 13 | private String buildVersion; // nullable 14 | private String fullVersion; 15 | private String implementor; // nullable 16 | private String home; 17 | 18 | public static final Rule rule = new ObjectRule<>(JDKInfo::new) 19 | .put("id", JDKInfo::setId, StringRule.get()) 20 | .put("majorVersion", JDKInfo::setMajorVersion, IntRule.get()) 21 | .put("minorVersion", JDKInfo::setMinorVersion, IntRule.get()) 22 | .put("patchVersion", JDKInfo::setPatchVersion, IntRule.get()) 23 | .put("buildVersion", JDKInfo::setBuildVersion, NullableStringRule.get()) 24 | .put("fullVersion", JDKInfo::setFullVersion, StringRule.get()) 25 | .put("implementor", JDKInfo::setImplementor, NullableStringRule.get()) 26 | .put("home", JDKInfo::setHome, StringRule.get()); 27 | 28 | @Override 29 | public JSON.Object toJson() { 30 | return new ObjectBuilder() 31 | .put("id", id) 32 | .put("majorVersion", majorVersion) 33 | .put("minorVersion", minorVersion) 34 | .put("patchVersion", patchVersion) 35 | .put("buildVersion", buildVersion) 36 | .put("fullVersion", fullVersion) 37 | .put("implementor", implementor) 38 | .put("home", home) 39 | .build(); 40 | } 41 | 42 | public JDKInfo() { 43 | } 44 | 45 | public JDKInfo(JDKInfoMatcher m) { 46 | this.majorVersion = m.majorVersion; 47 | this.minorVersion = m.minorVersion == null ? 0 : m.minorVersion; 48 | this.patchVersion = m.patchVersion == null ? 0 : m.patchVersion; 49 | this.buildVersion = m.buildVersion; 50 | this.fullVersion = m.fullVersion; 51 | this.implementor = m.implementor; 52 | } 53 | 54 | public String getId() { 55 | return id; 56 | } 57 | 58 | public void setId(String id) { 59 | this.id = id; 60 | } 61 | 62 | public int getMajorVersion() { 63 | return majorVersion; 64 | } 65 | 66 | public void setMajorVersion(int majorVersion) { 67 | this.majorVersion = majorVersion; 68 | } 69 | 70 | public int getMinorVersion() { 71 | return minorVersion; 72 | } 73 | 74 | public void setMinorVersion(int minorVersion) { 75 | this.minorVersion = minorVersion; 76 | } 77 | 78 | public int getPatchVersion() { 79 | return patchVersion; 80 | } 81 | 82 | public void setPatchVersion(int patchVersion) { 83 | this.patchVersion = patchVersion; 84 | } 85 | 86 | public String getBuildVersion() { 87 | return buildVersion; 88 | } 89 | 90 | public void setBuildVersion(String buildVersion) { 91 | this.buildVersion = buildVersion; 92 | } 93 | 94 | public String getFullVersion() { 95 | return fullVersion; 96 | } 97 | 98 | public void setFullVersion(String fullVersion) { 99 | this.fullVersion = fullVersion; 100 | } 101 | 102 | public String getImplementor() { 103 | return implementor; 104 | } 105 | 106 | public void setImplementor(String implementor) { 107 | this.implementor = implementor; 108 | } 109 | 110 | public String getHome() { 111 | return home; 112 | } 113 | 114 | public void setHome(String home) { 115 | this.home = home; 116 | } 117 | 118 | @Override 119 | public int compareTo(JDKInfo that) { 120 | if (majorVersion > that.majorVersion) 121 | return 1; 122 | if (majorVersion < that.majorVersion) 123 | return -1; 124 | if (minorVersion > that.minorVersion) 125 | return 1; 126 | if (minorVersion < that.minorVersion) 127 | return -1; 128 | if (patchVersion > that.patchVersion) 129 | return 1; 130 | if (patchVersion < that.patchVersion) 131 | return -1; 132 | if (buildVersion != null && that.buildVersion == null) 133 | return 1; 134 | if (buildVersion == null && that.buildVersion != null) 135 | return -1; 136 | if (implementor != null && that.implementor == null) 137 | return 1; 138 | if (implementor == null && that.implementor != null) 139 | return -1; 140 | return 0; 141 | } 142 | 143 | @SuppressWarnings("StringTemplateMigration") 144 | @Override 145 | public String toString() { 146 | return "JDKInfo{" + 147 | "id=" + (id == null ? "null" : ("'" + id + "'")) + 148 | ", majorVersion=" + majorVersion + 149 | ", minorVersion=" + minorVersion + 150 | ", patchVersion=" + patchVersion + 151 | ", buildVersion=" + (buildVersion == null ? "null" : ("'" + buildVersion + "'")) + 152 | ", fullVersion=" + (fullVersion == null ? "null" : ("'" + fullVersion + "'")) + 153 | ", implementor=" + (implementor == null ? "null" : ("'" + implementor + "'")) + 154 | ", home=" + (home == null ? "null" : ("'" + home + "'")) + 155 | '}'; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/entity/JDKInfoMatcher.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.entity; 2 | 3 | import java.util.Objects; 4 | 5 | public class JDKInfoMatcher { 6 | public final String implementor; 7 | public final int majorVersion; 8 | public final Integer minorVersion; 9 | public final Integer patchVersion; 10 | public final String buildVersion; 11 | public final String fullVersion; 12 | 13 | public JDKInfoMatcher(String implementor, int majorVersion, Integer minorVersion, Integer patchVersion, String buildVersion, String fullVersion) { 14 | this.implementor = implementor; 15 | this.majorVersion = majorVersion; 16 | this.minorVersion = minorVersion; 17 | this.patchVersion = patchVersion; 18 | if (patchVersion != null) { 19 | if (minorVersion == null) 20 | throw new NullPointerException(STR."patch version (\{patchVersion}) is specified but missing minor version"); 21 | } 22 | this.buildVersion = buildVersion; 23 | this.fullVersion = Objects.requireNonNull(fullVersion); 24 | } 25 | 26 | @SuppressWarnings("RedundantIfStatement") 27 | public boolean match(JDKInfo that, MatchOptions opts) { 28 | if (opts.matchImplementor) { 29 | if (implementor != null 30 | && !implementor.equals(that.getImplementor())) { 31 | return false; 32 | } 33 | } 34 | if (opts.matchMajorVersion) { 35 | if (majorVersion != that.getMajorVersion()) 36 | return false; 37 | if (majorVersion == 1) { 38 | // 1.7.x, 1.8.x, the minor version is critical 39 | if (minorVersion != null 40 | && minorVersion != that.getMinorVersion()) 41 | return false; 42 | } 43 | } else { 44 | if (majorVersion > that.getMajorVersion()) 45 | return false; 46 | if (majorVersion == 1 && that.getMajorVersion() == 1) { 47 | if (minorVersion != null 48 | && minorVersion > that.getMinorVersion()) 49 | return false; 50 | } 51 | } 52 | if (majorVersion != 1) { 53 | // 11.x.x, 21.x.x, the minor version is not critical 54 | if (minorVersion != null 55 | && minorVersion > that.getMinorVersion()) 56 | return false; 57 | } 58 | if (patchVersion != null 59 | && patchVersion > that.getPatchVersion()) { 60 | assert minorVersion != null; 61 | if (minorVersion == that.getMinorVersion()) { 62 | return false; 63 | } 64 | } 65 | if (opts.matchBuildVersion) { 66 | if (buildVersion != null 67 | && !buildVersion.equals(that.getBuildVersion())) { 68 | return false; 69 | } 70 | } 71 | return true; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/entity/JDKManConfig.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.entity; 2 | 3 | import vjson.JSON; 4 | import vjson.JSONObject; 5 | import vjson.deserializer.rule.ArrayRule; 6 | import vjson.deserializer.rule.NullableStringRule; 7 | import vjson.deserializer.rule.ObjectRule; 8 | import vjson.deserializer.rule.Rule; 9 | import vjson.util.ObjectBuilder; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class JDKManConfig implements JSONObject { 15 | private String defaultJDK; 16 | private List jdks; 17 | 18 | public static final Rule rule = new ObjectRule<>(() -> new JDKManConfig(null)) 19 | .put("defaultJDK", JDKManConfig::setDefaultJDK, NullableStringRule.get()) 20 | .put("jdks", JDKManConfig::setJdks, new ArrayRule<>(ArrayList::new, List::add, JDKInfo.rule)); 21 | 22 | @Override 23 | public JSON.Object toJson() { 24 | return new ObjectBuilder() 25 | .put("defaultJDK", defaultJDK) 26 | .putArray("jdks", a -> jdks.forEach(e -> a.addInst(e.toJson()))) 27 | .build(); 28 | } 29 | 30 | public JDKManConfig() { 31 | jdks = new ArrayList<>(); 32 | } 33 | 34 | private JDKManConfig(@SuppressWarnings("unused") Void unused) { 35 | } 36 | 37 | public String getDefaultJDK() { 38 | return defaultJDK; 39 | } 40 | 41 | public void setDefaultJDK(String defaultJDK) { 42 | this.defaultJDK = defaultJDK; 43 | } 44 | 45 | public List getJdks() { 46 | return jdks; 47 | } 48 | 49 | public void setJdks(List jdks) { 50 | this.jdks = jdks; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/entity/MatchOptions.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.entity; 2 | 3 | public class MatchOptions { 4 | boolean matchMajorVersion = true; 5 | boolean matchBuildVersion = true; 6 | boolean matchImplementor = true; 7 | 8 | public MatchOptions() { 9 | this(true); 10 | } 11 | 12 | public MatchOptions(boolean init) { 13 | matchMajorVersion = init; 14 | matchBuildVersion = init; 15 | matchImplementor = init; 16 | } 17 | 18 | public MatchOptions setMatchMajorVersion(boolean matchMajorVersion) { 19 | this.matchMajorVersion = matchMajorVersion; 20 | return this; 21 | } 22 | 23 | public MatchOptions setMatchBuildVersion(boolean matchBuildVersion) { 24 | this.matchBuildVersion = matchBuildVersion; 25 | return this; 26 | } 27 | 28 | public MatchOptions setMatchImplementor(boolean matchImplementor) { 29 | this.matchImplementor = matchImplementor; 30 | return this; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/ex/ErrorResult.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.ex; 2 | 3 | public class ErrorResult extends Exception { 4 | public ErrorResult(String message) { 5 | super(message); 6 | } 7 | 8 | public ErrorResult(String message, Throwable cause) { 9 | super(message, cause); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/res/Feature.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.res; 2 | 3 | import org.graalvm.nativeimage.hosted.RuntimeResourceAccess; 4 | 5 | public class Feature implements org.graalvm.nativeimage.hosted.Feature { 6 | @Override 7 | public void duringSetup(DuringSetupAccess access) { 8 | RuntimeResourceAccess.addResource(getClass().getModule(), "/io/vproxy/jdkman/res/jdkman_proxy-windows-x86_64.exe"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/res/ResConsts.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.res; 2 | 3 | public class ResConsts { 4 | private ResConsts() { 5 | } 6 | 7 | public static final String MD5_JDKMAN_PROXY_WINDOWS_X86_64 = "dc1dd297823a73c64cf17d62b789c34e"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/util/CommentLogHandler.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.util; 2 | 3 | import io.vproxy.base.util.log.LogHandler; 4 | import io.vproxy.base.util.log.LogRecord; 5 | 6 | public class CommentLogHandler implements LogHandler { 7 | private static final CommentLogHandler INST = new CommentLogHandler(); 8 | 9 | public static CommentLogHandler get() { 10 | return INST; 11 | } 12 | 13 | @Override 14 | public void publish(LogRecord logRecord) { 15 | var lines = logRecord.toColoredString().split("\n"); 16 | for (var line : lines) { 17 | System.out.println("## jdkman ## " + line); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/vproxy/jdkman/util/Utils.java: -------------------------------------------------------------------------------- 1 | package io.vproxy.jdkman.util; 2 | 3 | import io.vproxy.base.util.LogType; 4 | import io.vproxy.base.util.Logger; 5 | import io.vproxy.base.util.OS; 6 | import io.vproxy.jdkman.entity.JDKInfo; 7 | import io.vproxy.jdkman.entity.JDKInfoMatcher; 8 | import io.vproxy.jdkman.entity.JDKManConfig; 9 | import io.vproxy.jdkman.entity.MatchOptions; 10 | import io.vproxy.jdkman.ex.ErrorResult; 11 | 12 | import java.io.*; 13 | import java.nio.charset.Charset; 14 | import java.nio.charset.StandardCharsets; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.security.DigestInputStream; 18 | import java.security.MessageDigest; 19 | import java.security.NoSuchAlgorithmException; 20 | import java.util.ArrayList; 21 | import java.util.LinkedHashMap; 22 | import java.util.List; 23 | import java.util.function.Function; 24 | 25 | public class Utils { 26 | private Utils() { 27 | } 28 | 29 | public static String validateJavaHome(String javaHome) { 30 | var file = new File(javaHome); 31 | if (!file.exists()) { 32 | return STR."\{javaHome} does not exist"; 33 | } 34 | if (!file.isDirectory()) { 35 | return STR."\{javaHome} is not a directory"; 36 | } 37 | var bin = Path.of(file.getAbsolutePath(), "bin"); 38 | file = bin.toFile(); 39 | if (!file.exists()) { 40 | return STR."\{javaHome} does not have bin/ subdirectory"; 41 | } 42 | if (!file.isDirectory()) { 43 | return STR."\{file.getAbsolutePath()} is not a directory"; 44 | } 45 | var java = Path.of(file.getAbsolutePath(), "java" + (OS.isWindows() ? ".exe" : "")); 46 | file = java.toFile(); 47 | if (!file.exists()) { 48 | return STR."\{javaHome} does not have bin/java executable"; 49 | } 50 | if (!file.isFile()) { 51 | return STR."\{file.getAbsoluteFile()} is not a file"; 52 | } 53 | if (!file.canExecute()) { 54 | return STR."\{file.getAbsoluteFile()} is not executable"; 55 | } 56 | return null; 57 | } 58 | 59 | public static String readInputStream(InputStream input) throws IOException { 60 | var sb = new StringBuilder(); 61 | var chars = new char[1024]; 62 | try (var reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { 63 | while (true) { 64 | var len = reader.read(chars); 65 | if (len == -1) { 66 | break; 67 | } 68 | sb.append(chars, 0, len); 69 | } 70 | } 71 | return sb.toString(); 72 | } 73 | 74 | public static boolean isNonNegativeInteger(String s) { 75 | try { 76 | var n = Integer.parseInt(s); 77 | return n >= 0; 78 | } catch (NumberFormatException _) { 79 | return false; 80 | } 81 | } 82 | 83 | public static JDKInfoMatcher parseVersion(final String version) throws ErrorResult { 84 | String implementor = null; 85 | String versionPart; 86 | if (version.contains(":")) { 87 | implementor = version.substring(0, version.indexOf(":")); 88 | versionPart = version.substring(version.indexOf(":") + 1); 89 | } else { 90 | versionPart = version; 91 | } 92 | 93 | int major; 94 | Integer minor = null; 95 | Integer patch = null; 96 | String buildVersion = null; 97 | 98 | String versionStr; 99 | if (versionPart.contains("+")) { 100 | versionStr = versionPart.substring(0, versionPart.indexOf("+")); 101 | buildVersion = versionPart.substring(versionPart.indexOf("+") + 1); 102 | } else if (versionPart.contains("_")) { 103 | versionStr = versionPart.substring(0, versionPart.indexOf("_")); 104 | buildVersion = versionPart.substring(versionPart.indexOf("_") + 1); 105 | } else { 106 | versionStr = versionPart; 107 | } 108 | 109 | var split = versionStr.split("\\."); 110 | if (split.length == 0) { 111 | throw new ErrorResult(STR."\{versionStr} is not a valid version: empty string"); 112 | } 113 | if (!isNonNegativeInteger(split[0])) { 114 | throw new ErrorResult(STR."\{versionStr} is not a valid version: major version not valid: \{split[0]}"); 115 | } 116 | major = Integer.parseInt(split[0]); 117 | if (split.length >= 2) { 118 | if (!isNonNegativeInteger(split[1])) { 119 | throw new ErrorResult(STR."\{versionStr} is not a valid version: minor version not valid: \{split[1]}"); 120 | } 121 | minor = Integer.parseInt(split[1]); 122 | } 123 | if (split.length >= 3) { 124 | if (!isNonNegativeInteger(split[2])) { 125 | throw new ErrorResult(STR."\{versionStr} is not a valid version: patch version not valid: \{split[2]}"); 126 | } 127 | patch = Integer.parseInt(split[2]); 128 | } 129 | 130 | return new JDKInfoMatcher(implementor, major, minor, patch, buildVersion, version); 131 | } 132 | 133 | private static final String JAVA_VERSION = ".java-version"; 134 | private static final LinkedHashMap> TRY_CHARSETS = new LinkedHashMap<>() {{ 135 | put("UTF-8", tryCharset(StandardCharsets.UTF_8)); 136 | put("UTF-16LE", tryCharset(StandardCharsets.UTF_16LE)); 137 | put("UTF-16BE", tryCharset(StandardCharsets.UTF_16BE)); 138 | put("BOM", tryCharsetWithBOM()); 139 | }}; 140 | 141 | private static Function tryCharset(Charset charset) { 142 | return b -> new String(b, charset); 143 | } 144 | 145 | private static Function tryCharsetWithBOM() { 146 | return b -> { 147 | if (b.length < 2) { 148 | return null; 149 | } 150 | if (b[0] == (byte) 0xFF && b[1] == (byte) 0xFE) { 151 | var bb = new byte[b.length - 2]; 152 | System.arraycopy(b, 2, bb, 0, b.length - 2); 153 | return new String(bb, StandardCharsets.UTF_16LE); 154 | } else if (b[0] == (byte) 0xFE && b[1] == (byte) 0xFF) { 155 | var bb = new byte[b.length - 2]; 156 | System.arraycopy(b, 2, bb, 0, b.length - 2); 157 | return new String(bb, StandardCharsets.UTF_16BE); 158 | } 159 | if (b.length < 3) { 160 | return null; 161 | } 162 | if (b[0] == (byte) 0xEF && b[1] == (byte) 0xBB && b[2] == (byte) 0xBF) { 163 | var bb = new byte[b.length - 3]; 164 | System.arraycopy(b, 3, bb, 0, b.length - 3); 165 | return new String(bb, StandardCharsets.UTF_8); 166 | } 167 | return null; 168 | }; 169 | } 170 | 171 | public static JDKInfoMatcher currentVersion() { 172 | File dir; 173 | try { 174 | dir = new File("").getCanonicalFile(); 175 | } catch (IOException e) { 176 | Logger.warn(LogType.FILE_ERROR, "failed to retrieve current version from file", e); 177 | return null; 178 | } 179 | do { 180 | var path = Path.of(dir.getAbsolutePath(), JAVA_VERSION); 181 | if (path.toFile().exists() && path.toFile().isFile()) { 182 | byte[] contentBytes; 183 | try { 184 | contentBytes = Files.readAllBytes(path); 185 | } catch (IOException e) { 186 | Logger.warn(LogType.FILE_ERROR, STR."failed to retrieve current version from file \{path}", e); 187 | return null; 188 | } 189 | var lastErrors = new ArrayList(); 190 | for (var entry : TRY_CHARSETS.entrySet()) { 191 | var charsetName = entry.getKey(); 192 | var f = entry.getValue(); 193 | var content = f.apply(contentBytes); 194 | if (content == null) { 195 | lastErrors.add(new Exception(STR."unable to parse bytes to string with \{charsetName} in file \{path}")); 196 | continue; 197 | } 198 | content = content.trim(); 199 | content = new String(content.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); 200 | try { 201 | return parseVersion(content); 202 | } catch (ErrorResult e) { 203 | assert Logger.lowLevelDebug(STR."unable to parse file \{path}: \{content}"); 204 | lastErrors.add(e); 205 | } 206 | } 207 | Logger.warn(LogType.FILE_ERROR, STR."failed to retrieve current version from file \{path}: \{ 208 | lastErrors.stream().map(io.vproxy.base.util.Utils::formatErr).toList() 209 | }"); 210 | return null; 211 | } 212 | dir = dir.getParentFile(); 213 | } while (dir != null); 214 | 215 | return null; 216 | } 217 | 218 | public static JDKInfo currentVersion(JDKManConfig config) { 219 | var currentMatcher = Utils.currentVersion(); 220 | JDKInfo current = null; 221 | if (currentMatcher != null) { 222 | current = findProperJDK(config, currentMatcher); 223 | } 224 | if (current != null) { 225 | return current; 226 | } 227 | for (var jdk : config.getJdks()) { 228 | if (jdk.getId().equals(config.getDefaultJDK())) { 229 | return jdk; 230 | } 231 | } 232 | // still not found 233 | if (config.getJdks().isEmpty()) { 234 | // no jdk registered 235 | return null; 236 | } 237 | // has jdk, but non match the default id 238 | Logger.shouldNotHappen(STR."unable to find jdk with id == \{config.getDefaultJDK()}"); 239 | return config.getJdks().getFirst(); 240 | } 241 | 242 | private static JDKInfo findProperJDK(JDKManConfig config, JDKInfoMatcher currentMatcher) { 243 | var ls = new ArrayList(); 244 | var optsList = List.of( 245 | // most strict matching 246 | new MatchOptions(), 247 | // skip build version 248 | new MatchOptions() 249 | .setMatchBuildVersion(false), 250 | // skip build version and implementor 251 | new MatchOptions() 252 | .setMatchBuildVersion(false) 253 | .setMatchImplementor(false), 254 | // most loose matching 255 | new MatchOptions(false) 256 | ); 257 | for (var opts : optsList) { 258 | for (var jdk : config.getJdks()) { 259 | if (currentMatcher.match(jdk, opts)) { 260 | ls.add(jdk); 261 | } 262 | } 263 | if (!ls.isEmpty()) { 264 | ls.sort(JDKInfo::compareTo); 265 | return ls.getFirst(); 266 | } 267 | } 268 | return null; 269 | } 270 | 271 | public static String fileMD5(File file) throws IOException { 272 | MessageDigest md; 273 | try { 274 | md = MessageDigest.getInstance("MD5"); 275 | } catch (NoSuchAlgorithmException e) { 276 | Logger.shouldNotHappen("unable to find md alg: MD5"); 277 | throw new RuntimeException(e); 278 | } 279 | byte[] buf = new byte[256 * 1024]; 280 | try (var fis = new FileInputStream(file); var dis = new DigestInputStream(fis, md)) { 281 | //noinspection StatementWithEmptyBody 282 | while (dis.read(buf) != -1) { 283 | } 284 | } 285 | var md5Hash = md.digest(); 286 | StringBuilder sb = new StringBuilder(); 287 | for (byte b : md5Hash) { 288 | sb.append(String.format("%02x", b)); 289 | } 290 | return sb.toString(); 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module io.vproxy.jdkman { 2 | requires kotlin.stdlib; 3 | requires vjson; 4 | requires io.vproxy.base; 5 | requires org.graalvm.nativeimage; 6 | opens io.vproxy.jdkman.res; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/resources/io/vproxy/jdkman/res/jdkman_proxy-windows-x86_64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wkgcass/jdkman/85c6d62fac5e504f334572034069afacd51ecfbd/src/main/resources/io/vproxy/jdkman/res/jdkman_proxy-windows-x86_64.exe -------------------------------------------------------------------------------- /src/main/rust/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "jdkman-proxy" 7 | version = "1.0.0" 8 | -------------------------------------------------------------------------------- /src/main/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "jdkman-proxy" 3 | version = "1.0.0" 4 | edition = "2021" 5 | 6 | [profile.release] 7 | opt-level = 'z' 8 | lto = true 9 | -------------------------------------------------------------------------------- /src/main/rust/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::process::{Command, Stdio}; 2 | 3 | fn main() { 4 | let mut args: Vec<_> = std::env::args().collect(); 5 | if args.len() == 0 { 6 | println!("{}", "failed to determine the program to be executed: empty arguments list"); 7 | std::process::exit(1) 8 | } 9 | let mut name = args[0].clone(); 10 | if name.contains("/") { 11 | let idx = name.rfind("/").unwrap(); 12 | name = name.split_off(idx + 1); 13 | } 14 | if name.contains("\\") { 15 | let idx = name.rfind("\\").unwrap(); 16 | name = name.split_off(idx + 1); 17 | } 18 | 19 | let output = Command::new("jdkman").arg("which") 20 | .output() 21 | .expect("Failed to execute `jdkman which`"); 22 | let stdout = String::from_utf8(output.stdout) 23 | .expect("Invalid UTF-8 output from `jdkman which`"); 24 | if !output.status.success() { 25 | println!("failed to run `jdkman which`, stdout: {}", stdout); 26 | std::process::exit(output.status.code().unwrap_or(1)); 27 | } 28 | let javahome = stdout.trim(); 29 | 30 | let mut exe_path_buf = std::path::PathBuf::new(); 31 | exe_path_buf.push(javahome); 32 | exe_path_buf.push("bin"); 33 | exe_path_buf.push(name); 34 | let exe = exe_path_buf.into_os_string().into_string().unwrap(); 35 | args.remove(0); 36 | 37 | let mut child = Command::new(exe.clone()) 38 | .args(args) 39 | .stdin(Stdio::inherit()) 40 | .stdout(Stdio::inherit()) 41 | .stderr(Stdio::inherit()) 42 | .spawn().expect(format!("Failed to execute command {}", exe).as_str()); 43 | 44 | let exit_status = child.wait().unwrap(); 45 | std::process::exit(exit_status.code().unwrap()); 46 | } 47 | --------------------------------------------------------------------------------