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