├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jshellw ├── settings.gradle └── src └── main └── java └── tech └── toparvion └── sample └── jshell └── SpringBootJShellAdapter.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | 26 | ### JetBrains template 27 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 28 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 29 | 30 | # User-specific stuff 31 | .idea/**/workspace.xml 32 | .idea/**/tasks.xml 33 | .idea/**/usage.statistics.xml 34 | .idea/**/dictionaries 35 | .idea/**/shelf 36 | 37 | # Sensitive or high-churn files 38 | .idea/**/dataSources/ 39 | .idea/**/dataSources.ids 40 | .idea/**/dataSources.local.xml 41 | .idea/**/sqlDataSources.xml 42 | .idea/**/dynamic.xml 43 | .idea/**/uiDesigner.xml 44 | .idea/**/dbnavigator.xml 45 | 46 | # Gradle 47 | .idea/**/gradle.xml 48 | .idea/**/libraries 49 | 50 | # Gradle and Maven with auto-import 51 | # When using Gradle or Maven with auto-import, you should exclude module files, 52 | # since they will be recreated, and may cause churn. Uncomment if using 53 | # auto-import. 54 | .idea/modules.xml 55 | .idea/*.iml 56 | .idea/modules 57 | 58 | 59 | # File-based project format 60 | *.iws 61 | 62 | # IntelliJ 63 | out/ 64 | 65 | # mpeltonen/sbt-idea plugin 66 | .idea_modules/ 67 | 68 | # Editor-based Rest Client 69 | .idea/httpRequests 70 | 71 | ### Gradle template 72 | .gradle 73 | /build/ 74 | 75 | # Ignore Gradle GUI config 76 | gradle-app.setting 77 | 78 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 79 | !gradle-wrapper.jar 80 | 81 | # Cache of project 82 | .gradletasknamecache 83 | 84 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 85 | # gradle/wrapper/gradle-wrapper.properties 86 | 87 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019-2022 Vladimir Plizga 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBoot JShell Adapter 2 | A simple script to launch [JShell](http://openjdk.java.net/jeps/222) against Spring Boot packaged classpath. 3 | 4 | The script can be useful to quickly prototype on non-development environments (like Docker containers) where environment difference matters (e.g. OS features, file system structure, network policy restrictions, etc). 5 | 6 | ## Usage 7 | ### Deploy 8 | 9 | 0. Make sure you have Java 11+ installed on target environment 10 | 11 | 1. Copy [`jshellw`](https://github.com/Toparvion/springboot-jshell-adapter/blob/master/jshellw) wrapper script into destination, e.g. 12 | ```bash 13 | $ sudo docker cp jshellw mycontainer:/microservice/jshellw 14 | ``` 15 | 16 | 2. Make the script executable 17 | ```bash 18 | $ sudo docker exec -w /microservice mycontainer chmod +x jshellw 19 | ``` 20 | 21 | 3. Run the script pointing to Spring Boot JAR or WAR archive 22 | ```bash 23 | $ sudo docker exec -it -w /microservice mycontainer ./jshellw app.jar 24 | ``` 25 | 26 | The output should look like: 27 | ```text 28 | Created temp directory '/tmp/...'. Extracting classpath content... 29 | Extracted 191 files from the archive to '/tmp/.../BOOT-INF'. 30 | Starting JShell with '/usr/lib/jvm/java-11-openjdk-amd64/bin/jshell --feedback verbose --class-path /tmp/.../BOOT-INF/classes:/tmp/.../BOOT-INF/lib/*'... 31 | | Welcome to JShell -- Version 11.0.1 32 | | For an introduction type: /help intro 33 | 34 | jshell> 35 | ``` 36 | ##### In case of Windows 37 | To run the script in Windows just execute the following instead of 38 | steps 2 and 3: 39 | ``` 40 | java --source 11 jshellw app.jar 41 | ``` 42 | 43 | ### Check 44 | To check if classpath has been composed and applied correctly, type `/env` and you should see something like: 45 | ```text 46 | jshell> /env 47 | | --class-path /tmp/.../BOOT-INF/classes:/tmp/.../BOOT-INF/lib/HdrHistogram-2.1.9.jar:...... 48 | ``` 49 | 50 | ### Play 51 | Now you can import any classes from your classpath and work with them in JShell just like you do in your dev environment. 52 | For example: 53 | ``` 54 | jshell> import org.springframework.util.StringUtils 55 | jshell> var cleanedPath = StringUtils.cleanPath(".\\..\\core/inst/meg.dump") 56 | cleanedPath ==> "../core/inst/meg.dump" 57 | | created variable cleanedPath : String 58 | ``` 59 | You can even launch the application at whole by invoking it's main class, e.g. 60 | ``` 61 | jshell> import com.example.spring.boot.application.MainClass 62 | jshell> MainClass.main(new String[0]) 63 | ``` 64 | but before it make sure that current value of `user.dir` system property points to application's home directory (if it matters). 65 | 66 | #### Need help on using JShell? 67 | See this [Comprehensive Guide](https://www.infoq.com/articles/jshell-java-repl) or google for `java repl`. 68 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import java.nio.file.Files 2 | 3 | plugins { 4 | id 'java' 5 | id 'application' 6 | id 'idea' 7 | } 8 | 9 | group 'tech.toparvion.sample' 10 | version '1.0' 11 | 12 | sourceCompatibility = JavaVersion.VERSION_11 13 | mainClassName = 'tech.toparvion.sample.jshell.SpringBootJShellAdapter' 14 | 15 | tasks.register("regenerate") { 16 | group = 'jshellw' 17 | description = '(re)Generates JShell wrapper script from SpringBootJShellAdapter class' 18 | 19 | doLast { 20 | def srcFile = file('src/main/java/tech/toparvion/sample/jshell/SpringBootJShellAdapter.java') 21 | def dstFile = file('jshellw') 22 | def dstWriter = Files.newBufferedWriter(dstFile.toPath()) 23 | def javaHome = project.hasProperty("javaHome") 24 | ? javaHome 25 | : '/usr' 26 | dstWriter.write("#!$javaHome/bin/java --source 11") 27 | dstWriter.newLine() 28 | dstWriter.newLine() 29 | def srcReader = Files.newBufferedReader(srcFile.toPath()) 30 | srcReader.transferTo(dstWriter) 31 | dstWriter.close() 32 | srcReader.close() 33 | println "JShell wrapper script has been (re)generated with JavaHome=$javaHome/. How to use wrapper:\n" + 34 | "1. Copy it to the destination (e.g. with 'docker cp' command)\n" + 35 | "2. Make it executable: 'chmod +x jshellw'\n" + 36 | "3. Run it with path to Spring Boot application JAR, e.g. './jshell /opt/app/spring-boot-app.jar'" 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Toparvion/springboot-jshell-adapter/770d79d70dea54a43c2009ee57277067ab6bbf34/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /jshellw: -------------------------------------------------------------------------------- 1 | #!/usr/bin/java --source 11 2 | 3 | package tech.toparvion.sample.jshell; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | import java.nio.file.DirectoryStream; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.Paths; 13 | import java.util.Comparator; 14 | import java.util.List; 15 | import java.util.zip.ZipEntry; 16 | import java.util.zip.ZipInputStream; 17 | 18 | import static java.lang.String.format; 19 | 20 | /** 21 | * An adapter for JShell to run against Spring Boot packaged classpath.

