Debug JSP using Eclipse and JBoss - java

I need to debug JSP files using Eclipse and JBoss. I have a very big project. I have made remote debug. I configured JBoss and created debug configuration in Eclipse. If i put breakpoint in some place inside java class - everything works well and execution stops at this breakpoint. But then i'm trying to do the same thing inside JSP file execution doesn't stop at my breakpoint. What should i do to make JSP breakpoints work?
After building and compilation i'm getting ear file.
I'm using Eclipse Luna for Java EE developers and JBoss Application Server 7.1.1.
I'm setting breakpoints on java code inside jsp file.
JBoss starts with with bat file:
#echo off
rem -------------------------------------------------------------------------
rem JBoss Bootstrap Script for Windows
rem -------------------------------------------------------------------------
rem $Id$
#if not "%ECHO%" == "" echo %ECHO%
#if "%OS%" == "Windows_NT" setlocal
if "%OS%" == "Windows_NT" (
set "DIRNAME=%~dp0%"
) else (
set DIRNAME=.\
)
rem Read an optional configuration file.
if "x%STANDALONE_CONF%" == "x" (
set "STANDALONE_CONF=%DIRNAME%standalone.conf.bat"
)
if exist "%STANDALONE_CONF%" (
echo Calling "%STANDALONE_CONF%"
call "%STANDALONE_CONF%" %*
) else (
echo Config file not found "%STANDALONE_CONF%"
)
pushd %DIRNAME%..
set "RESOLVED_JBOSS_HOME=%CD%"
popd
if "x%JBOSS_HOME%" == "x" (
set "JBOSS_HOME=%RESOLVED_JBOSS_HOME%"
)
pushd "%JBOSS_HOME%"
set "SANITIZED_JBOSS_HOME=%CD%"
popd
if "%RESOLVED_JBOSS_HOME%" NEQ "%SANITIZED_JBOSS_HOME%" (
echo WARNING JBOSS_HOME may be pointing to a different installation - unpredictable results may occur.
)
set DIRNAME=
if "%OS%" == "Windows_NT" (
set "PROGNAME=%~nx0%"
) else (
set "PROGNAME=standalone.bat"
)
rem Setup JBoss specific properties
set JAVA_OPTS=%JAVA_OPTS% -Xdebug -Xnoagent
set JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=6687,server=y,suspend=n
set JAVA_OPTS=%JAVA_OPTS% -Dprogram.name=%PROGNAME%
set JAVA_OPTS=%JAVA_OPTS% -Dlog4j.ignoreTCL=true
set JAVA_OPTS=%JAVA_OPTS% -Dwin.debug=0
set JAVA_OPTS=%JAVA_OPTS% -Djava.net.preferIPv4Stack=true
set JAVA_OPTS=%JAVA_OPTS% -Xms256m -Xmx2024m -XX:MaxPermSize=1024m
set JAVA_OPTS=%JAVA_OPTS% -Djavax.net.ssl.trustStore=C:/java/jdk1.7.0_25/jre/lib/security/cacerts
set JAVA_HOME=C:\Java\jdk1.7.0_25\
if "x%JAVA_HOME%" == "x" (
set JAVA=java
echo JAVA_HOME is not set. Unexpected results may occur.
echo Set JAVA_HOME to the directory of your local JDK to avoid this message.
) else (
set "JAVA=%JAVA_HOME%\bin\java"
)
if not "%PRESERVE_JAVA_OPTS%" == "true" (
rem Add -client to the JVM options, if supported (32 bit VM), and not overriden
echo "%JAVA_OPTS%" | findstr /I \-server > nul
if errorlevel == 1 (
"%JAVA%" -client -version 2>&1 | findstr /I /C:"Client VM" > nul
if not errorlevel == 1 (
set "JAVA_OPTS=-client %JAVA_OPTS%"
)
)
rem Add compressed oops, if supported (64 bit VM), and not overriden
echo "%JAVA_OPTS%" | findstr /I "\-XX:\-UseCompressedOops \-client" > nul
if errorlevel == 1 (
"%JAVA%" -XX:+UseCompressedOops -version > nul 2>&1
if not errorlevel == 1 (
set "JAVA_OPTS=-XX:+UseCompressedOops %JAVA_OPTS%"
)
)
rem Add tiered compilation, if supported (64 bit VM), and not overriden
echo "%JAVA_OPTS%" | findstr /I "\-XX:\-TieredCompilation \-client" > nul
if errorlevel == 1 (
"%JAVA%" -XX:+TieredCompilation -version > nul 2>&1
if not errorlevel == 1 (
set "JAVA_OPTS=-XX:+TieredCompilation %JAVA_OPTS%"
)
)
)
rem Find jboss-modules.jar, or we can't continue
if exist "%JBOSS_HOME%\jboss-modules.jar" (
set "RUNJAR=%JBOSS_HOME%\jboss-modules.jar"
) else (
echo Could not locate "%JBOSS_HOME%\jboss-modules.jar".
echo Please check that you are in the bin directory when running this script.
goto END
)
rem Setup JBoss specific properties
rem Setup the java endorsed dirs
set JBOSS_ENDORSED_DIRS=%JBOSS_HOME%\lib\endorsed
rem Set default module root paths
if "x%JBOSS_MODULEPATH%" == "x" (
set "JBOSS_MODULEPATH=%JBOSS_HOME%\modules"
)
rem Set the standalone base dir
if "x%JBOSS_BASE_DIR%" == "x" (
set "JBOSS_BASE_DIR=%JBOSS_HOME%\standalone"
)
rem Set the standalone log dir
if "x%JBOSS_LOG_DIR%" == "x" (
set "JBOSS_LOG_DIR=%JBOSS_BASE_DIR%\log"
)
rem Set the standalone configuration dir
if "x%JBOSS_CONFIG_DIR%" == "x" (
set "JBOSS_CONFIG_DIR=%JBOSS_BASE_DIR%/configuration"
)
echo ===============================================================================
echo.
echo JBoss Bootstrap Environment
echo.
echo JBOSS_HOME: %JBOSS_HOME%
echo.
echo JAVA: %JAVA%
echo.
echo JAVA_OPTS: %JAVA_OPTS%
echo.
echo ===============================================================================
echo.
:RESTART
"%JAVA%" %JAVA_OPTS% ^
"-Dorg.jboss.boot.log.file=%JBOSS_LOG_DIR%\boot.log" ^
"-Dlogging.configuration=file:%JBOSS_CONFIG_DIR%/logging.properties" ^
-jar "%JBOSS_HOME%\jboss-modules.jar" ^
-mp "%JBOSS_MODULEPATH%" ^
-jaxpmodule "javax.xml.jaxp-provider" ^
org.jboss.as.standalone ^
-Djboss.home.dir="%JBOSS_HOME%" ^
%*
if ERRORLEVEL 10 goto RESTART
:END
if "x%NOPAUSE%" == "x" pause
:END_NO_PAUSE
I'm not using JBoss tools, but i'm reading how to use them now.
I can't ddebug before putting it in EAR file because it's a huge project and everything depends on everything.

