- Notifications
You must be signed in to change notification settings - Fork0
Maven package Tomcat redeploy Chrome reload Life easier
License
Al-rimi/tom-ps1
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This PowerShell script automates the process of building, deploying, and managing JSP web applications on Apache Tomcat, opening the browser, and reloading the page with no user interaction.
This video demonstrates thedev
deployment mode, which directly deploys files from the development folder. This method is significantly faster as it skips the Maven build process.
This video demonstrates themvn
deployment mode, which builds the project using Maven and deploys the generated WAR file. This method is slower due to the Maven build process.
Automatically builds projects using Maven
This feature ensures that the project is built using Maven, compiling the source code and generating a deployable WAR file.
$process=Start-Process-FilePath"mvn"-ArgumentList"clean package"-PassThru-Wait-NoNewWindowif ($process.ExitCode-ne0) {Write-Host"[ERROR] Maven build failed. Exiting."-ForegroundColor Red|Out-Nullexit1}
Explanation: The script starts the Maven process usingmvn clean package
. If the Maven build fails (i.e., the exit code is non-zero), an error message is displayed, and the script terminates.
Deploys WAR files to the Tomcat `webapps` directory
Once the Maven build completes successfully, the generated WAR file is deployed to the Tomcatwebapps
directory.
$WAR_FILE=Get-ChildItem-Path"$PROJECT_DIR\target"-Filter"*.war"|Select-Object-First1-ExpandProperty FullName$APP_NAME= [System.IO.Path]::GetFileNameWithoutExtension($WAR_FILE)if (-not$WAR_FILE) {Write-Host"[ERROR] No WAR file found. Closing Tomcat..."-ForegroundColor Redexit1}Copy-Item-Path$WAR_FILE-Destination"$TOMCAT_HOME\webapps\"INFO"New WAR file deployed"
Explanation: The script searches for the WAR file in the project's target directory and deploys it to the Tomcatwebapps
directory. If no WAR file is found, it terminates with an error message.
Supports two deployment modes: `dev` and `mvn`
The script now supports two deployment modes:
dev
: Directly deploys files from the development folder.mvn
: Builds the project using Maven and deploys the generated WAR file.
functiondeploy {param ( [ValidateSet("dev","mvn")] [string]$Type ) cleanOldDeploymentsif ($Type-eq"dev") {# Deploy from development folder }elseif ($Type-eq"mvn") {# Build and deploy using Maven }}
Explanation: Thedeploy
function now accepts aType
parameter to specify the deployment mode. This allows for more flexibility in how the application is deployed.
Starts or stops Tomcat based on its running status
The script includes functionality to start or stop Tomcat depending on the given action (start
orstop
).
functiontomcat {param ( [ValidateSet("start","stop","reload")] [string]$Action )$javaExecutable="$env:JAVA_HOME\bin\java.exe"Start-Process-FilePath$javaExecutable`-ArgumentList"-cp",$classpath,$catalinaOpts,$mainClass,$Action`-NoNewWindow`-RedirectStandardOutput$logOut`-RedirectStandardError$logErr`-Wait}
Explanation: Thetomcat
function takes an action parameter (start
,stop
, orreload
) and starts, stops, or reloads the Tomcat server accordingly by executing the Java process with the appropriate arguments.
Reloads the application if Tomcat is already running
If Tomcat is already running, the script will reload the application rather than restarting the server.
if ($tomcatRunning) {try {$creds=New-Object System.Management.Automation.PSCredential("admin", (ConvertTo-SecureString"admin"-AsPlainText-Force))Invoke-WebRequest-Uri"http://localhost:8080/manager/text/reload?path=/$APP_NAME"-Method Get-Credential$creds|Out-Null INFO"Tomcat reloaded" }catch {Write-Host"[ERROR] Failed to reload Tomcat. Check your credentials and Tomcat manager settings."-ForegroundColor Redexit1 }}else { Tomcat-Action start}
Explanation: If Tomcat is running, the script uses the Tomcat manager's API to reload the application without restarting the server. If Tomcat is not running, it starts the server first.Note: The script will crash if the following line is not added toapache-tomcat\conf\tomcat-users.xml
:
<userusername="admin"password="admin"roles="manager-gui,manager-script"/>
This line grants the necessary permissions to the Tomcat manager for reloading the application.
In newer versions of PowerShell, you might need to include the-AllowUnencryptedAuthentication
flag when running the script to enable basic authentication for the Tomcat manager API. The rest of the command should remain unchanged.
Example:
Invoke-WebRequest-Uri"http://localhost:8080/manager/text/reload?path=/$APP_NAME"-Method Get-Credential$creds-AllowUnencryptedAuthentication
Without this flag, you might encounter errors related to unencrypted communication during authentication.
Opens or refreshes the application in Google Chrome
The script ensures the application is opened or refreshed in Google Chrome after deployment.
$chromeProcesses=Get-Process-Name"chrome"-ErrorAction SilentlyContinueif ($chromeProcesses) {$chromeOpened=$falseforeach ($processin$chromeProcesses) {$chromeTitle=$process.MainWindowTitleif ($chromeTitle-like"*$APP_NAME*") {$chromeOpened=$true [System.Windows.Forms.SendKeys]::SendWait("^{F5}")# Ctrl+F5 for hard refresh INFO"Google Chrome reloaded"break } }if (-not$chromeOpened) { INFO"Opening Google Chrome"Start-Process"chrome""http://localhost:8080/$APP_NAME" }}else { INFO"Opening Google Chrome"Start-Process"chrome""http://localhost:8080/$APP_NAME"}
Explanation: The script checks if Google Chrome is already open and refreshes the tab with the deployed application. If Chrome is not open, it launches a new instance with the application URL.
Action | Description | Subactions (if applicable) |
---|---|---|
start | Starts the Tomcat server | None |
stop | Stops the Tomcat server | None |
deploy | Deploys the application to Tomcat | dev : Deploy from development foldermvn : Build and deploy using Maven |
clean | Cleans previous deployments | None |
help | Displays help message | None |
Before using this script, ensure the following requirements are met:
- Java Development Kit (JDK): Installed and
JAVA_HOME
environment variable is correctly set. - Apache Tomcat: Installed and
CATALINA_HOME
environment variable is correctly set. - Maven: Installed and added to the system's
PATH
. - Google Chrome: Installed for automatic browser interaction.
This script assumes that the working directory contains thepom.xml
file (for Maven builds) or a valid project structure (fordev
deployment). If these are missing, the script will not run.
This script is designed to beextendable. You can add new functionality such as pre-deployment checks, custom notifications, or integrate with other tools.
- Custom Deployment Notifications: You can modify the script to send email or Slack notifications after deployment.
- Custom Build Scripts: Add new Maven goals or other build scripts as part of the
mvn clean package
command.
For Visual Studio Code users, the script can be configured to run automatically on file save using theRun on Save extension.
- Install the extension from this repository:vscode-run-on-save.
- Add the following configuration to your VS Code settings:
"runOnSave.shell":"PowerShell","runOnSave.commands": [ {"match":".jsp","command":"tom deploy dev", }],"runOnSave.defaultRunIn":"terminal"
- IfJAVA_HOME orCATALINA_HOME is not set correctly, the script will terminate with an appropriate error message.
- Maven build failures will stop further deployment.
- Missing WAR files or invalid project structures will prompt Tomcat shutdown before exit.
This script is licensed under the MITLicense.
About
Maven package Tomcat redeploy Chrome reload Life easier