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