I have this trouble too. I am using Eclipse Luna + JBoss Tools (Luna) + JBoss 7.1.1 Final. JBoss will be started from Eclipse in debugging modus. But no one breakepoint is working in JSP, only in class files.
I found that it is a bug of JBoss 7.1.x (https://developer.jboss.org/message/723813)
I downloaded EAP 6.1 (old name - JBoss 7.2.0) - it is working perfect with JBoss Tools (Luna) 4.2.3 Final.

Related

How to configure Mule ESB (mule.bat) with different Java Version?

I have four JDK installed on my system for multiple modules.
jdk1.8.0_25,
jdk1.7.0_75 and
jdk1.6.0_19
I want to configure or change Mule.bat so that it should pick default Java version different from what set in Java home.
Following is code of Mule.bat but i am not able to find Java Home parameter in it.
#echo off setlocal
rem Copyright (c) 1999, 2006 Tanuki Software Inc. rem rem Java Service Wrapper command based script rem
if "%OS%"=="Windows_NT" goto nt echo This script only works with NT-based versions of Windows. goto :eof
:nt
rem rem Find the application home. rem rem %~dp0 is location of current script under NT set _REALPATH=%~dp0
rem ############################################################### rem Customized for Mule rem
###############################################################
rem Make sure that MULE_HOME is set. If no value was set in the environment, rem use the path that was used to launch this script. Since this script rem resides in the bin folder of the Mule distribution, we need to cut off the rem last 5 chars (\bin\) from the real path to determine the proper MULE_HOME if "%MULE_HOME%" == "" set MULE_HOME=%_REALPATH:~0,-5% echo MULE_HOME is set to %MULE_HOME%
rem If MULE_BASE is not set, set it to MULE_HOME if "%MULE_BASE%" == "" SET MULE_BASE=%MULE_HOME%
if "%MULE_APP%" == "" (
set MULE_APP=mule ) if "%MULE_APP_LONG%" == "" (
set MULE_APP_LONG=Mule )
set PATH=%PATH%;%MULE_HOME%\lib\native\profiler set
_WRAPPER_BASE=%MULE_HOME%\lib\boot\exec\wrapper
rem Configure remote Java debugging options here rem Setting suspend=y will wait for you to connect before proceeding set JPDA_OPTS=-Xdebug
-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
rem ############################################################### rem Decide on the wrapper binary. set
_WRAPPER_EXE=%_WRAPPER_BASE%-windows-x86-32.exe if exist "%_WRAPPER_EXE%" goto validate set
_WRAPPER_EXE=%_WRAPPER_BASE%-windows-x86-64.exe if exist "%_WRAPPER_EXE%" goto validate set _WRAPPER_EXE=%_WRAPPER_BASE%.exe if exist "%_WRAPPER_EXE%" goto validate echo Unable to locate a Wrapper executable using any of the following names: echo %_WRAPPER_BASE%-windows-x86-32.exe echo %_WRAPPER_BASE%-windows-x86-64.exe echo %_WRAPPER_BASE%.exe pause goto :eof
:validate rem Find the requested command. for /F %%v in ('echo %1^|findstr "^console$ ^start$ ^pause$ ^resume$ ^stop$ ^restart$ ^install$ ^remove"') do call :exec set COMMAND=%%v
if "%COMMAND%" == "" (
rem ###############################################################
rem Customized for Mule
rem ###############################################################
echo Running in console/foreground mode by default, use Ctrl-C to exit...
set COMMAND=:console
rem pause
rem goto :eof
rem ############################################################### ) else (
shift )
rem rem Find the wrapper.conf rem :conf set
_WRAPPER_CONF="%_REALPATH%..\conf\wrapper.conf"
rem ############################################################### rem Customized for Mule rem
###############################################################
rem add XML compatibility jars set MULE_ENDORSED=-M-Djava.endorsed.dirs=%MULE_HOME%\lib\endorsed
rem Mule options: Set the working directory to the current one and pass all command-line rem options (-config, -builder, etc.) straight through to the main() method. set MULE_OPTS=set.MULE_APP=%MULE_APP% set.MULE_APP_LONG=%MULE_APP_LONG% set.MULE_HOME="%MULE_HOME%" set.MULE_BASE="%MULE_BASE%" set.MULE_LIB=%MULE_LIB% wrapper.working.dir="%CD%" wrapper.app.parameter.1=%1 wrapper.app.parameter.2=%2 wrapper.app.parameter.3=%3 wrapper.app.parameter.4=%4 wrapper.app.parameter.5=%5 wrapper.app.parameter.6=%6 wrapper.app.parameter.7=%7 wrapper.app.parameter.8=%8 wrapper.app.parameter.9=%9
rem Adding additional jvm arguments to wrapper configuration if needed call "%MULE_HOME%\bin\launcher.bat" "%MULE_HOME%\bin\additional.groovy" %_WRAPPER_CONF% "%JPDA_OPTS%" "%MULE_ENDORSED%" %*
if not ERRORLEVEL 1 goto run goto :eof
:run
rem ############################################################### rem rem Run the application. rem At runtime, the current directory will be that of wrapper.exe rem call :%COMMAND% if errorlevel 1 pause goto :eof
rem ############################################################### rem Customized for Mule rem
###############################################################
:console "%_WRAPPER_EXE%" -c %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:start "%_WRAPPER_EXE%" -t %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:pause "%_WRAPPER_EXE%" -a %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:resume "%_WRAPPER_EXE%" -e %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:stop "%_WRAPPER_EXE%" -p %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:install "%_WRAPPER_EXE%" -i %_WRAPPER_CONF% %MULE_OPTS% goto :eof
:remove "%_WRAPPER_EXE%" -r %_WRAPPER_CONF% %MULE_OPTS% goto :eof
rem ###############################################################
:restart call :stop call :start goto :eof
:exec %* goto :eof
Mule uses the Java Service Wrapper to control the Java Virtual Machine (JVM) from your native OS.
1) You need to make changes to wrapper.conf file:-
$MULE_HOME/conf/wrapper.conf
2) Then you need to set wrapper.java.command parameter in it,
wrapper.java.command=%JAVA_HOME%/bin/java
or
wrapper.java.command=c:/jdk1.6.0/bin/java
JAVA_HOME