22 | * The program does the following:

    23 | *
  1. Locates given Spring Boot JAR/WAR file and checks it for reading
  2. 24 | *
  3. Extracts its {@code BOOT-INF} directory content into temporary directory ({@code java.io.tmp})
  4. 25 | *
  5. Composes a string of all paths to all extracted jars and a path to {@code classes} dir
  6. 26 | *
  7. Launches JShell with the composed string as {@code --class-path} option
  8. 27 | *
  9. After JShell exit, deletes temporary directory and exits as well
  10. 28 | *
29 | * 30 | * @author Toparvion 31 | * @see Readme on GitHub 32 | */ 33 | public class SpringBootJShellAdapter { 34 | private static final String BOOT_INF_DIR_NAME = "BOOT-INF/"; 35 | private static final String WEB_INF_DIR_NAME = "WEB-INF/"; 36 | 37 | public static void main(String[] args) throws IOException, InterruptedException { 38 | if (args.length < 1) { 39 | System.out.println("Usage: $ jshellw "); 40 | System.exit(1); 41 | } 42 | Path extractDirPath = extractClasspathFiles(args[0]); 43 | String jshellClasspathString = composeClasspathString(extractDirPath); 44 | launchJShell(jshellClasspathString); 45 | } 46 | 47 | private static Path extractClasspathFiles(String appArchivePathString) throws IOException { 48 | var appArchivePath = Paths.get(appArchivePathString); 49 | if (!Files.isReadable(appArchivePath)) { 50 | throw new IllegalArgumentException(format("File '%s' cannot be read. Check its path and permissions.", appArchivePathString)); 51 | } 52 | Path extractRoot = Files.createTempDirectory("springboot-jshell-adapter-"); 53 | Runtime.getRuntime().addShutdownHook(new Thread(() -> deletePathRecursively(extractRoot))); 54 | System.out.printf("Created temp directory '%s'. Extracting classpath content...\n", extractRoot); 55 | var filesCount = 0; 56 | try (InputStream fis = Files.newInputStream(appArchivePath)) { 57 | ZipInputStream zis = new ZipInputStream(fis); 58 | ZipEntry nextEntry; 59 | while ((nextEntry = zis.getNextEntry()) != null) { 60 | String archivedEntryPath = nextEntry.getName(); 61 | var isPathAcceptable = archivedEntryPath.startsWith(BOOT_INF_DIR_NAME) 62 | || archivedEntryPath.startsWith(WEB_INF_DIR_NAME); 63 | if (!isPathAcceptable) { 64 | continue; 65 | } 66 | // System.out.printf("Processing archive entry: %s\n", archivedEntryPath); 67 | Path extractedEntryPath = extractRoot.resolve(archivedEntryPath); 68 | if (nextEntry.isDirectory()) { 69 | Files.createDirectories(extractedEntryPath); 70 | 71 | } else { 72 | OutputStream nextFileOutStream = Files.newOutputStream(extractedEntryPath); 73 | zis.transferTo(nextFileOutStream); 74 | nextFileOutStream.close(); 75 | filesCount++; 76 | } 77 | } 78 | zis.closeEntry(); 79 | } 80 | Path infPath; 81 | try (DirectoryStream dirStream = Files.newDirectoryStream(extractRoot)) { 82 | infPath = dirStream.iterator().next().toAbsolutePath(); // it's enough to take the very first path only 83 | } 84 | System.out.printf("Extracted %d files from the archive to '%s'.\n", filesCount, infPath); 85 | return infPath; 86 | } 87 | 88 | private static String composeClasspathString(Path infPath) { 89 | return infPath.resolve("classes/").toAbsolutePath().toString() + 90 | System.getProperty("path.separator") + 91 | infPath.resolve("lib/").toAbsolutePath().toString() + 92 | System.getProperty("file.separator") + 93 | '*'; 94 | } 95 | 96 | private static void launchJShell(String jshellClassPath) throws InterruptedException, IOException { 97 | var jshellExecutable = System.getProperty("os.name").toLowerCase().startsWith("windows") 98 | ? "jshell.exe" 99 | : "jshell"; 100 | var jshellPath = Paths.get(System.getProperty("java.home")) 101 | .resolve("bin") 102 | .resolve(jshellExecutable) 103 | .toAbsolutePath() 104 | .toString(); 105 | var jshellArgs = List.of( 106 | jshellPath, 107 | "--feedback", "verbose", 108 | "--class-path", jshellClassPath 109 | ); 110 | ProcessBuilder jshellLauncher = new ProcessBuilder(jshellArgs); 111 | System.out.printf("Starting JShell with '%s'...\n", String.join(" ", jshellArgs)); 112 | jshellLauncher.inheritIO(); 113 | int jshellExitCode = jshellLauncher.start().waitFor(); 114 | System.out.printf("JShell exited with code %d.\n", jshellExitCode); 115 | } 116 | 117 | private static void deletePathRecursively(Path path2delete) { 118 | System.out.printf("Deleting temp directory '%s'...\n", path2delete); 119 | try { 120 | //noinspection ResultOfMethodCallIgnored 121 | Files.walk(path2delete) 122 | .sorted(Comparator.reverseOrder()) 123 | .map(Path::toFile) 124 | .forEach(File::delete); 125 | System.out.println("Temp directory deleted."); 126 | } catch (IOException e) { 127 | e.printStackTrace(); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'springboot-jshell-adapter' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/tech/toparvion/sample/jshell/SpringBootJShellAdapter.java: -------------------------------------------------------------------------------- 1 | package tech.toparvion.sample.jshell; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.OutputStream; 7 | import java.nio.file.DirectoryStream; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.Paths; 11 | import java.util.Comparator; 12 | import java.util.List; 13 | import java.util.zip.ZipEntry; 14 | import java.util.zip.ZipInputStream; 15 | 16 | import static java.lang.String.format; 17 | 18 | /** 19 | * An adapter for JShell to run against Spring Boot packaged classpath.

20 | * The program does the following:

    21 | *
  1. Locates given Spring Boot JAR/WAR file and checks it for reading
  2. 22 | *
  3. Extracts its {@code BOOT-INF} or {@code WEB-INF} directory content into temporary directory ({@code java.io.tmp})
  4. 23 | *
  5. Composes a string for passing to JShell as {@code --class-path} option
  6. 24 | *
  7. Launches JShell with the composed option
  8. 25 | *
  9. After JShell's exit, deletes temporary directory and exits as well
  10. 26 | *
27 | * 28 | * @author Toparvion 29 | * @see Readme on GitHub 30 | */ 31 | public class SpringBootJShellAdapter { 32 | private static final String BOOT_INF_DIR_NAME = "BOOT-INF/"; 33 | private static final String WEB_INF_DIR_NAME = "WEB-INF/"; 34 | 35 | public static void main(String[] args) throws IOException, InterruptedException { 36 | if (args.length < 1) { 37 | System.out.println("Usage: $ jshellw "); 38 | System.exit(1); 39 | } 40 | Path extractDirPath = extractClasspathFiles(args[0]); 41 | String jshellClasspathString = composeClasspathString(extractDirPath); 42 | launchJShell(jshellClasspathString); 43 | } 44 | 45 | private static Path extractClasspathFiles(String appArchivePathString) throws IOException { 46 | var appArchivePath = Paths.get(appArchivePathString); 47 | if (!Files.isReadable(appArchivePath)) { 48 | throw new IllegalArgumentException(format("File '%s' cannot be read. Check its path and permissions.", appArchivePathString)); 49 | } 50 | Path extractRoot = Files.createTempDirectory("springboot-jshell-adapter-"); 51 | Runtime.getRuntime().addShutdownHook(new Thread(() -> deletePathRecursively(extractRoot))); 52 | System.out.printf("Created temp directory '%s'. Extracting classpath content...\n", extractRoot); 53 | var filesCount = 0; 54 | try (InputStream fis = Files.newInputStream(appArchivePath)) { 55 | ZipInputStream zis = new ZipInputStream(fis); 56 | ZipEntry nextEntry; 57 | while ((nextEntry = zis.getNextEntry()) != null) { 58 | String archivedEntryPath = nextEntry.getName(); 59 | var isPathAcceptable = archivedEntryPath.startsWith(BOOT_INF_DIR_NAME) 60 | || archivedEntryPath.startsWith(WEB_INF_DIR_NAME); 61 | if (!isPathAcceptable) { 62 | continue; 63 | } 64 | // System.out.printf("Processing archive entry: %s\n", archivedEntryPath); 65 | Path extractedEntryPath = extractRoot.resolve(archivedEntryPath); 66 | if (nextEntry.isDirectory()) { 67 | Files.createDirectories(extractedEntryPath); 68 | 69 | } else { 70 | OutputStream nextFileOutStream = Files.newOutputStream(extractedEntryPath); 71 | zis.transferTo(nextFileOutStream); 72 | nextFileOutStream.close(); 73 | filesCount++; 74 | } 75 | } 76 | zis.closeEntry(); 77 | } 78 | Path infPath; 79 | try (DirectoryStream dirStream = Files.newDirectoryStream(extractRoot)) { 80 | infPath = dirStream.iterator().next().toAbsolutePath(); // it's enough to take the very first path only 81 | } 82 | System.out.printf("Extracted %d files from the archive to '%s'.\n", filesCount, infPath); 83 | return infPath; 84 | } 85 | 86 | private static String composeClasspathString(Path infPath) { 87 | return infPath.resolve("classes/").toAbsolutePath().toString() + 88 | System.getProperty("path.separator") + 89 | infPath.resolve("lib/").toAbsolutePath().toString() + 90 | System.getProperty("file.separator") + 91 | '*'; 92 | } 93 | 94 | private static void launchJShell(String jshellClassPath) throws InterruptedException, IOException { 95 | var jshellExecutable = System.getProperty("os.name").toLowerCase().startsWith("windows") 96 | ? "jshell.exe" 97 | : "jshell"; 98 | var jshellPath = Paths.get(System.getProperty("java.home")) 99 | .resolve("bin") 100 | .resolve(jshellExecutable) 101 | .toAbsolutePath() 102 | .toString(); 103 | var jshellArgs = List.of( 104 | jshellPath, 105 | "--feedback", "verbose", 106 | "--class-path", jshellClassPath 107 | ); 108 | ProcessBuilder jshellLauncher = new ProcessBuilder(jshellArgs); 109 | System.out.printf("Starting JShell with '%s'...\n", String.join(" ", jshellArgs)); 110 | jshellLauncher.inheritIO(); 111 | int jshellExitCode = jshellLauncher.start().waitFor(); 112 | System.out.printf("JShell exited with code %d.\n", jshellExitCode); 113 | } 114 | 115 | private static void deletePathRecursively(Path path2delete) { 116 | System.out.printf("Deleting temp directory '%s'...\n", path2delete); 117 | try { 118 | //noinspection ResultOfMethodCallIgnored 119 | Files.walk(path2delete) 120 | .sorted(Comparator.reverseOrder()) 121 | .map(Path::toFile) 122 | .forEach(File::delete); 123 | System.out.println("Temp directory deleted."); 124 | } catch (IOException e) { 125 | e.printStackTrace(); 126 | } 127 | } 128 | } 129 | --------------------------------------------------------------------------------