{"id":25926935,"url":"https://github.com/al-rimi/tom-script","last_synced_at":"2025-03-03T20:04:51.111Z","repository":{"id":280201151,"uuid":"941279299","full_name":"Al-rimi/tom-script","owner":"Al-rimi","description":"Maven package Tomcat redeploy Chrome reload Life easier","archived":false,"fork":false,"pushed_at":"2025-03-02T09:24:07.000Z","size":37,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-02T09:30:49.790Z","etag":null,"topics":["java-server","jsp","maven-tomcat","powershell-script","tomcat-redeploy"],"latest_commit_sha":null,"homepage":"","language":"PowerShell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Al-rimi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-01T22:53:55.000Z","updated_at":"2025-03-02T09:24:10.000Z","dependencies_parsed_at":"2025-03-02T09:30:56.325Z","dependency_job_id":"ed4315bb-f76e-49b1-a9e1-7a573622cbc9","html_url":"https://github.com/Al-rimi/tom-script","commit_stats":null,"previous_names":["al-rimi/tomcat-auto-script","al-rimi/tom-script"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Al-rimi%2Ftom-script","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Al-rimi%2Ftom-script/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Al-rimi%2Ftom-script/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Al-rimi%2Ftom-script/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Al-rimi","download_url":"https://codeload.github.com/Al-rimi/tom-script/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241731746,"owners_count":20010781,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java-server","jsp","maven-tomcat","powershell-script","tomcat-redeploy"],"created_at":"2025-03-03T20:04:50.273Z","updated_at":"2025-03-03T20:04:51.090Z","avatar_url":"https://github.com/Al-rimi.png","language":"PowerShell","readme":"# Tomcat Automation Script\n\nThis 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.\n\n![Video](./tom-video.gif)\n\n## Features\n\n\u003cdetails\u003e\n\u003csummary\u003eAutomatically builds projects using Maven\u003c/summary\u003e\n\nThis feature ensures that the project is built using Maven, compiling the source code and generating a deployable WAR file.\n\n```powershell\n$process = Start-Process -FilePath \"mvn\" -ArgumentList \"clean package\" -PassThru -Wait -NoNewWindow\n\nif ($process.ExitCode -ne 0) {\n    Write-Host \"[ERROR] Maven build failed. Exiting.\" -ForegroundColor Red | Out-Null\n    exit 1\n}\n```\nExplanation: The script starts the Maven process using `mvn clean package`. If the Maven build fails (i.e., the exit code is non-zero), an error message is displayed, and the script terminates.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eDeploys WAR files to the Tomcat `webapps` directory\u003c/summary\u003e\n\nOnce the Maven build completes successfully, the generated WAR file is deployed to the Tomcat `webapps` directory.\n\n```powershell\n$WAR_FILE = Get-ChildItem -Path \"$PROJECT_DIR\\target\" -Filter \"*.war\" | Select-Object -First 1 -ExpandProperty FullName\n$APP_NAME = [System.IO.Path]::GetFileNameWithoutExtension($WAR_FILE)\n\nif (-not $WAR_FILE) {\n    Write-Host \"[ERROR] No WAR file found. Closing Tomcat...\" -ForegroundColor Red\n    exit 1\n}\n\nCopy-Item -Path $WAR_FILE -Destination \"$TOMCAT_HOME\\webapps\\\"\nINFO \"New WAR file deployed\"\n```\n\nExplanation: The script searches for the WAR file in the project's target directory and deploys it to the Tomcat `webapps` directory. If no WAR file is found, it terminates with an error message.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eStarts or stops Tomcat based on its running status\u003c/summary\u003e\n\nThe script includes functionality to start or stop Tomcat depending on the given action (`start` or `stop`).\n\n```powershell\nfunction Tomcat {\n    param (\n        [ValidateSet(\"start\", \"stop\")]\n        [string]$Action\n    )\n    $javaExecutable = \"$env:JAVA_HOME\\bin\\java.exe\"\n\n    Start-Process -FilePath $javaExecutable `\n        -ArgumentList \"-cp\", $classpath, $catalinaOpts, $mainClass, $Action `\n        -NoNewWindow `\n        -RedirectStandardOutput $logOut `\n        -RedirectStandardError $logErr `\n        -Wait\n}\n```\n\nExplanation: The `Tomcat` function takes an action parameter (`start` or `stop`) and starts or stops the Tomcat server accordingly by executing the Java process with the appropriate arguments. If Tomcat is not already running, it can be started; if it is running, it can be stopped.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eReloads the application if Tomcat is already running\u003c/summary\u003e\n\nIf Tomcat is already running, the script will reload the application rather than restarting the server.\n\n```powershell\nif ($tomcatRunning) {\n    try {\n        $creds = New-Object System.Management.Automation.PSCredential(\"admin\", (ConvertTo-SecureString \"admin\" -AsPlainText -Force))\n        Invoke-WebRequest -Uri \"http://localhost:8080/manager/text/reload?path=/$APP_NAME\" -Method Get -Credential $creds | Out-Null\n        INFO \"Tomcat reloaded\"\n    } catch {\n        Write-Host \"[ERROR] Failed to reload Tomcat. Check your credentials and Tomcat manager settings.\" -ForegroundColor Red\n        exit 1\n    }\n} else {\n    Tomcat -Action start\n}\n```\n\nExplanation: 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 to `apache-tomcat\\conf\\tomcat-users.xml`:\n\n```xml\n\u003cuser username=\"admin\" password=\"admin\" roles=\"manager-gui,manager-script\"/\u003e\n```\n\nThis line grants the necessary permissions to the Tomcat manager for reloading the application.\n\n### For Newer PowerShell Versions:\nIn 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.\n\nExample:\n\n```powershell\nInvoke-WebRequest -Uri \"http://localhost:8080/manager/text/reload?path=/$APP_NAME\" -Method Get -Credential $creds -AllowUnencryptedAuthentication\n```\n\nWithout this flag, you might encounter errors related to unencrypted communication during authentication.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eOpens or refreshes the application in Google Chrome\u003c/summary\u003e\n\nThe script ensures the application is opened or refreshed in Google Chrome after deployment.\n\n```powershell\n$chromeProcesses = Get-Process -Name \"chrome\" -ErrorAction SilentlyContinue\n\nif ($chromeProcesses) {\n    $chromeOpened = $false\n    foreach ($process in $chromeProcesses) {\n        $chromeTitle = $process.MainWindowTitle\n        if ($chromeTitle -like \"*$APP_NAME*\") {\n            $chromeOpened = $true\n            [System.Windows.Forms.SendKeys]::SendWait(\"^{F5}\") # Ctrl+F5 for hard refresh\n            INFO \"Google Chrome reloaded\"\n            break\n        }\n    }\n\n    if (-not $chromeOpened) {\n        INFO \"Opening Google Chrome\"\n        Start-Process \"chrome\" \"http://localhost:8080/$APP_NAME\"\n    }\n} else {\n    INFO \"Opening Google Chrome\"\n    Start-Process \"chrome\" \"http://localhost:8080/$APP_NAME\"\n}\n```\n\nExplanation: 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.\n\u003c/details\u003e\n\n## Parameter Actions\n| Action   | Description                          |\n|----------|--------------------------------------|\n| start    | Starts the Tomcat server             |\n| stop     | Stops the Tomcat server              |\n| deploy   | Deploys the WAR file to Tomcat       |\n| clean    | Cleans previous deployments          |\n| auto     | Automates the entire process         |\n| help     | Displays help message                |\n\n## Prerequisites\nBefore using this script, ensure the following requirements are met:\n\n1. **[Java Development Kit (JDK)](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html)**: Installed and `JAVA_HOME` environment variable is correctly set.\n2. **[Apache Tomcat](https://tomcat.apache.org/download-90.cgi)**: Installed and `CATALINA_HOME` environment variable is correctly set.\n3. **[Maven](https://maven.apache.org/download.cgi)**: Installed and added to the system's `PATH`.\n4. **[Google Chrome](https://www.google.com/chrome/)**: Installed for automatic browser interaction.\n\n### This script assumes that the working directory contains the pom.xml file, indicating a valid Maven project. If the pom.xml is missing, the script will not run.\n\n### Extendable Code\nThis script is designed to be **extendable**. You can add new functionality such as pre-deployment checks, custom notifications, or integrate with other tools.\n\n### Add Custom Future Extensions:\n- **Custom Deployment Notifications**: You can modify the script to send email or Slack notifications after deployment.\n- **Custom Build Scripts**: Add new Maven goals or other build scripts as part of the mvn clean package command.\n\n## VS Code Automatic Execution\nFor Visual Studio Code users, the script can be configured to run automatically on file save using the **Run on Save** extension.\n\n1. Install the extension from this repository: [vscode-run-on-save](https://github.com/pucelle/vscode-run-on-save).\n2. Add the following configuration to your VS Code settings:\n\n```json\n\"runOnSave.shell\": \"PowerShell\",\n\"runOnSave.commands\": [\n    {\n        \"match\": \".*$\",\n        \"command\": \"tom\"\n    }\n],\n\"runOnSave.defaultRunIn\": \"terminal\"\n```\n\n## Error Handling\n- If **JAVA_HOME** or **CATALINA_HOME** is not set correctly, the script will terminate with an appropriate error message.\n- Maven build failures will stop further deployment.\n- Missing WAR files will prompt Tomcat shutdown before exit.\n\n## License\nThis script is licensed under the MIT [License](License).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fal-rimi%2Ftom-script","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fal-rimi%2Ftom-script","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fal-rimi%2Ftom-script/lists"}