how to get latest JRE version in command prompt if windows has more than one JRE version

I am trying get the latest JRE installed in windows using dir command. I Have JRE 1.6 and 1.8 installed on my Windows but I need to get whatever the latest version installed in windows (even in future it may change to 1.8 to 2.0*). Can any one please help on this.
Try this batch for win7
#echo off
#echo off
rem http://technet.microsoft.com/en-us/library/bb490890.aspx
SETLOCAL EnableDelayedExpansion
:: findJDK.bat
rem start:-> Run a command in a separate process, or run a file with its default associated application
rem REGEDIT.EXE: -> Export to a (.REG) file:
rem REGEDIT.EXE [ /L:system | /R:user ] /E exportfile.REG "registry_key"
start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit"
rem TYPE: -> Display text file content in console
rem FIND: -> Search files or standard output
rem reserved key words regarding reg-key -> "JavaHome" "MicroVersion" "RuntimeLib"
rem | Reads the output from one command and writes it to the input of another command. Also known as a pipe.
type reg1.txt | find "JavaHome" > reg2.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg2.txt) do (
set JavaTemp=%%~x
echo Regedit: JAVA_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JAVA_HOME=%JavaTemp%
set JAVA_HOME=%JAVA_HOME:\\=\%
echo JAVA_HOME was found to be %JAVA_HOME%
start /w regedit /e reg3.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment"
type reg3.txt | find "RuntimeLib" > reg4.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg4.txt) do (
set JavaTemp=%%~x
echo Regedit: JRE_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JRE_HOME=%JavaTemp%
set JRE_HOME=%JRE_HOME:\\=\%
echo JRE_HOME was found to be %JRE_HOME%
goto END
:ERROR
echo A reg1.txt is: & type reg1.txt
echo B reg2.txt is: & type reg2.txt
echo
:END
echo END
pause
java -version:1.8.0_101 -jar jarname.jar
Use above way to invoke java here you can give version of java which you want to use in case there are multiple in your path .

JAVA_OPTS on Apache-Tomcat 7

I have to add an option to tomcat in order to make JAAS Authentication work.
I opened catalina.bat and added this line :
set JAVA_OPTS = $JAVA_OPTS -Djava.security.auth.login.config==../conf/jaas.config
in order to have this final version of the file :
setlocal
set JAVA_OPTS = $JAVA_OPTS -Djava.security.auth.login.config==../conf/jaas.config
rem Suppress Terminate batch job on CTRL+C
if not ""%1"" == ""run"" goto mainEntry
if "%TEMP%" == "" goto mainEntry
if exist "%TEMP%\%~nx0.run" goto mainEntry
echo Y>"%TEMP%\%~nx0.run"
if not exist "%TEMP%\%~nx0.run" goto mainEntry
echo Y>"%TEMP%\%~nx0.Y"
call "%~f0" %* <"%TEMP%\%~nx0.Y"
rem Use provided errorlevel
set RETVAL=%ERRORLEVEL%
del /Q "%TEMP%\%~nx0.Y" >NUL 2>&1
exit /B %RETVAL%
:mainEntry
del /Q "%TEMP%\%~nx0.run" >NUL 2>&1
rem Guess CATALINA_HOME if not defined
set "CURRENT_DIR=%cd%"
if not "%CATALINA_HOME%" == "" goto gotHome
set "CATALINA_HOME=%CURRENT_DIR%"
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
cd ..
set "CATALINA_HOME=%cd%"
cd "%CURRENT_DIR%"
:gotHome
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
echo The CATALINA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
goto end
:okHome
rem Copy CATALINA_BASE from CATALINA_HOME if not defined
if not "%CATALINA_BASE%" == "" goto gotBase
set "CATALINA_BASE=%CATALINA_HOME%"
:gotBase
rem Ensure that any user defined CLASSPATH variables are not used on startup,
rem but allow them to be specified in setenv.bat, in rare case when it is needed.
set CLASSPATH=
rem Get standard environment variables
if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome
call "%CATALINA_BASE%\bin\setenv.bat"
goto setenvDone
:checkSetenvHome
if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"
:setenvDone
rem Get standard Java environment variables
if exist "%CATALINA_HOME%\bin\setclasspath.bat" goto okSetclasspath
echo Cannot find "%CATALINA_HOME%\bin\setclasspath.bat"
echo This file is needed to run this program
goto end
:okSetclasspath
call "%CATALINA_HOME%\bin\setclasspath.bat" %1
if errorlevel 1 goto end
rem Add on extra jar file to CLASSPATH
rem Note that there are no quotes as we do not want to introduce random
rem quotes into the CLASSPATH
if "%CLASSPATH%" == "" goto emptyClasspath
set "CLASSPATH=%CLASSPATH%;"
:emptyClasspath
set "CLASSPATH=%CLASSPATH%%CATALINA_HOME%\bin\bootstrap.jar"
if not "%CATALINA_TMPDIR%" == "" goto gotTmpdir
set "CATALINA_TMPDIR=%CATALINA_BASE%\temp"
:gotTmpdir
rem Add tomcat-juli.jar to classpath
rem tomcat-juli.jar can be over-ridden per instance
if not exist "%CATALINA_BASE%\bin\tomcat-juli.jar" goto juliClasspathHome
set "CLASSPATH=%CLASSPATH%;%CATALINA_BASE%\bin\tomcat-juli.jar"
goto juliClasspathDone
:juliClasspathHome
set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\bin\tomcat-juli.jar"
:juliClasspathDone
if not "%LOGGING_CONFIG%" == "" goto noJuliConfig
set LOGGING_CONFIG=-Dnop
if not exist "%CATALINA_BASE%\conf\logging.properties" goto noJuliConfig
set LOGGING_CONFIG=-Djava.util.logging.config.file="%CATALINA_BASE%\conf\logging.properties"
:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"
if not "%LOGGING_MANAGER%" == "" goto noJuliManager
set LOGGING_MANAGER=-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"
rem ----- Execute The Requested Command ---------------------------------------
echo Using CATALINA_BASE: "%CATALINA_BASE%"
echo Using CATALINA_HOME: "%CATALINA_HOME%"
echo Using CATALINA_TMPDIR: "%CATALINA_TMPDIR%"
if ""%1"" == ""debug"" goto use_jdk
echo Using JRE_HOME: "%JRE_HOME%"
goto java_dir_displayed
:use_jdk
echo Using JAVA_HOME: "%JAVA_HOME%"
:java_dir_displayed
echo Using CLASSPATH: "%CLASSPATH%"
set _EXECJAVA=%_RUNJAVA%
set MAINCLASS=org.apache.catalina.startup.Bootstrap
set ACTION=start
set SECURITY_POLICY_FILE=
set DEBUG_OPTS=
set JPDA=
if not ""%1"" == ""jpda"" goto noJpda
set JPDA=jpda
if not "%JPDA_TRANSPORT%" == "" goto gotJpdaTransport
set JPDA_TRANSPORT=dt_socket
:gotJpdaTransport
if not "%JPDA_ADDRESS%" == "" goto gotJpdaAddress
set JPDA_ADDRESS=8000
:gotJpdaAddress
if not "%JPDA_SUSPEND%" == "" goto gotJpdaSuspend
set JPDA_SUSPEND=n
:gotJpdaSuspend
if not "%JPDA_OPTS%" == "" goto gotJpdaOpts
set JPDA_OPTS=-agentlib:jdwp=transport=%JPDA_TRANSPORT%,address=%JPDA_ADDRESS%,server=y,suspend=%JPDA_SUSPEND%
:gotJpdaOpts
shift
:noJpda
if ""%1"" == ""debug"" goto doDebug
if ""%1"" == ""run"" goto doRun
if ""%1"" == ""start"" goto doStart
if ""%1"" == ""stop"" goto doStop
if ""%1"" == ""configtest"" goto doConfigTest
if ""%1"" == ""version"" goto doVersion
echo Usage: catalina ( commands ... )
echo commands:
echo debug Start Catalina in a debugger
echo debug -security Debug Catalina with a security manager
echo jpda start Start Catalina under JPDA debugger
echo run Start Catalina in the current window
echo run -security Start in the current window with security manager
echo start Start Catalina in a separate window
echo start -security Start in a separate window with security manager
echo stop Stop Catalina
echo configtest Run a basic syntax check on server.xml
echo version What version of tomcat are you running?
goto end
:doDebug
shift
set _EXECJAVA=%_RUNJDB%
set DEBUG_OPTS=-sourcepath "%CATALINA_HOME%\..\..\java"
if not ""%1"" == ""-security"" goto execCmd
shift
echo Using Security Manager
set "SECURITY_POLICY_FILE=%CATALINA_BASE%\conf\catalina.policy"
goto execCmd
:doRun
shift
if not ""%1"" == ""-security"" goto execCmd
shift
echo Using Security Manager
set "SECURITY_POLICY_FILE=%CATALINA_BASE%\conf\catalina.policy"
goto execCmd
:doStart
shift
if "%TITLE%" == "" set TITLE=Tomcat
set _EXECJAVA=start "%TITLE%" %_RUNJAVA%
if not ""%1"" == ""-security"" goto execCmd
shift
echo Using Security Manager
set "SECURITY_POLICY_FILE=%CATALINA_BASE%\conf\catalina.policy"
goto execCmd
:doStop
shift
set ACTION=stop
set CATALINA_OPTS=
goto execCmd
:doConfigTest
shift
set ACTION=configtest
set CATALINA_OPTS=
goto execCmd
:doVersion
%_EXECJAVA% -classpath "%CATALINA_HOME%\lib\catalina.jar" org.apache.catalina.util.ServerInfo
goto end
:execCmd
rem Get remaining unshifted command line arguments and save them in the
set CMD_LINE_ARGS=
:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs
:doneSetArgs
rem Execute Java with the applicable properties
if not "%JPDA%" == "" goto doJpda
if not "%SECURITY_POLICY_FILE%" == "" goto doSecurity
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doSecurity
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Djava.security.manager -Djava.security.policy=="%SECURITY_POLICY_FILE%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doJpda
if not "%SECURITY_POLICY_FILE%" == "" goto doSecurityJpda
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %JPDA_OPTS% %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:doSecurityJpda
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %JPDA_OPTS% %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Djava.security.manager -Djava.security.policy=="%SECURITY_POLICY_FILE%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
:end
It doesnt seem to be working as I get the same error of no LoginModule defined.
You need to delete that space after the JAVA_OPTS variable name, otherwise it will not get picked up.
Instead of this:
JAVA_OPTS = [params]
Do:
JAVA_OPTS= [params]
I used Eclipse server launch options to make it work, appearently for a reason or another it doesnt get detected using the catalina.bat.

Batch files for Java

In order to use a USB magstripe reader for accepting credit cards on a PC, my company uses Java on our web portal. In order to get the magstripe reader working properly, our Helpdesk has to guide customers through moving rxtxSerial.dll and RXTXcomm.jar files to the respective bin and lib\ext folders in Windows. We also have to add two URLs to the site exceptions list in the Java Control Panel. Both of these processes currently involve using the GUI and guiding our customers through doing this on their computers.
Java isn't really a strong suit for me. I am trying to create a batch file (with the .dll and .jar files in the same directory) that will automate both processes so that all a user has to do is run the batch file. However, I am running into a few problems that I'm not entirely prepared for.
I need to be able to have this file work for all possible installation paths of Java on the customer's computer. I am fine having a separate batch file for 32-but and 64-bit Java. However, not every customer has the jre8 folder in their "C:\Program Files (x86)\Java" directory. Sometimes instead of jre8, they will have something like jre1.8.0_31. I need the batch file to be able to account for these differences as well.
As far as my understanding goes, the sites.exceptions file is stored in a subdirectory contained within the user's directory. The problem is that I need to be able to create a batch file that will be able to locate the current user's directory as a part of the full file path. Furthermore, I'm not entirely clear on how to edit the sites.exceptions from the command prompt. I suppose I could have a pre-made exceptions file that gets copied over the the right directory (and naturally overriding any currently existing file).
I'm very new to the IT field, so I don't know if what I am asking is possible or if I'm explaining this right. I would really appreciate some help.
I think this might help you. This program detects wheter Java is installed or not. It also detects which version of java etc.
#echo off
if "%OS%" == "Windows_NT" setlocal
::::::::::::::::::::::::::::::::::::
:: Set JAVA_HOME or JRE_HOME ::
::::::::::::::::::::::::::::::::::::
set JDKKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit
set JDKKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit
set JREKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
set JREKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
reg query "%JDKKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit or 64 bit JDK
echo .Looking for 32 bit JDK on 64 bit machine
goto FINDJDK32
)
set KeyName=%JDKKeyName64%
goto JDKRUN
:FINDJDK32
reg query "%JDKKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit JDK
echo .Looking for 32 bit or 64 bit JRE
goto FINDJRE64
)
set KeyName=%JDKKeyName32%
goto JDKRUN
:FINDJRE64
reg query "%JREKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit or 64 bit JRE
echo .Looking for 32 bit JRE on 64 bit machine
goto FINDJRE32
)
set KeyName=%JREKeyName64%
goto JRERUN
:FINDJRE32
reg query "%JREKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit JRE
echo .Could not set JAVA_HOME or JRE_HOME. Aborting
goto ENDERROR
)
set KeyName=%JREKeyName32%
goto JRERUN
:JDKRUN
echo.
echo Using JDK
set "CURRENT_DIR=%cd%"
set "YOUR_PROGRAM_HOME_HERE=%CURRENT_DIR%"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JAVA_HOME=%%j
echo.
echo Seems fine!
echo Set JAVA_HOME : %JAVA_HOME%
echo Set YOUR_PROGRAM_HOME_HERE : %YOUR_PROGRAM_HOME_HERE%
echo.
goto NEXT
:JRERUN
echo.
echo [XAMPP]: Using JRE
set "CURRENT_DIR=%cd%"
set "YOUR_PROGRAM_HOME_HERE=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JRE_HOME=%%j
echo.
echo Seems fine!
echo Set JRE_HOME : %JRE_HOME%
echo Set YOUR_PROGRAM_HOME_HERE : %CATALINA_HOME%
echo.
:ENDERROR
exit 1
:NEXT
echo Finding Java Version
set Cmd=reg query "%KeyName%" /v CurrentVersion
for /f "tokens=2*" %%i in ('%Cmd% ^| find "CurrentVersion"') do set CVERSION=%%j
echo Java Version: %CVERSION%
echo Starting Service Install...
echo .
rem ----------END JAVA SEARCH-----------------------------------------------------------------
Now we've found the java HomeDirectory we can execute our packets trough java. We can use java trough cmd, so this should need to be easy.
Example of what we can do now:
rem Make sure prerequisite environment variables are set
if not "%JAVA_HOME%" == "" goto gotJdkHome
if not "%JRE_HOME%" == "" goto gotJreHome
echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
echo Service will try to guess them from the registry.
goto runAsUser
:gotJreHome
if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
goto runAsUser
:gotJdkHome
if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
if not "%JRE_HOME%" == "" goto runAsUser
set "JRE_HOME=%JAVA_HOME%\jre"
goto runAsUser
:noJavaHome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
echo NB: JAVA_HOME should point to a JDK not a JRE
goto end
Here comes the main code that let's you run your java applet/program
:doInstall
rem Install the service
echo Installing the service '%SERVICE_NAME%' ...
echo Using PROGRAM_HOME: "%YOUR_PROGRAM_HOME_HERE%"
echo Using JAVA_HOME: "%JAVA_HOME%"
echo Using JRE_HOME: "%JRE_HOME%"
rem Use the environment variables as an example
rem Each command line option is prefixed with PR_
set "PR_INSTALL=%EXECUTABLE%"
rem Add another jar or java file next to it with a semicolon. (still in the quotes)
set "PR_CLASSPATH=%YOUR_PROGRAM_HOME_HERE%\javawishprogram.jar;%YOUR_PROGRAM_HOME_HERE%\MaybeASecondoneIfYouwant.jar"
rem Set the server jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
rem Here you can go further on the JVM or not, you can map out your options.
if exist "%PR_JVM%" goto foundJvm
rem Set the client jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
set PR_JVM=auto
:foundJvm
echo Using JVM: "%PR_JVM%"
rem Here you're launching the main programme.
"%EXECUTABLE%" //IS//%SERVICE_NAME% --StartClass programJava.startup.Bootstrap --StartParams start --StopParams stop --Startup auto
You can do even more with this. But I'll let it to your imagination.
I borowed this script from CATALINA
This is the full script:
INGORE
#echo off
rem Licensed to the Apache Software Foundation (ASF) under one or more
rem contributor license agreements. See the NOTICE file distributed with
rem this work for additional information regarding copyright ownership.
rem The ASF licenses this file to You under the Apache License, Version 2.0
rem (the "License"); you may not use this file except in compliance with
rem the License. You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
if "%OS%" == "Windows_NT" setlocal
rem ---------------------------------------------------------------------------
rem NT Service Install/Uninstall script
rem
rem Options
rem install Install the service using Tomcat7 as service name.
rem Service is installed using default settings.
rem remove Remove the service from the System.
rem
rem name (optional) If the second argument is present it is considered
rem to be new service name
rem
rem $Id: service.bat 1000718 2010-09-24 06:00:00Z mturk $
rem ---------------------------------------------------------------------------
rem ---------XAMPP-------------------------------------------------------------
::::::::::::::::::::::::::::::::::::
:: Set JAVA_HOME or JRE_HOME ::
::::::::::::::::::::::::::::::::::::
echo.
echo [XAMPP]: Searching for JDK or JRE HOME with reg query ...
set JDKKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit
set JDKKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit
set JREKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
set JREKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
reg query "%JDKKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit or 64 bit JDK
echo . [XAMPP]: Looking for 32 bit JDK on 64 bit machine
goto FINDJDK32
)
set KeyName=%JDKKeyName64%
goto JDKRUN
:FINDJDK32
reg query "%JDKKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit JDK
echo . [XAMPP]: Looking for 32 bit or 64 bit JRE
goto FINDJRE64
)
set KeyName=%JDKKeyName32%
goto JDKRUN
:FINDJRE64
reg query "%JREKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit or 64 bit JRE
echo . [XAMPP]: Looking for 32 bit JRE on 64 bit machine
goto FINDJRE32
)
set KeyName=%JREKeyName64%
goto JRERUN
:FINDJRE32
reg query "%JREKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit JRE
echo . [XAMPP]: Could not set JAVA_HOME or JRE_HOME. Aborting
goto ENDERROR
)
set KeyName=%JREKeyName32%
goto JRERUN
:JDKRUN
echo.
echo [XAMPP]: Using JDK
set "CURRENT_DIR=%cd%"
set "CATALINA_HOME=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JAVA_HOME=%%j
echo.
echo [XAMPP]: Seems fine!
echo [XAMPP]: Set JAVA_HOME : %JAVA_HOME%
echo [XAMPP]: Set CATALINA_HOME : %CATALINA_HOME%
echo.
goto NEXT
:JRERUN
echo.
echo [XAMPP]: Using JRE
set "CURRENT_DIR=%cd%"
set "CATALINA_HOME=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JRE_HOME=%%j
echo.
echo [XAMPP]: Seems fine!
echo [XAMPP]: Set JRE_HOME : %JRE_HOME%
echo [XAMPP]: Set CATALINA_HOME : %CATALINA_HOME%
echo.
:ENDERROR
exit 1
:NEXT
echo [XAMPP]: Finding Java Version
set Cmd=reg query "%KeyName%" /v CurrentVersion
for /f "tokens=2*" %%i in ('%Cmd% ^| find "CurrentVersion"') do set CVERSION=%%j
echo [XAMPP]: Java Version: %CVERSION%
echo [XAMPP]: Starting Tomcat Service Install...
echo .
rem ----------END XAMPP-----------------------------------------------------------------
set "SELF=%~dp0%service.bat"
rem Guess CATALINA_HOME if not defined
set "CURRENT_DIR=%cd%"
if not "%CATALINA_HOME%" == "" goto gotHome
set "CATALINA_HOME=%cd%"
if exist "%CATALINA_HOME%\bin\tomcat7.exe" goto okHome
rem CD to the upper dir
cd ..
set "CATALINA_HOME=%cd%"
:gotHome
if exist "%CATALINA_HOME%\bin\tomcat7.exe" goto okHome
echo The tomcat.exe was not found...
echo The CATALINA_HOME environment variable is not defined correctly.
echo This environment variable is needed to run this program
goto end
:okHome
rem Make sure prerequisite environment variables are set
if not "%JAVA_HOME%" == "" goto gotJdkHome
if not "%JRE_HOME%" == "" goto gotJreHome
echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
echo Service will try to guess them from the registry.
goto okJavaHome
:gotJreHome
if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
goto okJavaHome
:gotJdkHome
if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
if not "%JRE_HOME%" == "" goto okJavaHome
set "JRE_HOME=%JAVA_HOME%\jre"
goto okJavaHome
:noJavaHome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
echo NB: JAVA_HOME should point to a JDK not a JRE
goto end
:okJavaHome
if not "%CATALINA_BASE%" == "" goto gotBase
set "CATALINA_BASE=%CATALINA_HOME%"
:gotBase
set "EXECUTABLE=%CATALINA_HOME%\bin\tomcat7.exe"
rem Set default Service name
set SERVICE_NAME=Tomcat7
set PR_DISPLAYNAME=Apache Tomcat 7
if "x%1x" == "xx" goto displayUsage
set SERVICE_CMD=%1
shift
if "x%1x" == "xx" goto checkServiceCmd
:checkUser
if "x%1x" == "x/userx" goto runAsUser
if "x%1x" == "x--userx" goto runAsUser
set SERVICE_NAME=%1
set PR_DISPLAYNAME=Apache Tomcat %1
shift
if "x%1x" == "xx" goto checkServiceCmd
goto checkUser
:runAsUser
shift
if "x%1x" == "xx" goto displayUsage
set SERVICE_USER=%1
shift
runas /env /savecred /user:%SERVICE_USER% "%COMSPEC% /K \"%SELF%\" %SERVICE_CMD% %SERVICE_NAME%"
goto end
:checkServiceCmd
if /i %SERVICE_CMD% == install goto doInstall
if /i %SERVICE_CMD% == remove goto doRemove
if /i %SERVICE_CMD% == uninstall goto doRemove
echo Unknown parameter "%1"
:displayUsage
echo.
echo Usage: service.bat install/remove [service_name] [/user username]
goto end
:doRemove
rem Remove the service
"%EXECUTABLE%" //DS//%SERVICE_NAME%
if not errorlevel 1 goto removed
echo Failed removing '%SERVICE_NAME%' service
goto end
:removed
echo The service '%SERVICE_NAME%' has been removed
goto end
:doInstall
rem Install the service
echo Installing the service '%SERVICE_NAME%' ...
echo Using CATALINA_HOME: "%CATALINA_HOME%"
echo Using CATALINA_BASE: "%CATALINA_BASE%"
echo Using JAVA_HOME: "%JAVA_HOME%"
echo Using JRE_HOME: "%JRE_HOME%"
rem Use the environment variables as an example
rem Each command line option is prefixed with PR_
set PR_DESCRIPTION=Apache Tomcat 7.0.22 Server - http://tomcat.apache.org/
set "PR_INSTALL=%EXECUTABLE%"
set "PR_LOGPATH=%CATALINA_BASE%\logs"
set "PR_CLASSPATH=%CATALINA_HOME%\bin\bootstrap.jar;%CATALINA_BASE%\bin\tomcat-juli.jar;%CATALINA_HOME%\bin\tomcat-juli.jar"
rem Set the server jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
rem Set the client jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
set PR_JVM=auto
:foundJvm
echo Using JVM: "%PR_JVM%"
"%EXECUTABLE%" //IS//%SERVICE_NAME% --StartClass org.apache.catalina.startup.Bootstrap --StopClass org.apache.catalina.startup.Bootstrap --StartParams start --StopParams stop --Startup auto
if not errorlevel 1 goto installed
echo Failed installing '%SERVICE_NAME%' service
goto ENDERROR
:installed
rem Clear the environment variables. They are not needed any more.
set PR_DISPLAYNAME=
set PR_DESCRIPTION=
set PR_INSTALL=
set PR_LOGPATH=
set PR_CLASSPATH=
set PR_JVM=
rem Set extra parameters
"%EXECUTABLE%" //US//%SERVICE_NAME% --JvmOptions "-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\endorsed" --StartMode jvm --StopMode jvm
rem More extra parameters
set "PR_LOGPATH=%CATALINA_BASE%\logs"
set PR_STDOUTPUT=auto
set PR_STDERROR=auto
rem XAMPP: We need special parameters for Java 7
if "%CVERSION%" == "1.7" goto JAVA7
:JAVA
"%EXECUTABLE%" //US//%SERVICE_NAME% ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties" --JvmMs 128 --JvmMx 256
goto FINISH
:JAVA7
"%EXECUTABLE%" //US//%SERVICE_NAME% ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties;-Djava.net.preferIPv4Stack=true" --JvmMs 128 --JvmMx 256
:FINISH
echo The service '%SERVICE_NAME%' has been installed.
:end
cd "%CURRENT_DIR%"

