Repository: zengkid/SmartTomcat Branch: master Commit: bcab0d92fcc5 Files: 32 Total size: 117.7 KB Directory structure: gitextract_inej82c3/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows/ │ ├── build.yml │ ├── publish.yml │ └── tagbuild.yml ├── .gitignore ├── .space.kts ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle.kts ├── config-example.txt ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src/ └── main/ ├── java/ │ └── com/ │ └── poratu/ │ └── idea/ │ └── plugins/ │ └── tomcat/ │ ├── conf/ │ │ ├── ServerConsoleView.java │ │ ├── TomcatCommandLineState.java │ │ ├── TomcatLogFile.java │ │ ├── TomcatRunConfiguration.java │ │ ├── TomcatRunConfigurationType.java │ │ ├── TomcatRunnerSettingsEditor.java │ │ └── TomcatRunnerSettingsForm.java │ ├── runner/ │ │ ├── TomcatDebugger.java │ │ ├── TomcatRunConfigurationProducer.java │ │ └── TomcatRunner.java │ ├── setting/ │ │ ├── TomcatInfo.java │ │ ├── TomcatInfoComponent.java │ │ ├── TomcatInfoConfigurable.java │ │ ├── TomcatServerManagerState.java │ │ └── TomcatServersConfigurable.java │ └── utils/ │ └── PluginUtils.java └── resources/ └── META-INF/ └── plugin.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: yuezk --- **Describe the bug** A clear and concise description of what the bug is. **Screenshots** If applicable, add screenshots to help explain your problem. **Intellij & SmartTomcat Version (Help -> About copy & paste below)** ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/workflows/build.yml ================================================ name: build on: push: branches: - master pull_request: branches: - master workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '25' - name: Build with Gradle run: | java -version ./gradlew build ================================================ FILE: .github/workflows/publish.yml ================================================ name: publish on: [workflow_dispatch] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK uses: actions/setup-java@v3 with: distribution: 'temurin' java-version: 25 - name: publish plugin env: intellijPublishToken: ${{ secrets.PUBLISH_TOKEN }} run: | ./gradlew publishPlugin ================================================ FILE: .github/workflows/tagbuild.yml ================================================ name: tagbuild on: push: tags: - 'release*' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK uses: actions/setup-java@v3 with: distribution: 'temurin' java-version: 25 - name: Check plugin version matches release tag run: | # Read the version from the Gradle properties version=$(./gradlew -q --no-daemon properties -Pversion | grep version: | awk '{print $2}') # Check that the version matches the tag if [[ "$version" != "${GITHUB_REF#refs/tags/release}" ]]; then echo "Version $version does not match tag ${GITHUB_REF#refs/tags/}" exit 1 fi - name: Generate release notes run: | ./gradlew -q getChangelog --no-header --project-version="${GITHUB_REF#refs/tags/release}" > release-notes.txt - name: Build with Gradle run: | ./gradlew verifyPlugin - name: Upload to releasex uses: softprops/action-gh-release@v1 if: startsWith(github.ref, 'refs/tags/') with: body_path: release-notes.txt files: build/libs/SmartTomcat-*.jar env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .gitignore ================================================ *.class # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* .idea *.iml .gradle out gen build target gradle bin gradle.properties release-notes.txt .intellijPlatform ================================================ FILE: .space.kts ================================================ /** * JetBrains Space Automation * This Kotlin-script file lets you automate build activities * For more info, see https://www.jetbrains.com/help/space/automation.html */ job("Build and run tests") { gradlew("openjdk:11", "assemble") } ================================================ FILE: CHANGELOG.md ================================================ # SmartTomcat Changelog ## [4.8.0] ### Changed - Requires 2024.2+ - Requires Java 17+ ## [4.7.5] ### Fixed - Do not copy Tomcat configs file when /.smarttomcat//conf folder is empty (#141) - Enhance the XPath selector for port (#128) ## [4.7.4] ### Fixed - write change log in plugin.xml ## [4.7.3] - be able to update the server.xml under the /.smarttomcat//conf. ## [4.7.2] - Add option to disable run configuration from context. ## [4.7.1] - Improve the release CI job. - Fix an NPE ## [4.7.0] - Support config the catalina base directory, thanks to @meier123456 ## [4.6.1] - Stop the debug process gracefully, fix #75. ## [4.6.0] - Support configuring the SSL port, thanks to @leopoldhub. ## [4.5.0] - Support reading classpath from the specific module as the classpath for Tomcat runtime. ## [4.4.1] ### Added - Added support for passing extra classpath the JVM. ## [4.4.0] ### Added - Added support for passing extra classpath the JVM. ## [4.3.8] ### Added - Added support for `allowLinking` and `cacheMaxSize` configurations, fix #99 ### Changed - Fixed a bug where SmartTomcat run configuration overrides the Application configuration, fix #100 ## [4.3.7] ### Changed - Fix context paths like /foo/bar may not working on Windows, fix #95 ## [4.3.6] ### Changed - Allow `Context Path` to be empty - Support `Context Path` like `/foo/bar` - Fix #92 ## [4.3.5] ### Changed - Remove Context elements inside the `server.xml`, fix #91 - Remove `reloadable` from the generated context xml file - Pretty print the generated context xml file - Improve the Tomcat configuration producer ## [4.3.4] ### Changed - Improve the Tomcat runner settings editor - Reuse the `` element in the context.xml file, fixes #83 ## [4.3.3] ### Changed - Improve Tomcat server management - Remove unnecessary `path` in Tomcat context file - Handle exceptions in older IDE versions ## [4.3.2] ### Changed - Fix the bug where the `temp` folder is not created ## [4.3.1] ### Added - Support Tomcat 6 and 7 ### Changed - Use separate context file to deploy webapps (#89) - Fixed IDEA warning during startup - Fixed the wrong `catalina.home` value ## [4.3.0] ### Added - Added support for redirecting the Tomcat logs to console. - Added support for exiting the Tomcat process gracefully when stopping ### Changed - Fixed the incorrect path of the Tomcat logs - Improved the TomcatRunner ## [4.2.0] ### Changed - IDEA - upgrade intellij platformVersion to latestVersion `2202.2+` - Dependencies - upgrade `org.jetbrains.intellij` to `1.6.0` ## [4.1.0] ### Changed - fixed defects - Dependencies - upgrade `org.jetbrains.intellij` to `1.5.2` ## [4.0.0] ### Added - changelog.md - add Dependencies plugin: `org.jetbrains.changelog 1.3.1` ### Changed - IDEA - upgrade intellij platformVersion to `2021.1` - Dependencies - upgrade `org.jetbrains.intellij` to `1.3.0` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # SmartTomcat The Tomcat plugin for Intellij IDEA The SmartTomcat will auto load the Webapp classes and libs from project and module, You needn't copy the classes and libs to the WEB-INF/classes and WEB-INF/lib. The Smart Tomcat plugin will auto config the classpath for tomcat server. The Smart Tomcat support Tomcat 6+ [![build](https://github.com/zengkid/SmartTomcat/actions/workflows/build.yml/badge.svg)](https://github.com/zengkid/SmartTomcat/actions/workflows/build.yml) ### User Guide * Tomcat Server Setting Navigate File -> Setting or Ctrl + Alt + S Open System Settings. In the Setting UI, go to Tomcat Server, and then add your tomcat servers, e.g. tomcat6, tomcat8, tomcat9 ![Smart Tomcat Setting1](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting1.png "Smart Tomcat") ![Smart Tomcat Setting2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting2.png "Smart Tomcat") ![Smart Tomcat Setting2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting3.png "Smart Tomcat") * Run/Debug setup Navigat Run -> Edit Configrations to Open Run/Debug Configrations. In the Run/Debug Configrations, add new configration, choose Smart Tomcat, for detail config as below ![Smart Tomcat run1](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run1.png "Smart Tomcat") ![Smart Tomcat run2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run2.png "Smart Tomcat") ![Smart Tomcat run3](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run3.png "Smart Tomcat") * Run/Debug config detail * Tomcat Server choose the tomcat server. * Deployment Directory the directory must be in project or module webapp. maven or gradle project, the default folder is /src/main/webapp **DON'T add output webapp to deployment directory.** * Custom Context opional, if webapp/META-INF/context.xml, if will auto add it. sample context.xml: ```xml ``` In Java Servlet, we can call it as below ```java Context ctx = new InitialContext(); ctx = (Context) ctx.lookup("java:comp/env"); String value1 = (String) ctx.lookup("varName1"); String value2 = (String) ctx.lookup("varName2"); DataSource datasource = (DataSource) ctx.lookup("jdbc/ds"); ``` * Context Path default value is '/' * Server Port default value is 8080 * ~~AJP Port~~ ~~default value is 8009~~ * Admin Port default value is 8005 * VM Options extract tomcat VM options e.g. -Duser.language=en * Env Options extract tomcat env parmaters e.g. param1=value1 ================================================ FILE: build.gradle.kts ================================================ import org.jetbrains.changelog.Changelog import org.jetbrains.changelog.markdownToHTML import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType //import org.jetbrains.intellij.platform.gradle.models.ProductRelease fun prop(key: String) = providers.gradleProperty(key).get() plugins { id("java") alias(libs.plugins.intelliJPlatform) // IntelliJ Platform Gradle Plugin alias(libs.plugins.changelog) // Gradle Changelog Plugin } group = prop("pluginGroup") version = prop("pluginVersion") // Configure project's dependencies repositories { mavenCentral() intellijPlatform { defaultRepositories() } } dependencies { intellijPlatform { intellijIdea(prop("platformVersion")) bundledPlugin("com.intellij.java") } } // Configure Gradle IntelliJ Plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin intellijPlatform { pluginConfiguration { name = prop("pluginName") version = prop("pluginVersion") ideaVersion { sinceBuild = prop("pluginSinceBuild") } description = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { val start = "" val end = "" with(it.lines()) { if (!containsAll(listOf(start, end))) { throw GradleException("Plugin description section not found in README.md:\n$start ... $end") } subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } } } pluginVerification { ides { create(IntelliJPlatformType.IntellijIdea, prop("platformVersion")) // recommended() // select { // types = listOf(IntelliJPlatformType.IntellijIdea) // channels = listOf(ProductRelease.Channel.RELEASE) // sinceBuild = prop("pluginSinceBuild") // } } } } changelog { version = prop("pluginVersion") itemPrefix = "-" keepUnreleasedSection = true unreleasedTerm = "[Unreleased]" groups = listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security") combinePreReleases = true } java { toolchain { languageVersion.set(JavaLanguageVersion.of(prop("jdkVersion"))) } } tasks { wrapper { gradleVersion = prop("gradleVersion") } withType { sourceCompatibility = prop("compatibleJdkVersion") targetCompatibility = prop("compatibleJdkVersion") } patchPluginXml { changeNotes = provider { changelog.renderItem( changelog .getLatest() .withHeader(false) .withEmptySections(false), Changelog.OutputType.HTML ) } } publishPlugin { dependsOn(patchChangelog) token.set(System.getenv("intellijPublishToken")) } } ================================================ FILE: config-example.txt ================================================ Config Example Deployment Directory: project_name/web-module/src/main/webapp Modules Root: project_name/web-module Context Path: /web-dir Server Port:8080 Ajp port:8009 Tomcat Port:8005 Vm options:-Dspring.profiles.active=dev -Xmx2048m -Xms768m Evn options: ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://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. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle.kts ================================================ rootProject.name = "SmartTomcat" //systemProp.system=systemValue pluginManagement { repositories { mavenCentral() maven("https://oss.sonatype.org/content/repositories/snapshots/") gradlePluginPortal() maven("https://maven.aliyun.com/nexus/content/repositories/gradle-plugin") } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/ServerConsoleView.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Url; import com.intellij.util.Urls; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Author : zengkid * Date : 2017-02-23 * Time : 00:13 */ public class ServerConsoleView extends ConsoleViewImpl { private final TomcatRunConfiguration configuration; private boolean printStarted = false; private final List httpPorts = new ArrayList<>(); private final List httpsPorts = new ArrayList<>(); public ServerConsoleView(TomcatRunConfiguration configuration) { super(configuration.getProject(), true); this.configuration = configuration; } @Override public void print(@NotNull String s, @NotNull ConsoleViewContentType contentType) { super.print(s, contentType); if (printStarted) { return; } // skip the exception log e.g.: // at org.apache.catalina.startup.Catalina.start(Catalina.java:772) boolean isExceptionLog = s.trim().startsWith("at "); if (isExceptionLog) { return; } if (this.parsePorts(s)) { return; } if (s.contains("org.apache.catalina.startup.Catalina start") || s.contains("org.apache.catalina.startup.Catalina.start")) { boolean portNotFound = httpPorts.isEmpty() && httpsPorts.isEmpty(); // Use the configured port if the port is not found in the log if (portNotFound) { this.httpPorts.add(String.valueOf(configuration.getPort())); Integer sslPort = configuration.getSslPort(); if (sslPort != null) { this.httpsPorts.add(String.valueOf(sslPort)); } } List urls = buildServerUrls(); for (Url url : urls) { super.print(url + "\n", contentType); } printStarted = true; } } // Parse the port number from the log // 21-Jun-2023 13:27:15.385 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"] // 21-Jun-2023 13:27:15.385 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-8443"] private boolean parsePorts(String s) { Pattern pattern = Pattern.compile("http-nio-(\\d+)"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String port = matcher.group(1); if (!this.httpPorts.contains(port)) { this.httpPorts.add(port); } return true; } pattern = Pattern.compile("https-jsse-nio-(\\d+)"); matcher = pattern.matcher(s); if (matcher.find()) { String port = matcher.group(1); if (!this.httpsPorts.contains(port)) { this.httpsPorts.add(port); } return true; } return false; } private List buildServerUrls() { List urls = new ArrayList<>(); String path = '/' + StringUtil.trimStart(configuration.getContextPath(), "/"); for (String httpPort : httpPorts) { boolean isDefaultPort = "80".equals(httpPort); String authority = "localhost" + (isDefaultPort ? "" : ":" + httpPort); urls.add(Urls.newHttpUrl(authority, path)); } for (String httpsPort : httpsPorts) { boolean isDefaultPort = "443".equals(httpsPort); String authority = "localhost" + (isDefaultPort ? "" : ":" + httpsPort); urls.add(Urls.newUrl("https", authority, path)); } return urls; } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatCommandLineState.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.JavaCommandLineState; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.process.KillableColoredProcessHandler; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.ui.ConsoleView; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.PathsList; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import java.util.Objects; /** * Author : zengkid * Date : 2017-02-17 * Time : 11:10 AM */ public class TomcatCommandLineState extends JavaCommandLineState { private static final String JDK_JAVA_OPTIONS = "JDK_JAVA_OPTIONS"; private static final String ENV_JDK_JAVA_OPTIONS = "--add-opens=java.base/java.lang=ALL-UNNAMED " + "--add-opens=java.base/java.io=ALL-UNNAMED " + "--add-opens=java.base/java.util=ALL-UNNAMED " + "--add-opens=java.base/java.util.concurrent=ALL-UNNAMED " + "--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED"; private static final String TOMCAT_MAIN_CLASS = "org.apache.catalina.startup.Bootstrap"; private static final String PARAM_CATALINA_HOME = "catalina.home"; private static final String PARAM_CATALINA_BASE = "catalina.base"; private static final String PARAM_CATALINA_TMPDIR = "java.io.tmpdir"; private static final String PARAM_LOGGING_CONFIG = "java.util.logging.config.file"; private static final String PARAM_LOGGING_MANAGER = "java.util.logging.manager"; private static final String PARAM_LOGGING_MANAGER_VALUE = "org.apache.juli.ClassLoaderLogManager"; private TomcatRunConfiguration configuration; protected TomcatCommandLineState(@NotNull ExecutionEnvironment environment) { super(environment); } protected TomcatCommandLineState(ExecutionEnvironment environment, TomcatRunConfiguration configuration) { this(environment); this.configuration = configuration; } @Override protected GeneralCommandLine createCommandLine() throws ExecutionException { GeneralCommandLine commandLine = super.createCommandLine(); // Set JDK_JAVA_OPTIONS String originalJdkJavaOptions = commandLine.getEnvironment().get(JDK_JAVA_OPTIONS); String jdkJavaOptions = originalJdkJavaOptions == null ? ENV_JDK_JAVA_OPTIONS : originalJdkJavaOptions + " " + ENV_JDK_JAVA_OPTIONS; return commandLine.withEnvironment(JDK_JAVA_OPTIONS, jdkJavaOptions); } @Override @NotNull protected OSProcessHandler startProcess() throws ExecutionException { KillableColoredProcessHandler processHandler = new KillableColoredProcessHandler(createCommandLine()); boolean shouldKillSoftly = !DebuggerSettings.getInstance().KILL_PROCESS_IMMEDIATELY; processHandler.setShouldKillProcessSoftly(shouldKillSoftly); ProcessTerminatedListener.attach(processHandler); return processHandler; } @Override protected JavaParameters createJavaParameters() { try { Path catalinaBase = PluginUtils.getCatalinaBase(configuration); Module module = configuration.getModule(); if (catalinaBase == null || module == null) { throw new ExecutionException("The Module Root specified is not a module according to Intellij"); } Path tomcatInstallationPath = Paths.get(configuration.getTomcatInfo().getPath()); Project project = configuration.getProject(); String tomcatVersion = configuration.getTomcatInfo().getVersion(); String vmOptions = configuration.getVmOptions(); String extraClassPath = configuration.getExtraClassPath(); Map envOptions = configuration.getEnvOptions(); //copy to project folder, and then user is able to update server.xml under the project. Path projectConfPath = Paths.get(Objects.requireNonNull(project.getBasePath()), ".smarttomcat", module.getName(), "conf"); if (!projectConfPath.toFile().exists() || PluginUtils.isEmptyFolder(projectConfPath)) { FileUtil.createDirectory(projectConfPath.toFile()); FileUtil.copyDir(tomcatInstallationPath.resolve("conf").toFile(), projectConfPath.toFile()); } // Copy the Tomcat configuration files to the working directory Path confPath = catalinaBase.resolve("conf"); FileUtil.delete(confPath.toFile()); FileUtil.createDirectory(confPath.toFile()); FileUtil.copyDir(projectConfPath.toFile(), confPath.toFile()); // create the temp folder FileUtil.createDirectory(catalinaBase.resolve("temp").toFile()); updateServerConf(confPath, configuration); createContextFile(tomcatVersion, module, confPath); deleteTomcatWorkFiles(catalinaBase); ProjectRootManager manager = ProjectRootManager.getInstance(project); JavaParameters javaParams = new JavaParameters(); javaParams.setDefaultCharset(project); javaParams.setWorkingDirectory(catalinaBase.toFile()); javaParams.setJdk(manager.getProjectSdk()); javaParams.getClassPath().add(tomcatInstallationPath.resolve("bin/bootstrap.jar").toFile()); javaParams.getClassPath().add(tomcatInstallationPath.resolve("bin/tomcat-juli.jar").toFile()); if (StringUtil.isNotEmpty(extraClassPath)) { javaParams.getClassPath().addAll(StringUtil.split(extraClassPath, File.pathSeparator)); } javaParams.setMainClass(TOMCAT_MAIN_CLASS); javaParams.getProgramParametersList().add("start"); javaParams.setPassParentEnvs(configuration.isPassParentEnvs()); if (envOptions != null) { javaParams.setEnv(envOptions); } ParametersList vmParams = javaParams.getVMParametersList(); vmParams.addParametersString(vmOptions); vmParams.addProperty(PARAM_CATALINA_HOME, tomcatInstallationPath.toString()); vmParams.defineProperty(PARAM_CATALINA_BASE, catalinaBase.toString()); vmParams.defineProperty(PARAM_CATALINA_TMPDIR, catalinaBase.resolve("temp").toString()); vmParams.defineProperty(PARAM_LOGGING_CONFIG, confPath.resolve("logging.properties").toString()); vmParams.defineProperty(PARAM_LOGGING_MANAGER, PARAM_LOGGING_MANAGER_VALUE); return javaParams; } catch (Exception e) { throw new RuntimeException(e); } } @Nullable @Override protected ConsoleView createConsole(@NotNull Executor executor) { return new ServerConsoleView(configuration); } private void updateServerConf(Path confPath, TomcatRunConfiguration cfg) throws ParserConfigurationException, XPathExpressionException, TransformerException, IOException, SAXException { Path serverXml = confPath.resolve("server.xml"); Document doc = PluginUtils.createDocumentBuilder().parse(serverXml.toFile()); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression exprConnectorShutdown = xpath.compile("/Server[@shutdown='SHUTDOWN']"); XPathExpression serviceExpression = xpath.compile("/Server/Service[@name='Catalina']"); XPathExpression exprConnector = xpath.compile("/Server/Service[@name='Catalina']/Connector[@protocol and (not(@SSLEnabled) or @SSLEnabled='false')]"); XPathExpression exprSSLConnector = xpath.compile("/Server/Service[@name='Catalina']/Connector[@SSLEnabled='true']"); XPathExpression exprContext = xpath.compile("/Server/Service[@name='Catalina']/Engine[@name='Catalina']/Host/Context"); Element serviceE = (Element) serviceExpression.evaluate(doc, XPathConstants.NODE); Element portShutdown = (Element) exprConnectorShutdown.evaluate(doc, XPathConstants.NODE); Element portE = (Element) exprConnector.evaluate(doc, XPathConstants.NODE); Element sslPortE = (Element) exprSSLConnector.evaluate(doc, XPathConstants.NODE); NodeList nodeList = (NodeList) exprContext.evaluate(doc, XPathConstants.NODESET); if (nodeList != null) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } } if (portShutdown != null) { portShutdown.setAttribute("port", String.valueOf(cfg.getAdminPort())); } if (portE != null) { portE.setAttribute("port", String.valueOf(cfg.getPort())); } Integer sslPort = cfg.getSslPort(); if (sslPortE != null && sslPort != null) { // Update SSL configuration sslPortE.setAttribute("port", sslPort.toString()); if (portE != null) { portE.setAttribute("redirectPort", sslPort.toString()); } } else { // Clean up SSL configuration if (portE != null) { portE.removeAttribute("redirectPort"); } if (serviceE != null && sslPortE != null) { serviceE.removeChild(sslPortE); } } PluginUtils.createTransformer().transform(new DOMSource(doc), new StreamResult(serverXml.toFile())); } private void createContextFile(String tomcatVersion, Module module, Path confPath) throws ParserConfigurationException, IOException, SAXException, TransformerException { String docBase = configuration.getDocBase(); String contextPath = configuration.getContextPath(); String normalizedContextPath = StringUtil.trim(contextPath, ch -> ch != '/'); String contextFileName = StringUtil.defaultIfEmpty(normalizedContextPath, "ROOT").replace('/', '#'); Path contextFilesDir = confPath.resolve("Catalina/localhost"); Path contextFilePath = contextFilesDir.resolve(contextFileName + ".xml"); // Create `conf/Catalina/localhost` folder FileUtil.createDirectory(contextFilesDir.toFile()); DocumentBuilder builder = PluginUtils.createDocumentBuilder(); Document doc = builder.newDocument(); Element contextRoot = createContextElement(doc, builder); contextRoot.setAttribute("docBase", docBase); collectResources(doc, contextRoot, module, tomcatVersion); doc.appendChild(contextRoot); StringWriter writer = new StringWriter(); PluginUtils.createTransformer().transform(new DOMSource(doc), new StreamResult(writer)); FileUtil.writeToFile(contextFilePath.toFile(), writer.toString()); } private Element createContextElement(Document doc, DocumentBuilder builder) throws IOException, SAXException { Path contextFile = findContextFileInApp(); if (contextFile == null) { return doc.createElement("Context"); } Element contextEl = builder.parse(contextFile.toFile()).getDocumentElement(); return (Element) doc.importNode(contextEl, true); } private Path findContextFileInApp() { String docBase = configuration.getDocBase(); if (docBase == null) { return null; } Path metaInf = Paths.get(docBase).resolve("META-INF"); Path contextLocalFile = metaInf.resolve("context_local.xml"); Path contextFile = metaInf.resolve("context.xml"); if (Files.exists(contextLocalFile)) { return contextLocalFile; } else if (Files.exists(contextFile)) { return contextFile; } else { return null; } } private void collectResources(Document doc, Element contextRoot, Module module, String tomcatVersion) { String majorVersionStr = tomcatVersion.split("\\.")[0]; int majorVersion = majorVersionStr.isEmpty() ? 8 : Integer.parseInt(majorVersionStr); PathsList pathsList = OrderEnumerator.orderEntries(module) .withoutSdk().runtimeOnly().productionOnly().getPathsList(); if (pathsList.isEmpty()) { return; } if (majorVersion >= 8) { Element resources = createResourcesElementIfNecessary(doc, contextRoot); pathsList.getVirtualFiles().forEach(file -> { Element res; String tagName; String className; String webAppMount; if (file.isDirectory()) { tagName = "PreResources"; className = "org.apache.catalina.webresources.DirResourceSet"; webAppMount = "/WEB-INF/classes"; } else { tagName = "PostResources"; className = "org.apache.catalina.webresources.FileResourceSet"; webAppMount = "/WEB-INF/lib/" + file.getName(); } res = doc.createElement(tagName); res.setAttribute("base", file.getPath()); res.setAttribute("className", className); res.setAttribute("webAppMount", webAppMount); resources.appendChild(res); }); } else if (majorVersion >= 6) { Element loader = doc.createElement("Loader"); loader.setAttribute("className", "org.apache.catalina.loader.VirtualWebappLoader"); loader.setAttribute("virtualClasspath", StringUtil.join(pathsList.getPathList(), ";")); contextRoot.appendChild(loader); } else { throw new RuntimeException("Unsupported Tomcat version: " + tomcatVersion); } } private Element createResourcesElementIfNecessary(Document doc, Element contextRoot) { Element resources = (Element) contextRoot.getElementsByTagName("Resources").item(0); if (resources == null) { resources = doc.createElement("Resources"); contextRoot.appendChild(resources); } if (Registry.is("smartTomcat.resources.allowLinking")) { resources.setAttribute("allowLinking", "true"); } int cacheMaxSize = Registry.intValue("smartTomcat.resources.cacheMaxSize", 10240); if (cacheMaxSize > 0) { resources.setAttribute("cacheMaxSize", String.valueOf(cacheMaxSize)); } return resources; } private void deleteTomcatWorkFiles(Path tomcatHome) { Path tomcatWorkPath = tomcatHome.resolve("work/Catalina/localhost"); FileUtil.processFilesRecursively(tomcatWorkPath.toFile(), file -> { // Delete the work files except the session persistence files if (file.isFile() && !file.getName().endsWith(".ser")) { FileUtil.delete(file); } return true; }); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatLogFile.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.execution.configurations.LogFileOptions; import com.intellij.execution.configurations.PredefinedLogFile; import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.nio.file.Paths; public class TomcatLogFile { public static final String TOMCAT_LOCALHOST_LOG_ID = "Tomcat Localhost Log"; public static final String TOMCAT_CATALINA_LOG_ID = "Tomcat Catalina Log"; public static final String TOMCAT_ACCESS_LOG_ID = "Tomcat Access Log"; public static final String TOMCAT_MANAGER_LOG_ID = "Tomcat Manager Log"; public static final String TOMCAT_HOST_MANAGER_LOG_ID = "Tomcat Host Manager Log"; private final String id; private final String filename; private boolean enabled; public TomcatLogFile(String id, String filename) { this.id = id; this.filename = filename; } public TomcatLogFile(String id, String filename, boolean enabled) { this(id, filename); this.enabled = enabled; } public String getId() { return id; } public LogFileOptions createLogFileOptions(PredefinedLogFile file, @Nullable Path logsDirPath) { Path logsPath = logsDirPath == null ? Paths.get("logs") : logsDirPath; return new LogFileOptions(file.getId(), logsPath.resolve(filename) + ".*", file.isEnabled()); } public PredefinedLogFile createPredefinedLogFile() { return new PredefinedLogFile(id, enabled); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfiguration.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.configurationStore.XmlSerializer; import com.intellij.diagnostic.logging.LogConfigurationPanel; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.Executor; import com.intellij.execution.JavaRunConfigurationExtensionManager; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.options.SettingsEditorGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.xmlb.XmlSerializerUtil; import com.poratu.idea.plugins.tomcat.setting.TomcatInfo; import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Author : zengkid * Date : 2/16/2017 * Time : 3:14 PM */ public class TomcatRunConfiguration extends LocatableConfigurationBase implements RunProfileWithCompileBeforeLaunchOption { private static final List tomcatLogFiles = Arrays.asList( new TomcatLogFile(TomcatLogFile.TOMCAT_LOCALHOST_LOG_ID, "localhost", true), new TomcatLogFile(TomcatLogFile.TOMCAT_ACCESS_LOG_ID, "localhost_access_log", true), new TomcatLogFile(TomcatLogFile.TOMCAT_CATALINA_LOG_ID, "catalina"), new TomcatLogFile(TomcatLogFile.TOMCAT_MANAGER_LOG_ID, "manager"), new TomcatLogFile(TomcatLogFile.TOMCAT_HOST_MANAGER_LOG_ID, "host-manager") ); private static List createPredefinedLogFiles() { return tomcatLogFiles.stream() .map(TomcatLogFile::createPredefinedLogFile) .collect(Collectors.toList()); } private TomcatRunConfigurationOptions tomcatOptions = new TomcatRunConfigurationOptions(); private RunConfigurationModule configurationModule; protected TomcatRunConfiguration(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) { super(project, factory, name); configurationModule = new RunConfigurationModule(project); TomcatServerManagerState applicationService = TomcatServerManagerState.getInstance(); List tomcatInfos = applicationService.getTomcatInfos(); if (!tomcatInfos.isEmpty()) { tomcatOptions.setTomcatInfo(tomcatInfos.get(0)); } addPredefinedTomcatLogFiles(); } @NotNull @Override public SettingsEditor getConfigurationEditor() { Project project = getProject(); SettingsEditorGroup group = new SettingsEditorGroup<>(); TomcatRunnerSettingsEditor tomcatSetting = new TomcatRunnerSettingsEditor(project); group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), tomcatSetting); group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<>()); JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group); return group; } @Override public void checkConfiguration() throws RuntimeConfigurationException { if (getTomcatInfo() == null) { throw new RuntimeConfigurationError("Tomcat server is not selected"); } if (StringUtil.isEmpty(getDocBase())) { throw new RuntimeConfigurationError("Deployment directory cannot be empty"); } if (StringUtil.isEmpty(getContextPath())) { throw new RuntimeConfigurationError("Context path cannot be empty"); } if (getModule() == null) { throw new RuntimeConfigurationError("Module is not selected"); } if (getPort() == null || getAdminPort() == null) { throw new RuntimeConfigurationError("Port cannot be empty"); } } @Override public void onNewConfigurationCreated() { super.onNewConfigurationCreated(); try { Project project = getProject(); List webRoots = PluginUtils.findWebRoots(project); if (!webRoots.isEmpty()) { VirtualFile webRoot = webRoots.get(0); tomcatOptions.setDocBase(webRoot.getPath()); Module module = PluginUtils.findContainingModule(webRoot.getPath(), project); if (module == null) { module = PluginUtils.guessModule(project); } if (module != null) { tomcatOptions.setContextPath("/" + PluginUtils.extractContextPath(module)); } configurationModule.setModule(module); } } catch (Exception e) { //do nothing. } } @Override public Module @NotNull [] getModules() { ModuleManager moduleManager = ModuleManager.getInstance(getProject()); return moduleManager.getModules(); } @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) { return new TomcatCommandLineState(executionEnvironment, this); } @Override public @Nullable LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile file) { for (TomcatLogFile logFile : tomcatLogFiles) { if (logFile.getId().equals(file.getId())) { return logFile.createLogFileOptions(file, PluginUtils.getTomcatLogsDirPath(this)); } } return super.getOptionsForPredefinedLogFile(file); } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); XmlSerializer.deserializeInto(element, tomcatOptions); configurationModule.readExternal(element); // for backward compatibility if (getAllLogFiles().isEmpty()) { addPredefinedTomcatLogFiles(); } // for backward compatibility if (configurationModule.getModule() == null) { configurationModule.setModule(PluginUtils.findContainingModule(tomcatOptions.getDocBase(), getProject())); } } @Override public void writeExternal(@NotNull Element element) throws WriteExternalException { super.writeExternal(element); XmlSerializer.serializeObjectInto(tomcatOptions, element); if (configurationModule.getModule() != null) { configurationModule.writeExternal(element); } } private void addPredefinedTomcatLogFiles() { createPredefinedLogFiles().forEach(this::addPredefinedLogFile); } @Nullable public Module getModule() { return this.configurationModule.getModule(); } public void setModule(Module module) { this.configurationModule.setModule(module); } public TomcatInfo getTomcatInfo() { return tomcatOptions.getTomcatInfo(); } public void setTomcatInfo(TomcatInfo tomcatInfo) { tomcatOptions.setTomcatInfo(tomcatInfo); } public String getCatalinaBase() { return tomcatOptions.getCatalinaBase(); } public void setCatalinaBase(String catalinaBase) { tomcatOptions.setCatalinaBase(catalinaBase); } public String getDocBase() { return tomcatOptions.getDocBase(); } public void setDocBase(String docBase) { tomcatOptions.setDocBase(docBase); } public String getContextPath() { return tomcatOptions.getContextPath(); } public void setContextPath(String contextPath) { tomcatOptions.setContextPath(contextPath); } public Integer getPort() { return tomcatOptions.getPort(); } public void setPort(Integer port) { tomcatOptions.setPort(port); } public Integer getSslPort() { return tomcatOptions.getSslPort(); } public void setSslPort(Integer sslPort) { tomcatOptions.setSslPort(sslPort); } public Integer getAdminPort() { return tomcatOptions.getAdminPort(); } public void setAdminPort(Integer adminPort) { tomcatOptions.setAdminPort(adminPort); } public String getVmOptions() { return tomcatOptions.getVmOptions(); } public void setVmOptions(String vmOptions) { tomcatOptions.setVmOptions(vmOptions); } public Map getEnvOptions() { return tomcatOptions.getEnvOptions(); } public void setEnvOptions(Map envOptions) { tomcatOptions.setEnvOptions(envOptions); } public Boolean isPassParentEnvs() { return tomcatOptions.isPassParentEnvs(); } public void setPassParentEnvironmentVariables(Boolean passParentEnvs) { tomcatOptions.setPassParentEnvs(passParentEnvs); } public String getExtraClassPath() { return tomcatOptions.getExtraClassPath(); } public void setExtraClassPath(String extraClassPath) { tomcatOptions.setExtraClassPath(extraClassPath); } @Override public RunConfiguration clone() { TomcatRunConfiguration clone = (TomcatRunConfiguration) super.clone(); clone.configurationModule = new RunConfigurationModule(getProject()); clone.configurationModule.setModule(configurationModule.getModule()); clone.tomcatOptions = XmlSerializerUtil.createCopy(tomcatOptions); return clone; } private static class TomcatRunConfigurationOptions implements Serializable { private TomcatInfo tomcatInfo; private String catalinaBase; private String docBase; private String contextPath; private Integer port = 8080; private Integer sslPort; private Integer adminPort = 8005; private String vmOptions; private Map envOptions; private Boolean passParentEnvs = true; private String extraClassPath; public TomcatInfo getTomcatInfo() { return tomcatInfo; } public void setTomcatInfo(TomcatInfo tomcatInfo) { this.tomcatInfo = tomcatInfo; } @Nullable public String getCatalinaBase() { return this.catalinaBase; } public void setCatalinaBase(String catalinaBase) { this.catalinaBase = catalinaBase; } @Nullable public String getDocBase() { return docBase; } public void setDocBase(String docBase) { this.docBase = docBase; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public Integer getSslPort() { return sslPort; } public void setSslPort(Integer sslPort) { this.sslPort = sslPort; } public Integer getAdminPort() { return adminPort; } public void setAdminPort(Integer adminPort) { this.adminPort = adminPort; } public String getVmOptions() { return vmOptions; } public void setVmOptions(String vmOptions) { this.vmOptions = vmOptions; } public Map getEnvOptions() { return envOptions; } public void setEnvOptions(Map envOptions) { this.envOptions = envOptions; } public Boolean isPassParentEnvs() { return passParentEnvs; } public void setPassParentEnvs(Boolean passParentEnvs) { this.passParentEnvs = passParentEnvs; } public String getExtraClassPath() { return extraClassPath; } public void setExtraClassPath(String extraClassPath) { this.extraClassPath = extraClassPath; } } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfigurationType.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.configurations.SimpleConfigurationType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.NotNullLazyValue; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * Author : zengkid * Date : 2/16/2017 * Time : 3:11 PM */ public class TomcatRunConfigurationType extends SimpleConfigurationType { private static final Icon TOMCAT_ICON = IconLoader.getIcon("/icon/tomcat.svg", TomcatRunConfigurationType.class); protected TomcatRunConfigurationType() { super("com.poratu.idea.plugins.tomcat", "Smart Tomcat", "Configuration to run Tomcat server", NotNullLazyValue.createValue(() -> TOMCAT_ICON)); } @Override public @NotNull RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new TomcatRunConfiguration(project, this, ""); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsEditor.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class TomcatRunnerSettingsEditor extends SettingsEditor { private final TomcatRunnerSettingsForm form; public TomcatRunnerSettingsEditor(Project project) { form = new TomcatRunnerSettingsForm(project); } @Override protected void resetEditorFrom(@NotNull TomcatRunConfiguration configuration) { form.resetFrom(configuration); } @Override protected void applyEditorTo(@NotNull TomcatRunConfiguration configuration) throws ConfigurationException { form.applyTo(configuration); } @Override protected @NotNull JComponent createEditor() { return form.getMainPanel(); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsForm.java ================================================ package com.poratu.idea.plugins.tomcat.conf; import com.intellij.application.options.ModulesComboBox; import com.intellij.execution.configuration.EnvironmentVariablesTextFieldWithBrowseButton; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextBrowseFolderListener; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.CollectionComboBoxModel; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.UIBundle; import com.intellij.ui.components.fields.ExtendableTextComponent; import com.intellij.ui.components.fields.ExtendableTextField; import com.intellij.util.Function; import com.intellij.util.ui.FormBuilder; import com.poratu.idea.plugins.tomcat.setting.TomcatInfo; import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.plaf.basic.BasicComboBoxEditor; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class TomcatRunnerSettingsForm implements Disposable { private static final Function> PATH_SEPARATOR_LINE_PARSER = text -> { final List result = new ArrayList<>(); final StringTokenizer tokenizer = new StringTokenizer(text, File.pathSeparator, false); while (tokenizer.hasMoreTokens()) { result.add(tokenizer.nextToken()); } return result; }; private static final Function, String> PATH_SEPARATOR_LINE_JOINER = strings -> StringUtil.join(strings, File.pathSeparator); private final Project project; private JPanel mainPanel; private final JPanel tomcatField = new JPanel(new BorderLayout()); private final TomcatComboBox tomcatComboBox = new TomcatComboBox(); private final TextFieldWithBrowseButton catalinaBaseField = new TextFieldWithBrowseButton(); private final TextFieldWithBrowseButton docBaseField = new TextFieldWithBrowseButton(); private final JPanel modulesComboBoxPanel = new JPanel(new GridBagLayout()); private final ModulesComboBox modulesComboBox = new ModulesComboBox(); private final JTextField contextPathField = new JTextField(); private final JPanel portFieldPanel = new JPanel(new GridBagLayout()); private final JPanel adminPortFieldPanel = new JPanel(new GridBagLayout()); private final JTextField portField = new JTextField(); private final JTextField sslPortField = new JTextField(); private final JTextField adminPort = new JTextField(); private final RawCommandLineEditor vmOptions = new RawCommandLineEditor(); private final EnvironmentVariablesTextFieldWithBrowseButton envOptions = new EnvironmentVariablesTextFieldWithBrowseButton(); private final RawCommandLineEditor extraClassPath = new RawCommandLineEditor(PATH_SEPARATOR_LINE_PARSER, PATH_SEPARATOR_LINE_JOINER); TomcatRunnerSettingsForm(Project project) { this.project = project; createTomcatField(); createClasspathField(); createPortField(); createAdminPortField(); extraClassPath.getEditorField().getEmptyText().setText("Use '" + File.pathSeparator + "' to separate paths"); initCatalinaBaseDirectory(); initDeploymentDirectory(); buildForm(); } private void createTomcatField() { JButton configurationButton = new JButton("Configure..."); configurationButton.addActionListener(e -> PluginUtils.openTomcatConfiguration()); tomcatField.add(tomcatComboBox, BorderLayout.CENTER); tomcatField.add(configurationButton, BorderLayout.EAST); } private void createClasspathField() { GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.weighty = 1; modulesComboBoxPanel.add(modulesComboBox, c); modulesComboBox.setModules(PluginUtils.getModules(project)); } private void createPortField() { JLabel sslPortLabel = new JLabel("SSL port:"); sslPortLabel.setHorizontalAlignment(SwingConstants.CENTER); sslPortLabel.setLabelFor(sslPortField); GridBagConstraints c = new GridBagConstraints(); // default constraints c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.gridx = 0; c.weightx = 1; portFieldPanel.add(portField, c); c.gridx = 1; c.weightx = 0; c.ipadx = 10; portFieldPanel.add(sslPortLabel, c); c.gridx = 2; c.weightx = 1; portFieldPanel.add(sslPortField, c); } private void createAdminPortField() { GridBagConstraints c = new GridBagConstraints(); // default constraints c.fill = GridBagConstraints.HORIZONTAL; c.gridy = 0; c.gridx = 0; c.weightx = 1; adminPortFieldPanel.add(adminPort, c); } private void initCatalinaBaseDirectory() { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() .withTitle("Select Catalina Base") .withDescription("Please select the Catalina Base directory"); // catalinaBaseField.addBrowseFolderListener("Select Catalina Base", "Please select the Catalina Base directory", // project, descriptor); TextBrowseFolderListener listener = new TextBrowseFolderListener(descriptor); catalinaBaseField.addBrowseFolderListener(listener); } private void initDeploymentDirectory() { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() .withTitle("Select Deployment Directory") .withDescription("Please the directory to deploy"); // docBaseField.addBrowseFolderListener("Select Deployment Directory", "Please the directory to deploy", // project, descriptor); docBaseField.addBrowseFolderListener(new TextBrowseFolderListener(descriptor)); docBaseField.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { // Update module selection when docBase is changed @Override protected void textChanged(@NotNull DocumentEvent e) { String docBase = docBaseField.getText(); Module module = PluginUtils.findContainingModule(docBase, project); if (module != null) { modulesComboBox.setSelectedModule(module); } } }); } private void buildForm() { FormBuilder builder = FormBuilder.createFormBuilder() .addLabeledComponent("Tomcat server:", tomcatField) .addLabeledComponent("Catalina base:", catalinaBaseField) .addLabeledComponent("Deployment directory:", docBaseField) .addLabeledComponent("Use classpath of module:", modulesComboBoxPanel) .addLabeledComponent("Context path:", contextPathField) .addLabeledComponent("Server port:", portFieldPanel) .addLabeledComponent("Admin port:", adminPortFieldPanel) .addLabeledComponent("VM options:", vmOptions) .addLabeledComponent("Environment variables:", envOptions) .addLabeledComponent("Extra JVM classpath:", extraClassPath) .addComponentFillVertically(new JPanel(), 0); mainPanel = builder.getPanel(); } public JPanel getMainPanel() { return mainPanel; } public void resetFrom(TomcatRunConfiguration configuration) { tomcatComboBox.setSelectedItem(configuration.getTomcatInfo()); Path catalinaBase = PluginUtils.getCatalinaBase(configuration); if (catalinaBase != null) { catalinaBaseField.setText(catalinaBase.toString()); } else { catalinaBaseField.setText(""); } docBaseField.setText(configuration.getDocBase()); modulesComboBox.setSelectedModule(configuration.getModule()); contextPathField.setText(configuration.getContextPath()); portField.setText(String.valueOf(configuration.getPort())); sslPortField.setText(configuration.getSslPort() != null ? String.valueOf(configuration.getSslPort()) : ""); adminPort.setText(String.valueOf(configuration.getAdminPort())); vmOptions.setText(configuration.getVmOptions()); if (configuration.getEnvOptions() != null) { envOptions.setEnvs(configuration.getEnvOptions()); } envOptions.setPassParentEnvs(configuration.isPassParentEnvs()); extraClassPath.setText(configuration.getExtraClassPath()); } public void applyTo(TomcatRunConfiguration configuration) throws ConfigurationException { try { configuration.setTomcatInfo((TomcatInfo) tomcatComboBox.getSelectedItem()); configuration.setCatalinaBase(catalinaBaseField.getText()); configuration.setDocBase(docBaseField.getText()); configuration.setModule(modulesComboBox.getSelectedModule()); configuration.setContextPath(contextPathField.getText()); configuration.setPort(PluginUtils.parsePort(portField.getText())); configuration.setSslPort(StringUtil.isNotEmpty(sslPortField.getText()) ? PluginUtils.parsePort(sslPortField.getText()) : null); configuration.setAdminPort(PluginUtils.parsePort(adminPort.getText())); configuration.setVmOptions(vmOptions.getText()); configuration.setEnvOptions(envOptions.getEnvs()); configuration.setPassParentEnvironmentVariables(envOptions.isPassParentEnvs()); configuration.setExtraClassPath(extraClassPath.getText()); } catch (Exception e) { throw new ConfigurationException(e.getMessage()); } } @Override public void dispose() { mainPanel = null; } private static class TomcatComboBox extends JComboBox { TomcatComboBox() { super(); List tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos(); ComboBoxModel model = new CollectionComboBoxModel<>(tomcatInfos); setModel(model); initBrowsableEditor(); } private void initBrowsableEditor() { ComboBoxEditor editor = new TomcatComboBoxEditor(this); setEditor(editor); setEditable(true); } } private static class TomcatComboBoxEditor extends BasicComboBoxEditor { private static final TomcatComboBoxTextComponentAccessor TEXT_COMPONENT_ACCESSOR = new TomcatComboBoxTextComponentAccessor(); private final TomcatComboBox comboBox; private boolean fileDialogOpened; public TomcatComboBoxEditor(TomcatComboBox comboBox) { this.comboBox = comboBox; } @Override protected JTextField createEditorComponent() { ExtendableTextField editor = new ExtendableTextField(); editor.addExtension(createBrowseExtension()); editor.setBorder(null); editor.setEditable(false); editor.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && !fileDialogOpened) { if (comboBox.isPopupVisible()) { comboBox.hidePopup(); } else { comboBox.showPopup(); } } } }); return editor; } private ExtendableTextComponent.Extension createBrowseExtension() { String tooltip = UIBundle.message("component.with.browse.button.browse.button.tooltip.text"); Runnable browseRunnable = () -> { fileDialogOpened = true; PluginUtils.chooseTomcat(tomcatInfo -> TEXT_COMPONENT_ACCESSOR.setText(comboBox, tomcatInfo.getPath())); SwingUtilities.invokeLater(() -> fileDialogOpened = false); }; return ExtendableTextComponent.Extension.create(AllIcons.General.OpenDisk, AllIcons.General.OpenDiskHover, tooltip, browseRunnable); } } private static class TomcatComboBoxTextComponentAccessor implements TextComponentAccessor> { @Override public String getText(JComboBox component) { return component.getEditor().getItem().toString(); } @Override public void setText(JComboBox comboBox, @NotNull String text) { TomcatServerManagerState.createTomcatInfo(text).ifPresent(tomcatInfo -> { CollectionComboBoxModel model = (CollectionComboBoxModel) comboBox.getModel(); model.add(tomcatInfo); comboBox.setSelectedItem(tomcatInfo); }); } } //isFileVisible is Non-extendable method usage violation, // use withExtensionFilter instead, but it's not support folder /* private static class IgnoreOutputFileChooserDescriptor extends FileChooserDescriptor { private static final FileChooserDescriptor singleFolderDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); private final Project project; public IgnoreOutputFileChooserDescriptor(Project project) { super(singleFolderDescriptor); this.project = project; } @Override public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots(); for (VirtualFile excludeFile : excludeRoots) { if (excludeFile.equals(file)) { return false; } } } return super.isFileVisible(file, showHiddenFiles); } } */ } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatDebugger.java ================================================ package com.poratu.idea.plugins.tomcat.runner; import com.intellij.debugger.impl.GenericDebuggerRunner; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.executors.DefaultDebugExecutor; import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration; import org.jetbrains.annotations.NotNull; /** * Author : zengkid * Date : 2017-02-17 * Time : 11:00 AM */ public class TomcatDebugger extends GenericDebuggerRunner { private static final String RUNNER_ID = "SmartTomcatDebugger"; @Override @NotNull public String getRunnerId() { return RUNNER_ID; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { return (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) && profile instanceof TomcatRunConfiguration); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunConfigurationProducer.java ================================================ package com.poratu.idea.plugins.tomcat.runner; import com.intellij.execution.Location; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.LazyRunConfigurationProducer; import com.intellij.execution.application.ApplicationConfigurationType; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationTypeUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration; import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfigurationType; import com.poratu.idea.plugins.tomcat.setting.TomcatInfo; import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class TomcatRunConfigurationProducer extends LazyRunConfigurationProducer { @NotNull @Override public ConfigurationFactory getConfigurationFactory() { return ConfigurationTypeUtil.findConfigurationType(TomcatRunConfigurationType.class); } @Override protected boolean setupConfigurationFromContext(@NotNull TomcatRunConfiguration configuration, @NotNull ConfigurationContext context, @NotNull Ref sourceElement) { if (Registry.is("smartTomcat.disableRunConfigurationProducer")) { return false; } Module module = context.getModule(); if (module == null) { return false; } // Skip if it contains a main class, to avoid conflict with the default Application run configuration PsiClass psiClass = ApplicationConfigurationType.getMainClass(context.getPsiLocation()); if (psiClass != null) { return false; } List webRoots = findWebRoots(context.getLocation()); if (webRoots.isEmpty()) { return false; } List tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos(); if (!tomcatInfos.isEmpty()) { configuration.setTomcatInfo(tomcatInfos.get(0)); } String contextPath = PluginUtils.extractContextPath(module); configuration.setName("Tomcat: " + contextPath); configuration.setDocBase(webRoots.get(0).getPath()); configuration.setContextPath("/" + contextPath); return true; } @Override public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) { return false; } @Override public boolean isConfigurationFromContext(@NotNull TomcatRunConfiguration configuration, @NotNull ConfigurationContext context) { if (Registry.is("smartTomcat.disableRunConfigurationProducer")) { return false; } List webRoots = findWebRoots(context.getLocation()); return webRoots.stream().anyMatch(webRoot -> webRoot.getPath().equals(configuration.getDocBase())); } private List findWebRoots(@Nullable Location location) { if (location == null) { return ContainerUtil.emptyList(); } boolean isTestFile = PluginUtils.isUnderTestSources(location); if (isTestFile) { return ContainerUtil.emptyList(); } return PluginUtils.findWebRoots(location.getModule()); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunner.java ================================================ package com.poratu.idea.plugins.tomcat.runner; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.impl.DefaultJavaProgramRunner; import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration; import org.jetbrains.annotations.NotNull; /** * Author : zengkid * Date : 2017-02-17 * Time : 11:01 AM */ public class TomcatRunner extends DefaultJavaProgramRunner { private static final String RUNNER_ID = "SmartTomcatRunner"; @NotNull @Override public String getRunnerId() { return RUNNER_ID; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile runProfile) { return (DefaultRunExecutor.EXECUTOR_ID.equals(executorId)) && runProfile instanceof TomcatRunConfiguration; } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfo.java ================================================ package com.poratu.idea.plugins.tomcat.setting; import java.io.Serializable; import java.util.Objects; /** * Author : zengkid * Date : 2017-03-05 * Time : 16:17 */ public class TomcatInfo implements Serializable { private String name; private String version; private String path; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TomcatInfo that = (TomcatInfo) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(path, that.path); } @Override public int hashCode() { return Objects.hash(name, version, path); } @Override public String toString() { return name; } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoComponent.java ================================================ package com.poratu.idea.plugins.tomcat.setting; import com.intellij.openapi.Disposable; import com.intellij.ui.components.JBLabel; import com.intellij.util.ui.FormBuilder; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import javax.swing.*; public class TomcatInfoComponent implements Disposable { private JPanel mainPanel; public TomcatInfoComponent(TomcatInfo tomcatInfo) { JBLabel versionLabel = new JBLabel(tomcatInfo.getVersion()); JBLabel locationLabel = new JBLabel(tomcatInfo.getPath()); mainPanel = FormBuilder.createFormBuilder() .setVerticalGap(UIUtil.LARGE_VGAP) .addLabeledComponent("Version:", versionLabel) .addLabeledComponent("Location:", locationLabel) .addComponentFillVertically(new JPanel(), 0) .getPanel(); mainPanel.setBorder(JBUI.Borders.empty(0, 10)); } public JComponent getMainPanel() { return mainPanel; } @Override public void dispose() { mainPanel = null; } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoConfigurable.java ================================================ package com.poratu.idea.plugins.tomcat.setting; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.ui.NamedConfigurable; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class TomcatInfoConfigurable extends NamedConfigurable { private final TomcatInfo tomcatInfo; private final TomcatInfoComponent tomcatInfoView; private String displayName; private final TomcatNameValidator nameValidator; public TomcatInfoConfigurable(TomcatInfo tomcatInfo, Runnable treeUpdater, TomcatNameValidator nameValidator) { super(true, treeUpdater); this.tomcatInfo = tomcatInfo; this.tomcatInfoView = new TomcatInfoComponent(tomcatInfo); this.displayName = tomcatInfo.getName(); this.nameValidator = nameValidator; } @Override public void setDisplayName(String name) { this.displayName = name; } @Override public TomcatInfo getEditableObject() { return tomcatInfo; } @Override public String getBannerSlogan() { return null; } @Override public JComponent createOptionsPanel() { return tomcatInfoView.getMainPanel(); } @Override public String getDisplayName() { return displayName; } @Override protected void checkName(@NonNls @NotNull String name) throws ConfigurationException { super.checkName(name); if (name.equals(tomcatInfo.getName())) { return; } nameValidator.validate(name); } @Override public boolean isModified() { return !displayName.equals(tomcatInfo.getName()); } @Override public void apply() { tomcatInfo.setName(displayName); } } @FunctionalInterface interface TomcatNameValidator { void validate(T t) throws ConfigurationException; } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServerManagerState.java ================================================ package com.poratu.idea.plugins.tomcat.setting; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.ui.Messages; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.XCollection; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.function.UnaryOperator; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.zip.ZipEntry; /** * Author : zengkid * Date : 2017-03-05 * Time : 15:20 */ @State(name = "ServerConfiguration", storages = @Storage("smart.tomcat.xml")) public class TomcatServerManagerState implements PersistentStateComponent { @XCollection(elementTypes = TomcatInfo.class) private final List tomcatInfos = new ArrayList<>(); public static TomcatServerManagerState getInstance() { return ApplicationManager.getApplication().getService(TomcatServerManagerState.class); } @NotNull public List getTomcatInfos() { return tomcatInfos; } @Nullable @Override public TomcatServerManagerState getState() { return this; } @Override public void loadState(@NotNull TomcatServerManagerState tomcatSettingsState) { XmlSerializerUtil.copyBean(tomcatSettingsState, this); } public static Optional createTomcatInfo(String tomcatHome) { return createTomcatInfo(tomcatHome, TomcatServerManagerState::generateTomcatName); } public static Optional createTomcatInfo(String tomcatHome, UnaryOperator nameGenerator) { File jarFile = Paths.get(tomcatHome, "lib/catalina.jar").toFile(); if (!jarFile.exists()) { Messages.showErrorDialog("Can not find catalina.jar in " + tomcatHome, "Error"); return Optional.empty(); } final TomcatInfo tomcatInfo = new TomcatInfo(); tomcatInfo.setPath(tomcatHome); try (JarFile jar = new JarFile(jarFile)) { ZipEntry entry = jar.getEntry("org/apache/catalina/util/ServerInfo.properties"); Properties p = new Properties(); try (InputStream is = jar.getInputStream(entry)) { p.load(is); } String serverInfo = p.getProperty("server.info"); String serverNumber = p.getProperty("server.number"); String name = nameGenerator == null ? generateTomcatName(serverInfo) : nameGenerator.apply(serverInfo); tomcatInfo.setName(name); tomcatInfo.setVersion(serverNumber); } catch (IOException e) { Messages.showErrorDialog("Can not read server version in " + tomcatHome, "Error"); return Optional.empty(); } return Optional.of(tomcatInfo); } private static String generateTomcatName(String name) { List existingServers = getInstance().getTomcatInfos(); List existingNames = existingServers.stream() .map(TomcatInfo::getName) .collect(Collectors.toList()); return PluginUtils.generateSequentName(existingNames, name); } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServersConfigurable.java ================================================ package com.poratu.idea.plugins.tomcat.setting; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.ui.CommonActionsPanel; import com.intellij.util.IconUtil; import com.poratu.idea.plugins.tomcat.utils.PluginUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * Author : zengkid * Date : 2017-02-23 * Time : 00:14 */ public class TomcatServersConfigurable extends MasterDetailsComponent { @Override public String getDisplayName() { return "Tomcat Server"; } @Override public String getHelpTopic() { return "Smart Tomcat Help"; } public TomcatServersConfigurable() { initTree(); } @Override protected @Nullable List createActions(boolean fromPopup) { List actions = new ArrayList<>(); actions.add(new AddTomcatAction()); // noinspection MissingRecentApi - the inspection of the next line is incorrect. It is available in 193+, actually actions.add(new MyDeleteAction()); return actions; } @Override public boolean isModified() { boolean modified = super.isModified(); if (modified) { return true; } int size = TomcatServerManagerState.getInstance().getTomcatInfos().size(); return myRoot.getChildCount() != size; } @Override public void reset() { myRoot.removeAllChildren(); TomcatServerManagerState state = TomcatServerManagerState.getInstance(); for (TomcatInfo info : state.getTomcatInfos()) { addNode(info, false); } super.reset(); } @Override public void apply() throws ConfigurationException { super.apply(); List tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos(); tomcatInfos.clear(); for (int i = 0; i < myRoot.getChildCount(); i++) { TomcatInfoConfigurable configurable = (TomcatInfoConfigurable) ((MyNode) myRoot.getChildAt(i)).getConfigurable(); tomcatInfos.add(configurable.getEditableObject()); } } @Override protected boolean wasObjectStored(Object editableObject) { // noinspection SuspiciousMethodCalls return TomcatServerManagerState.getInstance().getTomcatInfos().contains(editableObject); } private void addNode(TomcatInfo tomcatInfo, boolean selectInTree) { TomcatInfoConfigurable configurable = new TomcatInfoConfigurable(tomcatInfo, TREE_UPDATER, this::validateName); MyNode node = new MyNode(configurable); addNode(node, myRoot); if (selectInTree) { selectNodeInTree(node); } } private void validateName(String name) throws ConfigurationException { for (int i = 0; i < myRoot.getChildCount(); i++) { TomcatInfoConfigurable configurable = (TomcatInfoConfigurable) ((MyNode) myRoot.getChildAt(i)).getConfigurable(); if (configurable.getEditableObject().getName().equals(name)) { throw new ConfigurationException("Duplicate name: \"" + name + "\""); } } } private class AddTomcatAction extends DumbAwareAction { public AddTomcatAction() { super("Add", "Add a Tomcat server", IconUtil.getAddIcon()); registerCustomShortcutSet(CommonActionsPanel.getCommonShortcut(CommonActionsPanel.Buttons.ADD), myTree); } @Override public void actionPerformed(@NotNull AnActionEvent e) { PluginUtils.chooseTomcat(this::createUniqueName, tomcatInfo -> addNode(tomcatInfo, true)); } private String createUniqueName(String preferredName) { List existingNames = new ArrayList<>(); for (int i = 0; i < myRoot.getChildCount(); i++) { String displayName = ((MyNode) myRoot.getChildAt(i)).getDisplayName(); existingNames.add(displayName); } return PluginUtils.generateSequentName(existingNames, preferredName); } } } ================================================ FILE: src/main/java/com/poratu/idea/plugins/tomcat/utils/PluginUtils.java ================================================ package com.poratu.idea.plugins.tomcat.utils; import com.intellij.execution.Location; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleFileIndex; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration; import com.poratu.idea.plugins.tomcat.setting.TomcatInfo; import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState; import com.poratu.idea.plugins.tomcat.setting.TomcatServersConfigurable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Author : zengkid * Date : 2017-03-06 * Time : 21:35 */ public final class PluginUtils { private static final int MIN_PORT_VALUE = 0; private static final int MAX_PORT_VALUE = 65535; private PluginUtils() { } /** * Generate a sequent name based on the existing names * * @param existingNames existing names, e.g. ["tomcat 7", "tomcat 8", "tomcat 9"] * @param preferredName preferred name, e.g. "tomcat 8" * @return sequent name, e.g. "tomcat 8 (2)" */ public static String generateSequentName(List existingNames, String preferredName) { int maxSequent = 0; for (String existingName : existingNames) { Pattern pattern = Pattern.compile("^" + StringUtil.escapeToRegexp(preferredName) + "(?:\\s\\((\\d+)\\))?$"); Matcher matcher = pattern.matcher(existingName); if (matcher.matches()) { String seq = matcher.group(1); if (seq == null) { // No sequent implies that the sequent is 1 maxSequent = 1; } else { maxSequent = Math.max(maxSequent, Integer.parseInt(seq)); } } } return maxSequent == 0 ? preferredName : preferredName + " (" + (maxSequent + 1) + ")"; } public static void chooseTomcat(Consumer callback) { chooseTomcat(null, callback); } public static void chooseTomcat(UnaryOperator nameGenerator, Consumer callback) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory .createSingleFolderDescriptor() .withTitle("Select Tomcat Server") .withDescription("Select the directory of the Tomcat Server"); FileChooser.chooseFile(descriptor, null, null, file -> TomcatServerManagerState .createTomcatInfo(file.getPath(), nameGenerator) .ifPresent(callback)); } @Nullable private static Path defaultCatalinaBase(TomcatRunConfiguration configuration) { String userHome = System.getProperty("user.home"); Project project = configuration.getProject(); Module module = configuration.getModule(); if (module == null) { return null; } Path path = Paths.get(userHome, ".SmartTomcat", project.getName(), module.getName()); if (!Files.exists(path)) { try { Files.createDirectories(path); } catch (IOException e) { return null; } } return path; } @Nullable public static Path getCatalinaBase(TomcatRunConfiguration configuration) { if(!StringUtil.isEmptyOrSpaces(configuration.getCatalinaBase())) { /* CATALINA_BASE override from intellij run configuration */ return Paths.get(configuration.getCatalinaBase()); } return defaultCatalinaBase(configuration); } public static Path getTomcatLogsDirPath(TomcatRunConfiguration configuration) { Path catalinaBase = getCatalinaBase(configuration); if (catalinaBase != null) { return catalinaBase.resolve("logs"); } return null; } @SuppressWarnings("HttpUrlsUsage") public static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); } catch (IllegalArgumentException ignored) { // Some Java implementations do not support these features } dbf.setExpandEntityReferences(false); return dbf.newDocumentBuilder(); } @SuppressWarnings("HttpUrlsUsage") public static Transformer createTransformer() throws TransformerConfigurationException { TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = factory.newTransformer(); try { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (IllegalArgumentException ignored) { // ignore } return transformer; } public static void openTomcatConfiguration() { ShowSettingsUtil.getInstance().showSettingsDialog(null, TomcatServersConfigurable.class); } public static int parsePort(String text) throws ConfigurationException { if (StringUtil.isEmpty(text)) { throw new ConfigurationException("Port cannot be empty"); } try { int port = Integer.parseInt(text); if (port < MIN_PORT_VALUE || port > MAX_PORT_VALUE) { throw new ConfigurationException("Port number must be between " + MIN_PORT_VALUE + " and " + MAX_PORT_VALUE); } return port; } catch (NumberFormatException e) { throw new ConfigurationException("Port number must be an integer"); } } public static String extractContextPath(Module module) { String name = module.getName(); String s = StringUtil.trimEnd(name, ".main"); return ArrayUtil.getLastElement(s.split("\\.")); } public static List findWebRoots(Module module) { List webRoots = new ArrayList<>(); if (module == null) { return webRoots; } ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); ModuleFileIndex fileIndex = moduleRootManager.getFileIndex(); VirtualFile[] sourceRoots = moduleRootManager.getSourceRoots(false); List parentRoots = Stream.of(sourceRoots) .map(VirtualFile::getParent) .distinct() .toList(); for (VirtualFile parentRoot : parentRoots) { fileIndex.iterateContentUnderDirectory(parentRoot, file -> { Path path = Paths.get(file.getPath(), "WEB-INF"); if (Files.exists(path)) { webRoots.add(file); } return true; }, file -> { if (file.isDirectory()) { String path = file.getPath(); return webRoots.stream().noneMatch(root -> file.getPath().startsWith(root.getPath())) && !path.contains("node_modules"); } return false; }); } return webRoots; } public static List findWebRoots(Project project) { Module[] modules = ModuleManager.getInstance(project).getModules(); List webRoots = new ArrayList<>(); for (Module module : modules) { webRoots.addAll(findWebRoots(module)); } return webRoots; } public static boolean isUnderTestSources(@Nullable Location location) { if (location == null) { return false; } VirtualFile file = location.getVirtualFile(); if (file == null) { return false; } return ProjectFileIndex.getInstance(location.getProject()).isInTestSourceContent(file); } /** * Get all modules except the module with name ends with ".test" */ public static List getModules(Project project) { Module[] modules = ModuleManager.getInstance(project).getModules(); return Arrays.stream(modules).filter(module -> !module.getName().endsWith(".test")).collect(Collectors.toList()); } /** * Prefer the module with name ends with ".main" and has the least number of dots in the name, * e.g. `webapp.main` will be chosen over `webapp.library.main` * If no module with name ends with ".main", return the first module */ public static @Nullable Module guessModule(Project project) { List modules = getModules(project); Module result = null; int dotCountInModuleName = Integer.MAX_VALUE; for (Module module : modules) { if (module.getName().endsWith(".main")) { int dotCount = StringUtil.countChars(module.getName(), '.'); if (dotCount < dotCountInModuleName) { result = module; dotCountInModuleName = dotCount; } } } if (result != null) { return result; } return modules.stream().findFirst().orElse(null); } /** * Find the module containing the file */ public static @Nullable Module findContainingModule(@Nullable String filePath, @NotNull Project project) { if (StringUtil.isEmpty(filePath)) { return null; } VirtualFile virtualFile = VfsUtil.findFile(Paths.get(filePath), true); if (virtualFile == null) { return null; } return ModuleUtilCore.findModuleForFile(virtualFile, project); } /** * Checks if the given folder is empty. * * @param path the path to the folder * @return {@code true} if the folder exists and is empty, {@code false} otherwise * @throws IOException if an I/O error occurs */ public static boolean isEmptyFolder(Path path) throws IOException { if (Files.isDirectory(path)) { try (Stream entries = Files.list(path)) { return entries.findFirst().isEmpty(); } } return false; } } ================================================ FILE: src/main/resources/META-INF/plugin.xml ================================================ com.poratu.idea.plugins.tomcat Smart Tomcat zengkid com.intellij.modules.java