Switching between different JDK versions in Windows

I'm working on few projects and some of them are using different JDK. Switching between JDK versions is not comfortable. So I was wondering if there is any easy way to change it?
I found 2 ways, which should solve this problem, but it doesn't work.
First solution is creating a bat files like this:
#echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_72
echo setting PATH
set PATH=C:\Program Files\Java\jdk1.7.0_72\bin;%PATH%
echo Display java version
java -version
pause
And after running this bat, I see right version of Java. But when I close this CMD and open a new one and type "java -version" it says that I still have 1.8.0_25. So it doesn't work.
Second solution which I found is an application from this site. And it also doesn't work. The same effect as in the first solution.
Any ideas? Because changing JAVA_HOME and PAHT by: Win + Pause -> Advanced System Settings -> Environment Variables -> and editing these variables, is terrible way...
The set command only works for the current terminal. To permanently set a system or user environment variable you can use setx.
setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_72" /m
The /m option is used to set the variable system wide (and not just for the current user). The terminal must be run as administrator to use this option.
The variable will be available in all new terminal windows, but not the current one. If you also want to use the path in the same window, you need to use both set and setx.
You can avoid manipulating the PATH variable if you just once put %JAVA_HOME% in there, instead of the full JDK path. If you change JAVA_HOME, PATH will be updated too.
There are also a few environment variable editors as alternative to the cumbersome Windows environment variable settings. See "Is there a convenient way to edit PATH in Windows 7?" on Super User.
In case if someone want to switch frequently in each new command window then I am using following approach.
Command Prompt Version:
Create batch file using below code. You can add n number of version using if and else blocks.
#echo off
if "%~1" == "11" (
set "JAVA_HOME=C:\Software\openjdk-11+28_windows-x64_bin\jdk-11"
) else (
set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_151"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
Save this batch file as SJV.bat and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".
Now open new command window and just type SJV 11 it will switch to Java 11.
Type SJV 8 it will switch to Java 8.
PowerShell Version
Create powershell(ps1) file using below code. You can add n number of version using if and else blocks.
If($args[0] -eq "11")
{
$env:JAVA_HOME = 'C:\Software\openjdk-11+28_windows-x64_bin\jdk-11'
}else{
$env:JAVA_HOME = 'C:\Program Files\Java\jdk1.8.0_151'
}
$env:Path = $env:JAVA_HOME+'\bin;'+$env:Path
java -version
Save this script file as SJV.ps1 and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".
Now open new powershell window and just type SJV 11 it will switch to Java 11.
Type SJV 8 OR SJV it will switch to Java 8.
I hope this help someone who want to change it frequently.
Open Environment Variables editor (File Explorer > right click on
This PC > Properties > Advanced system settings > Environment
Variables...)
Find Path variable in System variables list >
press Edit > put %JAVA_HOME%bin; at first position. This is required
because Java installer adds C:\Program Files (x86)\Common
Files\Oracle\Java\javapath to the PATH which references to the latest Java version installed.
Now you can switch between Java version using setx command (should be run under administrative permissions):
setx /m JAVA_HOME "c:\Program Files\Java\jdk-10.0.1\
(note: there is no double quote at the end of the line and should not be or you'll get c:\Program Files\Java\jdk-10.0.1\" in your JAVA_HOME variable and it breaks your PATH variable)
Solution with system variables (and administrative permissions) is more robust because it puts desired path to Java at the start of the resulting PATH variable.
If your path have less than 1024 characters can execute (Run as Administrator) this script:
#echo off
set "JAVA5_FOLDER=C:\Java\jdk1.5.0_22"
set "JAVA6_FOLDER=C:\Java\jdk1.6.0_45"
set "JAVA7_FOLDER=C:\Java\jdk1.7.0_80"
set "JAVA8_FOLDER=C:\Java\jdk1.8.0_121"
set "JAVA9_FOLDER=C:\Java\jdk-10.0.1"
set "CLEAR_FOLDER=C:\xxxxxx"
(echo "%PATH%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%
echo path length = %STRLENGTH%
if %STRLENGTH% GTR 1024 goto byebye
echo Old Path: %PATH%
echo ===================
echo Choose new Java Version:
echo [5] JDK5
echo [6] JDK6
echo [7] JDK7
echo [8] JDK8
echo [9] JDK10
echo [x] Exit
:choice
SET /P C=[5,6,7,8,9,x]?
for %%? in (5) do if /I "%C%"=="%%?" goto JDK_L5
for %%? in (6) do if /I "%C%"=="%%?" goto JDK_L6
for %%? in (7) do if /I "%C%"=="%%?" goto JDK_L7
for %%? in (8) do if /I "%C%"=="%%?" goto JDK_L8
for %%? in (9) do if /I "%C%"=="%%?" goto JDK_L9
for %%? in (x) do if /I "%C%"=="%%?" goto byebye
goto choice
#echo on
:JDK_L5
set "NEW_PATH=%JAVA5_FOLDER%"
goto setPath
:JDK_L6
#echo off
set "NEW_PATH=%JAVA6_FOLDER%"
goto setPath
:JDK_L7
#echo off
set "NEW_PATH=%JAVA7_FOLDER%"
goto setPath
:JDK_L8
#echo off
set "NEW_PATH=%JAVA8_FOLDER%"
goto setPath
:JDK_L9
#echo off
set NEW_PATH = %JAVA9_FOLDER%
:setPath
Call Set "PATH=%%PATH:%JAVA5_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA6_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA7_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA8_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA9_FOLDER%=%CLEAR_FOLDER%%%"
rem echo Interim Path: %PATH%
Call Set "PATH=%%PATH:%CLEAR_FOLDER%=%NEW_PATH%%%"
setx PATH "%PATH%" /M
call set "JAVA_HOME=%NEW_PATH%"
setx JAVA_HOME %JAVA_HOME%
echo New Path: %PATH%
:byebye
echo
java -version
pause
If more than 1024, try to remove some unnecessary paths, or can modify this scripts with some inputs from https://superuser.com/questions/387619/overcoming-the-1024-character-limit-with-setx
Run this BAT file to conveniently change the java version.
Pros:
It does NOT modify the PATH system environment variable.
The only thing that has to be maintained is the relational array (can be conveniently constructed as a sparse array) that holds the version number and the path at the beginning of the script.
Precondition:
The following entry %JAVA_HOME%\bin has to be appended to the PATH environment variable.
#echo off
#cls
#title Switch Java Version
setlocal EnableExtensions DisableDelayedExpansion
:: This bat file Switches the Java Version using the JAVA_HOME variable.
:: This script does NOT modify the PATH system environment variable.
:: Precondition: The following entry "%JAVA_HOME%\bin" has to be appended to the PATH environment variable.
:: Script Name: SwitchJavaVersion | Version 1 | 2021/11/04
rem Add items to vector as follows:
rem AvailableVersions["Java Major Version Number"]="Java Absolute Path"
set AvailableVersions[8]="D:\Program Files\Java\jdk8u252-b09"
set AvailableVersions[17]="D:\Program Files\Java\jdk-17.0.1"
call :PrintJavaVersion
call :PrintAvailableVersions
call :GetJavaVersion
call :SetJavaVersion
call :ResetLocalPath
if %errorlevel% neq 0 exit /b %errorlevel%
call :PrintJavaVersion
pause
endlocal
exit /b
rem Print available versions.
:PrintAvailableVersions
echo Available Java Versions:
for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do echo ^> %%I
exit /b
rem Get version from user input or command-line arguments.
:GetJavaVersion
set "JavaVersion="
if "%~1"=="" (
set /p JavaVersion="Type the major java version number you want to switch to: "
) else (
set /a JavaVersion="%~1"
)
exit /b
rem Update JAVA_HOME user variable with hardcoded paths.
:SetJavaVersion
set JavaPath=
for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do (
if "%%I" == "%JavaVersion%" (
setlocal EnableDelayedExpansion
set JavaPath=!AvailableVersions[%%I]!
setlocal EnableExtensions DisableDelayedExpansion
)
)
if not defined JavaPath (
echo "Specified version NOT found: Default settings applied."
for /f "tokens=2 delims==" %%I in ('set AvailableVersions[') do (
set JavaPath=%%I
goto exitForJavaPath
)
)
:exitForJavaPath
rem remove quotes from path
set JavaPath=%JavaPath:"=%
set "JAVA_HOME=%JavaPath%"
setx JAVA_HOME "%JAVA_HOME%"
rem setlocal statement was run 2 times previously inside the for loop; therefore, the endlocal statement must be executed 2 times to close those nested local scopes.
rem below endlocal statement will close local scope set by previous "setlocal EnableExtensions DisableDelayedExpansion" statement
endlocal & set "JavaPath=%JavaPath%"
rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
set "JAVA_HOME=%JavaPath%"
rem below endlocal statement will close local scope set by previous "setlocal EnableDelayedExpansion" statement
endlocal & set "JavaPath=%JavaPath%"
rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
set "JAVA_HOME=%JavaPath%"
exit /b
rem Get User and System Path variable's definition from Registry,
rem evaluate the definitions with the new values and reset
rem the local path variable so newly set java version
rem is properly displayed.
:ResetLocalPath
set "PathValue="
for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "PathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "PathValue=%%~K"
if not defined PathValue goto pathError
set "UserPathValue="
for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "UserPathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "UserPathValue=%%~K"
if not defined UserPathValue goto pathError
call set "Path=%PathValue%;%UserPathValue%"
echo Path variable reset:
echo PATH=%Path%
echo.
exit /b
rem Display the Java version.
:PrintJavaVersion
echo Current Java Version:
java -version
echo.
exit /b
rem Error handling subroutine.
:pathError
echo.
echo Error while refreshing the PATH variable:
echo PathValue=%PathValue%
echo UserPathValue=%UserPathValue%
pause
exit /b 2
endlocal
exit
Load below mentioned PowerShell script at the start of the PowerShell. or generate the file using New-Item $profile -Type File -Force
this will create a file here C:\Users\{user_name}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile
Now copy-paste the content given below in this file to be loaded each time the PowerShell is started
Set all the java versions you need as separate variables.
Java_8_home-> Points to Java 8 Location in local
Java_11_home -> Points to Java 11 Location in local
Java_17_home -> Points to Java 17 Location in local
Java_Home-> This points to the java version you want to use
Run in power shell to update the version to 8 update_java_version 8 $True
To update execution policy to allow script to be loaded at start of the PowerShell use below command
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force
`
function update_java_version($version, [bool] $everywhere)
{
switch ($version)
{
8 {
$java_value = (Get-Item Env:Java_8_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
11 {
$java_value = (Get-Item Env:Java_11_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
17 {
$java_value = (Get-Item Env:Java_17_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
default {
throw "No matching java version found for `$version`: $version"
}
}
if ($everywhere)
{
[System.Environment]::SetEnvironmentVariable("Java_Home", $java_value, "User")
}
}
function refresh-path
{
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
";" +
[System.Environment]::GetEnvironmentVariable("Path", "User")
}
Adding to the answer provided here (https://stackoverflow.com/a/64459399/894565).
I manually created environment variables via UI for Java11, Java17 and Java8. To change across Java version:
From powershell (PJV.ps1):
if($args[0] -eq "11") {
$Env:JAVA_HOME="$ENV:JAVA11"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "17") {
$Env:JAVA_HOME="$ENV:JAVA17"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "8") {
$Env:JAVA_HOME="$ENV:JAVA8"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
}
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
From command line (JV.bat):
#echo off
if "%~1" == "11" (
set "JAVA_HOME=%JAVA11%"
setx JAVA_HOME "%JAVA11%"
) else if "%~1" == "17" (
set "JAVA_HOME=%JAVA17%"
setx JAVA_HOME "%JAVA17%"
) else (
set "JAVA_HOME=%JAVA8%"
setx JAVA_HOME "%JAVA8%"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
Finally both these files are in the same folder. And this folder path has been added to my system PATH

Categories