Full Code of zengkid/SmartTomcat for AI

master bcab0d92fcc5 cached
32 files
117.7 KB
27.0k tokens
197 symbols
1 requests
Download .txt
Repository: zengkid/SmartTomcat
Branch: master
Commit: bcab0d92fcc5
Files: 32
Total size: 117.7 KB

Directory structure:
gitextract_inej82c3/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build.yml
│       ├── publish.yml
│       └── tagbuild.yml
├── .gitignore
├── .space.kts
├── CHANGELOG.md
├── LICENSE
├── README.md
├── build.gradle.kts
├── config-example.txt
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── poratu/
        │           └── idea/
        │               └── plugins/
        │                   └── tomcat/
        │                       ├── conf/
        │                       │   ├── ServerConsoleView.java
        │                       │   ├── TomcatCommandLineState.java
        │                       │   ├── TomcatLogFile.java
        │                       │   ├── TomcatRunConfiguration.java
        │                       │   ├── TomcatRunConfigurationType.java
        │                       │   ├── TomcatRunnerSettingsEditor.java
        │                       │   └── TomcatRunnerSettingsForm.java
        │                       ├── runner/
        │                       │   ├── TomcatDebugger.java
        │                       │   ├── TomcatRunConfigurationProducer.java
        │                       │   └── TomcatRunner.java
        │                       ├── setting/
        │                       │   ├── TomcatInfo.java
        │                       │   ├── TomcatInfoComponent.java
        │                       │   ├── TomcatInfoConfigurable.java
        │                       │   ├── TomcatServerManagerState.java
        │                       │   └── TomcatServersConfigurable.java
        │                       └── utils/
        │                           └── PluginUtils.java
        └── resources/
            └── META-INF/
                └── plugin.xml

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: yuezk

---

**Describe the bug**
A clear and concise description of what the bug is.


**Screenshots**
If applicable, add screenshots to help explain your problem.

**Intellij & SmartTomcat Version (Help -> About copy & paste below)**


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.


================================================
FILE: .github/workflows/build.yml
================================================
name: build

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Set up JDK
        uses: actions/setup-java@v5
        with:
          distribution: 'temurin'
          java-version: '25'

      - name: Build with Gradle
        run: |
          java -version
          ./gradlew build


================================================
FILE: .github/workflows/publish.yml
================================================
name: publish

on: [workflow_dispatch]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Set up JDK
        uses: actions/setup-java@v3
        with:
          distribution: 'temurin'
          java-version: 25

      - name: publish plugin
        env:
          intellijPublishToken: ${{ secrets.PUBLISH_TOKEN }}
        run: | 
         ./gradlew publishPlugin


================================================
FILE: .github/workflows/tagbuild.yml
================================================
name: tagbuild

on:
  push:
    tags:
      - 'release*'

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Set up JDK
        uses: actions/setup-java@v3
        with:
          distribution: 'temurin'
          java-version: 25

      - name: Check plugin version matches release tag
        run: |
          # Read the version from the Gradle properties
          version=$(./gradlew -q --no-daemon properties -Pversion | grep version: | awk '{print $2}')
          # Check that the version matches the tag
          if [[ "$version" != "${GITHUB_REF#refs/tags/release}" ]]; then
              echo "Version $version does not match tag ${GITHUB_REF#refs/tags/}"
              exit 1
          fi

      - name: Generate release notes
        run: |
          ./gradlew -q getChangelog --no-header --project-version="${GITHUB_REF#refs/tags/release}" > release-notes.txt

      - name: Build with Gradle
        run: | 
          ./gradlew verifyPlugin

      - name: Upload to releasex
        uses: softprops/action-gh-release@v1
        if: startsWith(github.ref, 'refs/tags/')
        with:
          body_path: release-notes.txt
          files: build/libs/SmartTomcat-*.jar
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .gitignore
================================================
*.class

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*


.idea
*.iml
.gradle
out
gen
build
target
gradle
bin
gradle.properties
release-notes.txt
.intellijPlatform


================================================
FILE: .space.kts
================================================
/**
* JetBrains Space Automation
* This Kotlin-script file lets you automate build activities
* For more info, see https://www.jetbrains.com/help/space/automation.html
*/

job("Build and run tests") {
   gradlew("openjdk:11", "assemble")
}

================================================
FILE: CHANGELOG.md
================================================
<!-- Keep a Changelog guide -> https://keepachangelog.com -->
# SmartTomcat Changelog

## [4.8.0]

### Changed
- Requires 2024.2+ 
- Requires Java 17+

## [4.7.5]

### Fixed
- Do not copy Tomcat configs file when <project>/.smarttomcat/<module>/conf folder is empty (#141)
- Enhance the XPath selector for port (#128)

## [4.7.4]

### Fixed
- write change log in plugin.xml

## [4.7.3]

- be able to update the server.xml under the <project>/.smarttomcat/<module>/conf.

## [4.7.2]

- Add option to disable run configuration from context.

## [4.7.1]

- Improve the release CI job.
- Fix an NPE

## [4.7.0]

- Support config the catalina base directory, thanks to @meier123456

## [4.6.1]

- Stop the debug process gracefully, fix #75.

## [4.6.0]

- Support configuring the SSL port, thanks to @leopoldhub.

## [4.5.0]

- Support reading classpath from the specific module as the classpath for Tomcat runtime.

## [4.4.1]
### Added

- Added support for passing extra classpath the JVM.

## [4.4.0]
### Added

- Added support for passing extra classpath the JVM.

## [4.3.8]
### Added

- Added support for `allowLinking` and `cacheMaxSize` configurations, fix #99

### Changed

- Fixed a bug where SmartTomcat run configuration overrides the Application configuration, fix #100

## [4.3.7]
### Changed

- Fix context paths like /foo/bar may not working on Windows, fix #95

## [4.3.6]
### Changed

- Allow `Context Path` to be empty
- Support `Context Path` like `/foo/bar`
- Fix #92

## [4.3.5]
### Changed
- Remove Context elements inside the `server.xml`, fix #91
- Remove `reloadable` from the generated context xml file
- Pretty print the generated context xml file
- Improve the Tomcat configuration producer

## [4.3.4]
### Changed
- Improve the Tomcat runner settings editor 
- Reuse the `<Resources>` element in the context.xml file, fixes #83

## [4.3.3]
### Changed
- Improve Tomcat server management
- Remove unnecessary `path` in Tomcat context file
- Handle exceptions in older IDE versions

## [4.3.2]
### Changed
- Fix the bug where the `temp` folder is not created

## [4.3.1]
### Added
- Support Tomcat 6 and 7
### Changed
- Use separate context file to deploy webapps (#89)
- Fixed IDEA warning during startup
- Fixed the wrong `catalina.home` value

## [4.3.0]
### Added
- Added support for redirecting the Tomcat logs to console.
- Added support for exiting the Tomcat process gracefully when stopping
### Changed
- Fixed the incorrect path of the Tomcat logs
- Improved the TomcatRunner

## [4.2.0]
### Changed
- IDEA - upgrade intellij platformVersion to latestVersion `2202.2+`
- Dependencies - upgrade `org.jetbrains.intellij` to `1.6.0`

## [4.1.0]
### Changed 
- fixed defects
- Dependencies - upgrade `org.jetbrains.intellij` to `1.5.2`

## [4.0.0]
### Added
- changelog.md
- add Dependencies plugin: `org.jetbrains.changelog 1.3.1`

### Changed
- IDEA - upgrade intellij platformVersion to `2021.1`
- Dependencies - upgrade `org.jetbrains.intellij` to `1.3.0` 


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# SmartTomcat
<!-- Plugin description -->
The Tomcat plugin for Intellij IDEA

The SmartTomcat will auto load the Webapp classes and libs from project and module, You needn't copy the classes and libs to the WEB-INF/classes and WEB-INF/lib.
The Smart Tomcat plugin will auto config the classpath for tomcat server.
The Smart Tomcat support Tomcat 6+
<!-- Plugin description end -->

[![build](https://github.com/zengkid/SmartTomcat/actions/workflows/build.yml/badge.svg)](https://github.com/zengkid/SmartTomcat/actions/workflows/build.yml)

### User Guide
* Tomcat Server Setting

        Navigate File -> Setting or Ctrl + Alt + S  Open System Settings.
        In the Setting UI, go to Tomcat Server, and then add your tomcat servers, e.g. tomcat6, tomcat8, tomcat9

![Smart Tomcat Setting1](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting1.png "Smart Tomcat")
![Smart Tomcat Setting2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting2.png "Smart Tomcat")
![Smart Tomcat Setting2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/setting3.png "Smart Tomcat")
  
* Run/Debug setup
        
        Navigat Run -> Edit Configrations to Open Run/Debug Configrations. 
        In the Run/Debug Configrations, add new configration, choose Smart Tomcat, 
        for detail config as below
        
![Smart Tomcat run1](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run1.png "Smart Tomcat")
![Smart Tomcat run2](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run2.png "Smart Tomcat")
![Smart Tomcat run3](https://raw.githubusercontent.com/zengkid/SmartTomcat/master/doc/run3.png "Smart Tomcat")
  
* Run/Debug config detail
    * Tomcat Server
        
            choose the tomcat server.
        
    * Deployment Directory
    
            the directory must be in project or module webapp. 
            maven or gradle project, the default folder is <project_name>/src/main/webapp
   
      **DON'T add output webapp to deployment directory.**
            
    * Custom Context
        
            opional, if webapp/META-INF/context.xml, if will auto add it.
            sample context.xml:    
        ```xml
        <?xml version="1.0" encoding="UTF-8"?>
        
        <Context>
            <Environment name="varName1" value="theValue1" type="java.lang.String" override="false"/>
            <Environment name="varName2" value="theValue2" type="java.lang.String" override="false"/>
        
            <Resource name="jdbc/ds"
                      auth="Container"
                      type="javax.sql.DataSource"
                      username="sa"
                      password="sa"
                      driverClassName="org.h2.Driver"
                      url="jdbc:h2:mem:db;DB_CLOSE_DELAY=-1"
                      maxActive="8"
                      maxIdle="4"/>
        </Context>
      ```
      In Java Servlet, we can call it as below     
       ```java      
             Context ctx = new InitialContext();
             ctx = (Context) ctx.lookup("java:comp/env");
             String value1 = (String) ctx.lookup("varName1");
             String value2 = (String) ctx.lookup("varName2");
             DataSource datasource = (DataSource) ctx.lookup("jdbc/ds");
         ```      
        
    * Context Path
    
            default value is '/<module_name>'
            
    * Server Port
            
            default value is 8080
            
    * ~~AJP Port~~
    
         ~~default value is 8009~~
    
    * Admin Port
    
            default value is 8005
            
    * VM Options
    
            extract tomcat VM options
            e.g. -Duser.language=en
    
    * Env Options
        
            extract tomcat env parmaters
            e.g. param1=value1


================================================
FILE: build.gradle.kts
================================================
import org.jetbrains.changelog.Changelog
import org.jetbrains.changelog.markdownToHTML
import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType
//import org.jetbrains.intellij.platform.gradle.models.ProductRelease

fun prop(key: String) = providers.gradleProperty(key).get()

plugins {
    id("java")
    alias(libs.plugins.intelliJPlatform) // IntelliJ Platform Gradle Plugin
    alias(libs.plugins.changelog) // Gradle Changelog Plugin
}

group = prop("pluginGroup")
version = prop("pluginVersion")

// Configure project's dependencies
repositories {
    mavenCentral()
    intellijPlatform {
        defaultRepositories()
    }
}

dependencies {
    intellijPlatform {
        intellijIdea(prop("platformVersion"))
        bundledPlugin("com.intellij.java")
    }
}

// Configure Gradle IntelliJ Plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin
intellijPlatform {
    pluginConfiguration {
        name = prop("pluginName")
        version = prop("pluginVersion")
        ideaVersion {
            sinceBuild = prop("pluginSinceBuild")
        }

        description = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
            val start = "<!-- Plugin description -->"
            val end = "<!-- Plugin description end -->"

            with(it.lines()) {
                if (!containsAll(listOf(start, end))) {
                    throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
                }
                subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
            }
        }
    }

    pluginVerification {

        ides {
            create(IntelliJPlatformType.IntellijIdea, prop("platformVersion"))
//            recommended()
//            select {
//                types = listOf(IntelliJPlatformType.IntellijIdea)
//                channels = listOf(ProductRelease.Channel.RELEASE)
//                sinceBuild = prop("pluginSinceBuild")
//            }
        }
    }

}
changelog {
    version = prop("pluginVersion")
    itemPrefix = "-"
    keepUnreleasedSection = true
    unreleasedTerm = "[Unreleased]"
    groups = listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security")
    combinePreReleases = true
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(prop("jdkVersion")))
    }
}

tasks {
    wrapper {
        gradleVersion = prop("gradleVersion")
    }

    withType<JavaCompile> {
        sourceCompatibility = prop("compatibleJdkVersion")
        targetCompatibility = prop("compatibleJdkVersion")
    }

    patchPluginXml {
        changeNotes = provider {
            changelog.renderItem(
                changelog
                    .getLatest()
                    .withHeader(false)
                    .withEmptySections(false),
                Changelog.OutputType.HTML
            )
        }
    }

    publishPlugin {
        dependsOn(patchChangelog)
        token.set(System.getenv("intellijPublishToken"))
    }
}


================================================
FILE: config-example.txt
================================================
Config Example

Deployment Directory:  project_name/web-module/src/main/webapp
Modules Root: project_name/web-module
Context Path: /web-dir    
Server Port:8080
Ajp port:8009
Tomcat Port:8005
Vm options:-Dspring.profiles.active=dev -Xmx2048m -Xms768m
Evn options:


================================================
FILE: gradlew
================================================
#!/bin/sh

#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#

##############################################################################
#
#   Gradle start up script for POSIX generated by Gradle.
#
#   Important for running:
#
#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
#       noncompliant, but you have some other compliant shell such as ksh or
#       bash, then to run this script, type that shell name before the whole
#       command line, like:
#
#           ksh Gradle
#
#       Busybox and similar reduced shells will NOT work, because this script
#       requires all of these POSIX shell features:
#         * functions;
#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
#         * compound commands having a testable exit status, especially «case»;
#         * various built-in commands including «command», «set», and «ulimit».
#
#   Important for patching:
#
#   (2) This script targets any POSIX shell, so it avoids extensions provided
#       by Bash, Ksh, etc; in particular arrays are avoided.
#
#       The "traditional" practice of packing multiple parameters into a
#       space-separated string is a well documented source of bugs and security
#       problems, so this is (mostly) avoided, by progressively accumulating
#       options in "$@", and eventually passing that to Java.
#
#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
#       see the in-line comments for details.
#
#       There are tweaks for specific operating systems such as AIX, CygWin,
#       Darwin, MinGW, and NonStop.
#
#   (3) This script is generated from the Groovy template
#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
#       within the Gradle project.
#
#       You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################

# Attempt to set APP_HOME

# Resolve links: $0 may be a link
app_path=$0

# Need this for daisy-chained symlinks.
while
    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
    [ -h "$app_path" ]
do
    ls=$( ls -ld "$app_path" )
    link=${ls#*' -> '}
    case $link in             #(
      /*)   app_path=$link ;; #(
      *)    app_path=$APP_HOME$link ;;
    esac
done

# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

warn () {
    echo "$*"
} >&2

die () {
    echo
    echo "$*"
    echo
    exit 1
} >&2

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in                #(
  CYGWIN* )         cygwin=true  ;; #(
  Darwin* )         darwin=true  ;; #(
  MSYS* | MINGW* )  msys=true    ;; #(
  NONSTOP* )        nonstop=true ;;
esac



# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD=$JAVA_HOME/jre/sh/java
    else
        JAVACMD=$JAVA_HOME/bin/java
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD=java
    if ! command -v java >/dev/null 2>&1
    then
        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
    case $MAX_FD in #(
      max*)
        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        MAX_FD=$( ulimit -H -n ) ||
            warn "Could not query maximum file descriptor limit"
    esac
    case $MAX_FD in  #(
      '' | soft) :;; #(
      *)
        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
        # shellcheck disable=SC2039,SC3045
        ulimit -n "$MAX_FD" ||
            warn "Could not set maximum file descriptor limit to $MAX_FD"
    esac
fi

# Collect all arguments for the java command, stacking in reverse order:
#   * args from the command line
#   * the main class name
#   * -classpath
#   * -D...appname settings
#   * --module-path (only if needed)
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.

# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )

    JAVACMD=$( cygpath --unix "$JAVACMD" )

    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    for arg do
        if
            case $arg in                                #(
              -*)   false ;;                            # don't mess with options #(
              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
                    [ -e "$t" ] ;;                      #(
              *)    false ;;
            esac
        then
            arg=$( cygpath --path --ignore --mixed "$arg" )
        fi
        # Roll the args list around exactly as many times as the number of
        # args, so each arg winds up back in the position where it started, but
        # possibly modified.
        #
        # NB: a `for` loop captures its iteration list before it begins, so
        # changing the positional parameters here affects neither the number of
        # iterations, nor the values presented in `arg`.
        shift                   # remove old arg
        set -- "$@" "$arg"      # push replacement arg
    done
fi


# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
#     and any embedded shellness will be escaped.
#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
#     treated as '${Hostname}' itself on the command line.

set -- \
        "-Dorg.gradle.appname=$APP_BASE_NAME" \
        -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
        "$@"

# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
    die "xargs is not available"
fi

# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
#   set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#

eval "set -- $(
        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
        xargs -n1 |
        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
        tr '\n' ' '
    )" '"$@"'

exec "$JAVACMD" "$@"


================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem

@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

:execute
@rem Setup the command line



@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*

:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: settings.gradle.kts
================================================
rootProject.name = "SmartTomcat"
//systemProp.system=systemValue


pluginManagement {
    repositories {
        mavenCentral()
        maven("https://oss.sonatype.org/content/repositories/snapshots/")
        gradlePluginPortal()
        maven("https://maven.aliyun.com/nexus/content/repositories/gradle-plugin")
    }
}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/ServerConsoleView.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Url;
import com.intellij.util.Urls;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author : zengkid
 * Date   : 2017-02-23
 * Time   : 00:13
 */
public class ServerConsoleView extends ConsoleViewImpl {
    private final TomcatRunConfiguration configuration;
    private boolean printStarted = false;
    private final List<String> httpPorts = new ArrayList<>();
    private final List<String> httpsPorts = new ArrayList<>();

    public ServerConsoleView(TomcatRunConfiguration configuration) {
        super(configuration.getProject(), true);
        this.configuration = configuration;
    }

    @Override
    public void print(@NotNull String s, @NotNull ConsoleViewContentType contentType) {
        super.print(s, contentType);

        if (printStarted) {
            return;
        }

        // skip the exception log e.g.:
        // at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
        boolean isExceptionLog = s.trim().startsWith("at ");
        if (isExceptionLog) {
            return;
        }

        if (this.parsePorts(s)) {
            return;
        }

        if (s.contains("org.apache.catalina.startup.Catalina start")
                || s.contains("org.apache.catalina.startup.Catalina.start")) {
            boolean portNotFound = httpPorts.isEmpty() && httpsPorts.isEmpty();
            // Use the configured port if the port is not found in the log
            if (portNotFound) {
                this.httpPorts.add(String.valueOf(configuration.getPort()));
                Integer sslPort = configuration.getSslPort();
                if (sslPort != null) {
                    this.httpsPorts.add(String.valueOf(sslPort));
                }
            }

            List<Url> urls = buildServerUrls();
            for (Url url : urls) {
                super.print(url + "\n", contentType);
            }
            printStarted = true;
        }
    }

    // Parse the port number from the log
    // 21-Jun-2023 13:27:15.385 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
    // 21-Jun-2023 13:27:15.385 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["https-jsse-nio-8443"]
    private boolean parsePorts(String s) {
        Pattern pattern = Pattern.compile("http-nio-(\\d+)");
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            String port = matcher.group(1);
            if (!this.httpPorts.contains(port)) {
                this.httpPorts.add(port);
            }
            return true;
        }

        pattern = Pattern.compile("https-jsse-nio-(\\d+)");
        matcher = pattern.matcher(s);
        if (matcher.find()) {
            String port = matcher.group(1);
            if (!this.httpsPorts.contains(port)) {
                this.httpsPorts.add(port);
            }
            return true;
        }

        return false;
    }

    private List<Url> buildServerUrls() {
        List<Url> urls = new ArrayList<>();
        String path = '/' + StringUtil.trimStart(configuration.getContextPath(), "/");

        for (String httpPort : httpPorts) {
            boolean isDefaultPort = "80".equals(httpPort);
            String authority = "localhost" + (isDefaultPort ? "" : ":" + httpPort);
            urls.add(Urls.newHttpUrl(authority, path));
        }

        for (String httpsPort : httpsPorts) {
            boolean isDefaultPort = "443".equals(httpsPort);
            String authority = "localhost" + (isDefaultPort ? "" : ":" + httpsPort);
            urls.add(Urls.newUrl("https", authority, path));
        }

        return urls;
    }
}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatCommandLineState.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.JavaCommandLineState;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.ParametersList;
import com.intellij.execution.process.KillableColoredProcessHandler;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderEnumerator;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PathsList;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;

/**
 * Author : zengkid
 * Date   : 2017-02-17
 * Time   : 11:10 AM
 */

public class TomcatCommandLineState extends JavaCommandLineState {

    private static final String JDK_JAVA_OPTIONS = "JDK_JAVA_OPTIONS";
    private static final String ENV_JDK_JAVA_OPTIONS = "--add-opens=java.base/java.lang=ALL-UNNAMED " +
            "--add-opens=java.base/java.io=ALL-UNNAMED " +
            "--add-opens=java.base/java.util=ALL-UNNAMED " +
            "--add-opens=java.base/java.util.concurrent=ALL-UNNAMED " +
            "--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED";

    private static final String TOMCAT_MAIN_CLASS = "org.apache.catalina.startup.Bootstrap";
    private static final String PARAM_CATALINA_HOME = "catalina.home";
    private static final String PARAM_CATALINA_BASE = "catalina.base";
    private static final String PARAM_CATALINA_TMPDIR = "java.io.tmpdir";
    private static final String PARAM_LOGGING_CONFIG = "java.util.logging.config.file";
    private static final String PARAM_LOGGING_MANAGER = "java.util.logging.manager";
    private static final String PARAM_LOGGING_MANAGER_VALUE = "org.apache.juli.ClassLoaderLogManager";
    private TomcatRunConfiguration configuration;

    protected TomcatCommandLineState(@NotNull ExecutionEnvironment environment) {
        super(environment);
    }

    protected TomcatCommandLineState(ExecutionEnvironment environment, TomcatRunConfiguration configuration) {
        this(environment);
        this.configuration = configuration;
    }

    @Override
    protected GeneralCommandLine createCommandLine() throws ExecutionException {
        GeneralCommandLine commandLine = super.createCommandLine();

        // Set JDK_JAVA_OPTIONS
        String originalJdkJavaOptions = commandLine.getEnvironment().get(JDK_JAVA_OPTIONS);
        String jdkJavaOptions = originalJdkJavaOptions == null ? ENV_JDK_JAVA_OPTIONS : originalJdkJavaOptions + " " + ENV_JDK_JAVA_OPTIONS;
        return commandLine.withEnvironment(JDK_JAVA_OPTIONS, jdkJavaOptions);
    }

    @Override
    @NotNull
    protected OSProcessHandler startProcess() throws ExecutionException {
        KillableColoredProcessHandler processHandler = new KillableColoredProcessHandler(createCommandLine());
        boolean shouldKillSoftly = !DebuggerSettings.getInstance().KILL_PROCESS_IMMEDIATELY;

        processHandler.setShouldKillProcessSoftly(shouldKillSoftly);
        ProcessTerminatedListener.attach(processHandler);

        return processHandler;
    }

    @Override
    protected JavaParameters createJavaParameters() {
        try {
            Path catalinaBase = PluginUtils.getCatalinaBase(configuration);
            Module module = configuration.getModule();
            if (catalinaBase == null || module == null) {
                throw new ExecutionException("The Module Root specified is not a module according to Intellij");
            }

            Path tomcatInstallationPath = Paths.get(configuration.getTomcatInfo().getPath());
            Project project = configuration.getProject();
            String tomcatVersion = configuration.getTomcatInfo().getVersion();
            String vmOptions = configuration.getVmOptions();
            String extraClassPath = configuration.getExtraClassPath();
            Map<String, String> envOptions = configuration.getEnvOptions();

            //copy to project folder, and then user is able to update server.xml under the project.
            Path projectConfPath = Paths.get(Objects.requireNonNull(project.getBasePath()), ".smarttomcat", module.getName(), "conf");
            if (!projectConfPath.toFile().exists() || PluginUtils.isEmptyFolder(projectConfPath)) {
                FileUtil.createDirectory(projectConfPath.toFile());
                FileUtil.copyDir(tomcatInstallationPath.resolve("conf").toFile(), projectConfPath.toFile());
            }

            // Copy the Tomcat configuration files to the working directory
            Path confPath = catalinaBase.resolve("conf");
            FileUtil.delete(confPath.toFile());
            FileUtil.createDirectory(confPath.toFile());
            FileUtil.copyDir(projectConfPath.toFile(), confPath.toFile());
            // create the temp folder
            FileUtil.createDirectory(catalinaBase.resolve("temp").toFile());

            updateServerConf(confPath, configuration);
            createContextFile(tomcatVersion, module, confPath);
            deleteTomcatWorkFiles(catalinaBase);

            ProjectRootManager manager = ProjectRootManager.getInstance(project);

            JavaParameters javaParams = new JavaParameters();
            javaParams.setDefaultCharset(project);
            javaParams.setWorkingDirectory(catalinaBase.toFile());
            javaParams.setJdk(manager.getProjectSdk());

            javaParams.getClassPath().add(tomcatInstallationPath.resolve("bin/bootstrap.jar").toFile());
            javaParams.getClassPath().add(tomcatInstallationPath.resolve("bin/tomcat-juli.jar").toFile());
            if (StringUtil.isNotEmpty(extraClassPath)) {
                javaParams.getClassPath().addAll(StringUtil.split(extraClassPath, File.pathSeparator));
            }

            javaParams.setMainClass(TOMCAT_MAIN_CLASS);
            javaParams.getProgramParametersList().add("start");

            javaParams.setPassParentEnvs(configuration.isPassParentEnvs());
            if (envOptions != null) {
                javaParams.setEnv(envOptions);
            }

            ParametersList vmParams = javaParams.getVMParametersList();
            vmParams.addParametersString(vmOptions);
            vmParams.addProperty(PARAM_CATALINA_HOME, tomcatInstallationPath.toString());
            vmParams.defineProperty(PARAM_CATALINA_BASE, catalinaBase.toString());
            vmParams.defineProperty(PARAM_CATALINA_TMPDIR, catalinaBase.resolve("temp").toString());
            vmParams.defineProperty(PARAM_LOGGING_CONFIG, confPath.resolve("logging.properties").toString());
            vmParams.defineProperty(PARAM_LOGGING_MANAGER, PARAM_LOGGING_MANAGER_VALUE);

            return javaParams;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Nullable
    @Override
    protected ConsoleView createConsole(@NotNull Executor executor) {
        return new ServerConsoleView(configuration);
    }

    private void updateServerConf(Path confPath, TomcatRunConfiguration cfg)
            throws ParserConfigurationException, XPathExpressionException, TransformerException, IOException, SAXException {
        Path serverXml = confPath.resolve("server.xml");
        Document doc = PluginUtils.createDocumentBuilder().parse(serverXml.toFile());
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression exprConnectorShutdown = xpath.compile("/Server[@shutdown='SHUTDOWN']");
        XPathExpression serviceExpression = xpath.compile("/Server/Service[@name='Catalina']");
        XPathExpression exprConnector = xpath.compile("/Server/Service[@name='Catalina']/Connector[@protocol and (not(@SSLEnabled) or @SSLEnabled='false')]");
        XPathExpression exprSSLConnector = xpath.compile("/Server/Service[@name='Catalina']/Connector[@SSLEnabled='true']");
        XPathExpression exprContext = xpath.compile("/Server/Service[@name='Catalina']/Engine[@name='Catalina']/Host/Context");

        Element serviceE = (Element) serviceExpression.evaluate(doc, XPathConstants.NODE);
        Element portShutdown = (Element) exprConnectorShutdown.evaluate(doc, XPathConstants.NODE);
        Element portE = (Element) exprConnector.evaluate(doc, XPathConstants.NODE);
        Element sslPortE = (Element) exprSSLConnector.evaluate(doc, XPathConstants.NODE);

        NodeList nodeList = (NodeList) exprContext.evaluate(doc, XPathConstants.NODESET);
        if (nodeList != null) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                node.getParentNode().removeChild(node);
            }
        }

        if (portShutdown != null) {
            portShutdown.setAttribute("port", String.valueOf(cfg.getAdminPort()));
        }
        if (portE != null) {
            portE.setAttribute("port", String.valueOf(cfg.getPort()));
        }
        Integer sslPort = cfg.getSslPort();

        if (sslPortE != null && sslPort != null) {
            // Update SSL configuration
            sslPortE.setAttribute("port", sslPort.toString());
            if (portE != null) {
                portE.setAttribute("redirectPort", sslPort.toString());
            }
        } else {
            // Clean up SSL configuration
            if (portE != null) {
                portE.removeAttribute("redirectPort");
            }
            if (serviceE != null && sslPortE != null) {
                serviceE.removeChild(sslPortE);
            }
        }

        PluginUtils.createTransformer().transform(new DOMSource(doc), new StreamResult(serverXml.toFile()));
    }

    private void createContextFile(String tomcatVersion, Module module, Path confPath)
            throws ParserConfigurationException, IOException, SAXException, TransformerException {
        String docBase = configuration.getDocBase();
        String contextPath = configuration.getContextPath();
        String normalizedContextPath = StringUtil.trim(contextPath, ch -> ch != '/');
        String contextFileName = StringUtil.defaultIfEmpty(normalizedContextPath, "ROOT").replace('/', '#');
        Path contextFilesDir = confPath.resolve("Catalina/localhost");
        Path contextFilePath = contextFilesDir.resolve(contextFileName + ".xml");

        // Create `conf/Catalina/localhost` folder
        FileUtil.createDirectory(contextFilesDir.toFile());

        DocumentBuilder builder = PluginUtils.createDocumentBuilder();
        Document doc = builder.newDocument();
        Element contextRoot = createContextElement(doc, builder);

        contextRoot.setAttribute("docBase", docBase);

        collectResources(doc, contextRoot, module, tomcatVersion);
        doc.appendChild(contextRoot);

        StringWriter writer = new StringWriter();
        PluginUtils.createTransformer().transform(new DOMSource(doc), new StreamResult(writer));
        FileUtil.writeToFile(contextFilePath.toFile(), writer.toString());
    }

    private Element createContextElement(Document doc, DocumentBuilder builder) throws IOException, SAXException {
        Path contextFile = findContextFileInApp();

        if (contextFile == null) {
            return doc.createElement("Context");
        }

        Element contextEl = builder.parse(contextFile.toFile()).getDocumentElement();
        return (Element) doc.importNode(contextEl, true);
    }

    private Path findContextFileInApp() {
        String docBase = configuration.getDocBase();
        if (docBase == null) {
            return null;
        }

        Path metaInf = Paths.get(docBase).resolve("META-INF");
        Path contextLocalFile = metaInf.resolve("context_local.xml");
        Path contextFile = metaInf.resolve("context.xml");

        if (Files.exists(contextLocalFile)) {
            return contextLocalFile;
        } else if (Files.exists(contextFile)) {
            return contextFile;
        } else {
            return null;
        }
    }

    private void collectResources(Document doc, Element contextRoot, Module module, String tomcatVersion) {
        String majorVersionStr = tomcatVersion.split("\\.")[0];
        int majorVersion = majorVersionStr.isEmpty() ? 8 : Integer.parseInt(majorVersionStr);
        PathsList pathsList = OrderEnumerator.orderEntries(module)
                .withoutSdk().runtimeOnly().productionOnly().getPathsList();

        if (pathsList.isEmpty()) {
            return;
        }

        if (majorVersion >= 8) {
            Element resources = createResourcesElementIfNecessary(doc, contextRoot);
            pathsList.getVirtualFiles().forEach(file -> {
                Element res;
                String tagName;
                String className;
                String webAppMount;

                if (file.isDirectory()) {
                    tagName = "PreResources";
                    className = "org.apache.catalina.webresources.DirResourceSet";
                    webAppMount = "/WEB-INF/classes";
                } else {
                    tagName = "PostResources";
                    className = "org.apache.catalina.webresources.FileResourceSet";
                    webAppMount = "/WEB-INF/lib/" + file.getName();
                }

                res = doc.createElement(tagName);
                res.setAttribute("base", file.getPath());
                res.setAttribute("className", className);
                res.setAttribute("webAppMount", webAppMount);

                resources.appendChild(res);
            });
        } else if (majorVersion >= 6) {
            Element loader = doc.createElement("Loader");
            loader.setAttribute("className", "org.apache.catalina.loader.VirtualWebappLoader");
            loader.setAttribute("virtualClasspath", StringUtil.join(pathsList.getPathList(), ";"));
            contextRoot.appendChild(loader);
        } else {
            throw new RuntimeException("Unsupported Tomcat version: " + tomcatVersion);
        }
    }

    private Element createResourcesElementIfNecessary(Document doc, Element contextRoot) {
        Element resources = (Element) contextRoot.getElementsByTagName("Resources").item(0);
        if (resources == null) {
            resources = doc.createElement("Resources");
            contextRoot.appendChild(resources);
        }

        if (Registry.is("smartTomcat.resources.allowLinking")) {
            resources.setAttribute("allowLinking", "true");
        }

        int cacheMaxSize = Registry.intValue("smartTomcat.resources.cacheMaxSize", 10240);
        if (cacheMaxSize > 0) {
            resources.setAttribute("cacheMaxSize", String.valueOf(cacheMaxSize));
        }

        return resources;
    }

    private void deleteTomcatWorkFiles(Path tomcatHome) {
        Path tomcatWorkPath = tomcatHome.resolve("work/Catalina/localhost");
        FileUtil.processFilesRecursively(tomcatWorkPath.toFile(), file -> {
            // Delete the work files except the session persistence files
            if (file.isFile() && !file.getName().endsWith(".ser")) {
                FileUtil.delete(file);
            }
            return true;
        });
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatLogFile.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.execution.configurations.LogFileOptions;
import com.intellij.execution.configurations.PredefinedLogFile;
import org.jetbrains.annotations.Nullable;

import java.nio.file.Path;
import java.nio.file.Paths;

public class TomcatLogFile {

    public static final String TOMCAT_LOCALHOST_LOG_ID = "Tomcat Localhost Log";
    public static final String TOMCAT_CATALINA_LOG_ID = "Tomcat Catalina Log";
    public static final String TOMCAT_ACCESS_LOG_ID = "Tomcat Access Log";
    public static final String TOMCAT_MANAGER_LOG_ID = "Tomcat Manager Log";
    public static final String TOMCAT_HOST_MANAGER_LOG_ID = "Tomcat Host Manager Log";

    private final String id;
    private final String filename;
    private boolean enabled;

    public TomcatLogFile(String id, String filename) {
        this.id = id;
        this.filename = filename;
    }

    public TomcatLogFile(String id, String filename, boolean enabled) {
        this(id, filename);
        this.enabled = enabled;
    }

    public String getId() {
        return id;
    }

    public LogFileOptions createLogFileOptions(PredefinedLogFile file, @Nullable Path logsDirPath) {
        Path logsPath = logsDirPath == null ? Paths.get("logs") : logsDirPath;
        return new LogFileOptions(file.getId(), logsPath.resolve(filename) + ".*", file.isEnabled());
    }

    public PredefinedLogFile createPredefinedLogFile() {
        return new PredefinedLogFile(id, enabled);
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfiguration.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.configurationStore.XmlSerializer;
import com.intellij.diagnostic.logging.LogConfigurationPanel;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.Executor;
import com.intellij.execution.JavaRunConfigurationExtensionManager;
import com.intellij.execution.configurations.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.poratu.idea.plugins.tomcat.setting.TomcatInfo;
import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Author : zengkid
 * Date   : 2/16/2017
 * Time   : 3:14 PM
 */
public class TomcatRunConfiguration extends LocatableConfigurationBase<LocatableRunConfigurationOptions> implements RunProfileWithCompileBeforeLaunchOption {

    private static final List<TomcatLogFile> tomcatLogFiles = Arrays.asList(
            new TomcatLogFile(TomcatLogFile.TOMCAT_LOCALHOST_LOG_ID, "localhost", true),
            new TomcatLogFile(TomcatLogFile.TOMCAT_ACCESS_LOG_ID, "localhost_access_log", true),
            new TomcatLogFile(TomcatLogFile.TOMCAT_CATALINA_LOG_ID, "catalina"),
            new TomcatLogFile(TomcatLogFile.TOMCAT_MANAGER_LOG_ID, "manager"),
            new TomcatLogFile(TomcatLogFile.TOMCAT_HOST_MANAGER_LOG_ID, "host-manager")
    );

    private static List<PredefinedLogFile> createPredefinedLogFiles() {
        return tomcatLogFiles.stream()
                .map(TomcatLogFile::createPredefinedLogFile)
                .collect(Collectors.toList());
    }

    private TomcatRunConfigurationOptions tomcatOptions = new TomcatRunConfigurationOptions();
    private RunConfigurationModule configurationModule;

    protected TomcatRunConfiguration(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
        super(project, factory, name);
        configurationModule = new RunConfigurationModule(project);

        TomcatServerManagerState applicationService = TomcatServerManagerState.getInstance();
        List<TomcatInfo> tomcatInfos = applicationService.getTomcatInfos();
        if (!tomcatInfos.isEmpty()) {
            tomcatOptions.setTomcatInfo(tomcatInfos.get(0));
        }
        addPredefinedTomcatLogFiles();
    }

    @NotNull
    @Override
    public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
        Project project = getProject();
        SettingsEditorGroup<TomcatRunConfiguration> group = new SettingsEditorGroup<>();
        TomcatRunnerSettingsEditor tomcatSetting = new TomcatRunnerSettingsEditor(project);

        group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), tomcatSetting);
        group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<>());
        JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group);
        return group;
    }

    @Override
    public void checkConfiguration() throws RuntimeConfigurationException {
        if (getTomcatInfo() == null) {
            throw new RuntimeConfigurationError("Tomcat server is not selected");
        }

        if (StringUtil.isEmpty(getDocBase())) {
            throw new RuntimeConfigurationError("Deployment directory cannot be empty");
        }

        if (StringUtil.isEmpty(getContextPath())) {
            throw new RuntimeConfigurationError("Context path cannot be empty");
        }

        if (getModule() == null) {
            throw new RuntimeConfigurationError("Module is not selected");
        }

        if (getPort() == null || getAdminPort() == null) {
            throw new RuntimeConfigurationError("Port cannot be empty");
        }
    }

    @Override
    public void onNewConfigurationCreated() {
        super.onNewConfigurationCreated();

        try {
            Project project = getProject();
            List<VirtualFile> webRoots = PluginUtils.findWebRoots(project);

            if (!webRoots.isEmpty()) {
                VirtualFile webRoot = webRoots.get(0);
                tomcatOptions.setDocBase(webRoot.getPath());
                Module module = PluginUtils.findContainingModule(webRoot.getPath(), project);

                if (module == null) {
                    module = PluginUtils.guessModule(project);
                }

                if (module != null) {
                    tomcatOptions.setContextPath("/" + PluginUtils.extractContextPath(module));
                }

                configurationModule.setModule(module);
            }
        } catch (Exception e) {
            //do nothing.
        }

    }

    @Override
    public Module @NotNull [] getModules() {
        ModuleManager moduleManager = ModuleManager.getInstance(getProject());
        return moduleManager.getModules();
    }

    @Nullable
    @Override
    public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) {
        return new TomcatCommandLineState(executionEnvironment, this);
    }

    @Override
    public @Nullable LogFileOptions getOptionsForPredefinedLogFile(PredefinedLogFile file) {
        for (TomcatLogFile logFile : tomcatLogFiles) {
            if (logFile.getId().equals(file.getId())) {
                return logFile.createLogFileOptions(file, PluginUtils.getTomcatLogsDirPath(this));
            }
        }

        return super.getOptionsForPredefinedLogFile(file);
    }

    @Override
    public void readExternal(@NotNull Element element) throws InvalidDataException {
        super.readExternal(element);
        XmlSerializer.deserializeInto(element, tomcatOptions);
        configurationModule.readExternal(element);

        // for backward compatibility
        if (getAllLogFiles().isEmpty()) {
            addPredefinedTomcatLogFiles();
        }

        // for backward compatibility
        if (configurationModule.getModule() == null) {
            configurationModule.setModule(PluginUtils.findContainingModule(tomcatOptions.getDocBase(), getProject()));
        }
    }

    @Override
    public void writeExternal(@NotNull Element element) throws WriteExternalException {
        super.writeExternal(element);
        XmlSerializer.serializeObjectInto(tomcatOptions, element);
        if (configurationModule.getModule() != null) {
            configurationModule.writeExternal(element);
        }
    }

    private void addPredefinedTomcatLogFiles() {
        createPredefinedLogFiles().forEach(this::addPredefinedLogFile);
    }

    @Nullable
    public Module getModule() {
        return this.configurationModule.getModule();
    }

    public void setModule(Module module) {
        this.configurationModule.setModule(module);
    }

    public TomcatInfo getTomcatInfo() {
        return tomcatOptions.getTomcatInfo();
    }

    public void setTomcatInfo(TomcatInfo tomcatInfo) {
        tomcatOptions.setTomcatInfo(tomcatInfo);
    }

    public String getCatalinaBase() { return tomcatOptions.getCatalinaBase(); }
    public void setCatalinaBase(String catalinaBase) { tomcatOptions.setCatalinaBase(catalinaBase); }
    public String getDocBase() {
        return tomcatOptions.getDocBase();
    }

    public void setDocBase(String docBase) {
        tomcatOptions.setDocBase(docBase);
    }

    public String getContextPath() {
        return tomcatOptions.getContextPath();
    }

    public void setContextPath(String contextPath) {
        tomcatOptions.setContextPath(contextPath);
    }

    public Integer getPort() {
        return tomcatOptions.getPort();
    }

    public void setPort(Integer port) {
        tomcatOptions.setPort(port);
    }

    public Integer getSslPort() {
        return tomcatOptions.getSslPort();
    }

    public void setSslPort(Integer sslPort) {
        tomcatOptions.setSslPort(sslPort);
    }

    public Integer getAdminPort() {
        return tomcatOptions.getAdminPort();
    }

    public void setAdminPort(Integer adminPort) {
        tomcatOptions.setAdminPort(adminPort);
    }

    public String getVmOptions() {
        return tomcatOptions.getVmOptions();
    }

    public void setVmOptions(String vmOptions) {
        tomcatOptions.setVmOptions(vmOptions);
    }

    public Map<String, String> getEnvOptions() {
        return tomcatOptions.getEnvOptions();
    }

    public void setEnvOptions(Map<String, String> envOptions) {
        tomcatOptions.setEnvOptions(envOptions);
    }

    public Boolean isPassParentEnvs() {
        return tomcatOptions.isPassParentEnvs();
    }

    public void setPassParentEnvironmentVariables(Boolean passParentEnvs) {
        tomcatOptions.setPassParentEnvs(passParentEnvs);
    }

    public String getExtraClassPath() {
        return tomcatOptions.getExtraClassPath();
    }

    public void setExtraClassPath(String extraClassPath) {
        tomcatOptions.setExtraClassPath(extraClassPath);
    }

    @Override
    public RunConfiguration clone() {
        TomcatRunConfiguration clone = (TomcatRunConfiguration) super.clone();
        clone.configurationModule = new RunConfigurationModule(getProject());
        clone.configurationModule.setModule(configurationModule.getModule());
        clone.tomcatOptions = XmlSerializerUtil.createCopy(tomcatOptions);
        return clone;
    }

    private static class TomcatRunConfigurationOptions implements Serializable {
        private TomcatInfo tomcatInfo;

        private String catalinaBase;
        private String docBase;
        private String contextPath;
        private Integer port = 8080;
        private Integer sslPort;
        private Integer adminPort = 8005;
        private String vmOptions;
        private Map<String, String> envOptions;
        private Boolean passParentEnvs = true;
        private String extraClassPath;

        public TomcatInfo getTomcatInfo() {
            return tomcatInfo;
        }

        public void setTomcatInfo(TomcatInfo tomcatInfo) {
            this.tomcatInfo = tomcatInfo;
        }

        @Nullable
        public String getCatalinaBase() { return this.catalinaBase; }
        public void setCatalinaBase(String catalinaBase) { this.catalinaBase = catalinaBase; }

        @Nullable
        public String getDocBase() {
            return docBase;
        }

        public void setDocBase(String docBase) {
            this.docBase = docBase;
        }

        public String getContextPath() {
            return contextPath;
        }

        public void setContextPath(String contextPath) {
            this.contextPath = contextPath;
        }

        public Integer getPort() {
            return port;
        }

        public void setPort(Integer port) {
            this.port = port;
        }

        public Integer getSslPort() {
            return sslPort;
        }

        public void setSslPort(Integer sslPort) {
            this.sslPort = sslPort;
        }

        public Integer getAdminPort() {
            return adminPort;
        }

        public void setAdminPort(Integer adminPort) {
            this.adminPort = adminPort;
        }

        public String getVmOptions() {
            return vmOptions;
        }

        public void setVmOptions(String vmOptions) {
            this.vmOptions = vmOptions;
        }

        public Map<String, String> getEnvOptions() {
            return envOptions;
        }

        public void setEnvOptions(Map<String, String> envOptions) {
            this.envOptions = envOptions;
        }

        public Boolean isPassParentEnvs() {
            return passParentEnvs;
        }

        public void setPassParentEnvs(Boolean passParentEnvs) {
            this.passParentEnvs = passParentEnvs;
        }

        public String getExtraClassPath() {
            return extraClassPath;
        }

        public void setExtraClassPath(String extraClassPath) {
            this.extraClassPath = extraClassPath;
        }
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfigurationType.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.SimpleConfigurationType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.NotNullLazyValue;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * Author : zengkid
 * Date   : 2/16/2017
 * Time   : 3:11 PM
 */
public class TomcatRunConfigurationType extends SimpleConfigurationType {

    private static final Icon TOMCAT_ICON = IconLoader.getIcon("/icon/tomcat.svg", TomcatRunConfigurationType.class);

    protected TomcatRunConfigurationType() {
        super("com.poratu.idea.plugins.tomcat",
                "Smart Tomcat",
                "Configuration to run Tomcat server",
                NotNullLazyValue.createValue(() -> TOMCAT_ICON));
    }

    @Override
    public @NotNull RunConfiguration createTemplateConfiguration(@NotNull Project project) {
        return new TomcatRunConfiguration(project, this, "");
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsEditor.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class TomcatRunnerSettingsEditor extends SettingsEditor<TomcatRunConfiguration> {

    private final TomcatRunnerSettingsForm form;

    public TomcatRunnerSettingsEditor(Project project) {
        form = new TomcatRunnerSettingsForm(project);
    }

    @Override
    protected void resetEditorFrom(@NotNull TomcatRunConfiguration configuration) {
        form.resetFrom(configuration);
    }

    @Override
    protected void applyEditorTo(@NotNull TomcatRunConfiguration configuration) throws ConfigurationException {
        form.applyTo(configuration);
    }

    @Override
   protected @NotNull JComponent createEditor() {
        return form.getMainPanel();
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsForm.java
================================================
package com.poratu.idea.plugins.tomcat.conf;

import com.intellij.application.options.ModulesComboBox;
import com.intellij.execution.configuration.EnvironmentVariablesTextFieldWithBrowseButton;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.CollectionComboBoxModel;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.RawCommandLineEditor;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.fields.ExtendableTextComponent;
import com.intellij.ui.components.fields.ExtendableTextField;
import com.intellij.util.Function;
import com.intellij.util.ui.FormBuilder;
import com.poratu.idea.plugins.tomcat.setting.TomcatInfo;
import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class TomcatRunnerSettingsForm implements Disposable {
    private static final Function<String, List<String>> PATH_SEPARATOR_LINE_PARSER = text -> {
        final List<String> result = new ArrayList<>();
        final StringTokenizer tokenizer = new StringTokenizer(text, File.pathSeparator, false);
        while (tokenizer.hasMoreTokens()) {
            result.add(tokenizer.nextToken());
        }
        return result;
    };
    private static final Function<List<String>, String> PATH_SEPARATOR_LINE_JOINER = strings -> StringUtil.join(strings, File.pathSeparator);

    private final Project project;
    private JPanel mainPanel;
    private final JPanel tomcatField = new JPanel(new BorderLayout());
    private final TomcatComboBox tomcatComboBox = new TomcatComboBox();
    private final TextFieldWithBrowseButton catalinaBaseField = new TextFieldWithBrowseButton();
    private final TextFieldWithBrowseButton docBaseField = new TextFieldWithBrowseButton();
    private final JPanel modulesComboBoxPanel = new JPanel(new GridBagLayout());
    private final ModulesComboBox modulesComboBox = new ModulesComboBox();
    private final JTextField contextPathField = new JTextField();
    private final JPanel portFieldPanel = new JPanel(new GridBagLayout());
    private final JPanel adminPortFieldPanel = new JPanel(new GridBagLayout());
    private final JTextField portField = new JTextField();
    private final JTextField sslPortField = new JTextField();
    private final JTextField adminPort = new JTextField();
    private final RawCommandLineEditor vmOptions = new RawCommandLineEditor();
    private final EnvironmentVariablesTextFieldWithBrowseButton envOptions = new EnvironmentVariablesTextFieldWithBrowseButton();
    private final RawCommandLineEditor extraClassPath = new RawCommandLineEditor(PATH_SEPARATOR_LINE_PARSER, PATH_SEPARATOR_LINE_JOINER);


    TomcatRunnerSettingsForm(Project project) {
        this.project = project;

        createTomcatField();
        createClasspathField();
        createPortField();
        createAdminPortField();

        extraClassPath.getEditorField().getEmptyText().setText("Use '" + File.pathSeparator + "' to separate paths");

        initCatalinaBaseDirectory();
        initDeploymentDirectory();
        buildForm();
    }

    private void createTomcatField() {
        JButton configurationButton = new JButton("Configure...");
        configurationButton.addActionListener(e -> PluginUtils.openTomcatConfiguration());
        tomcatField.add(tomcatComboBox, BorderLayout.CENTER);
        tomcatField.add(configurationButton, BorderLayout.EAST);
    }

    private void createClasspathField() {
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.weighty = 1;
        modulesComboBoxPanel.add(modulesComboBox, c);
        modulesComboBox.setModules(PluginUtils.getModules(project));
    }

    private void createPortField() {
        JLabel sslPortLabel = new JLabel("SSL port:");
        sslPortLabel.setHorizontalAlignment(SwingConstants.CENTER);
        sslPortLabel.setLabelFor(sslPortField);

        GridBagConstraints c = new GridBagConstraints();

        // default constraints
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 0;

        c.gridx = 0;
        c.weightx = 1;
        portFieldPanel.add(portField, c);

        c.gridx = 1;
        c.weightx = 0;
        c.ipadx = 10;
        portFieldPanel.add(sslPortLabel, c);

        c.gridx = 2;
        c.weightx = 1;
        portFieldPanel.add(sslPortField, c);
    }

    private void createAdminPortField() {
        GridBagConstraints c = new GridBagConstraints();

        // default constraints
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridy = 0;

        c.gridx = 0;
        c.weightx = 1;
        adminPortFieldPanel.add(adminPort, c);
    }

    private void initCatalinaBaseDirectory() {
        FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
                .withTitle("Select Catalina Base")
                .withDescription("Please select the Catalina Base directory");
//        catalinaBaseField.addBrowseFolderListener("Select Catalina Base", "Please select the Catalina Base directory",
//                project, descriptor);
        TextBrowseFolderListener listener = new TextBrowseFolderListener(descriptor);

        catalinaBaseField.addBrowseFolderListener(listener);
    }

    private void initDeploymentDirectory() {
        FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
                .withTitle("Select Deployment Directory")
                .withDescription("Please the directory to deploy");
//        docBaseField.addBrowseFolderListener("Select Deployment Directory", "Please the directory to deploy",
//                project, descriptor);
        docBaseField.addBrowseFolderListener(new TextBrowseFolderListener(descriptor));
        docBaseField.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
            // Update module selection when docBase is changed
            @Override
            protected void textChanged(@NotNull DocumentEvent e) {
                String docBase = docBaseField.getText();
                Module module = PluginUtils.findContainingModule(docBase, project);

                if (module != null) {
                    modulesComboBox.setSelectedModule(module);
                }
            }
        });
    }

    private void buildForm() {
        FormBuilder builder = FormBuilder.createFormBuilder()
                .addLabeledComponent("Tomcat server:", tomcatField)
                .addLabeledComponent("Catalina base:", catalinaBaseField)
                .addLabeledComponent("Deployment directory:", docBaseField)
                .addLabeledComponent("Use classpath of module:", modulesComboBoxPanel)
                .addLabeledComponent("Context path:", contextPathField)
                .addLabeledComponent("Server port:", portFieldPanel)
                .addLabeledComponent("Admin port:", adminPortFieldPanel)
                .addLabeledComponent("VM options:", vmOptions)
                .addLabeledComponent("Environment variables:", envOptions)
                .addLabeledComponent("Extra JVM classpath:", extraClassPath)
                .addComponentFillVertically(new JPanel(), 0);

        mainPanel = builder.getPanel();
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    public void resetFrom(TomcatRunConfiguration configuration) {
        tomcatComboBox.setSelectedItem(configuration.getTomcatInfo());

        Path catalinaBase = PluginUtils.getCatalinaBase(configuration);
        if (catalinaBase != null) {
            catalinaBaseField.setText(catalinaBase.toString());
        } else {
            catalinaBaseField.setText("");
        }

        docBaseField.setText(configuration.getDocBase());
        modulesComboBox.setSelectedModule(configuration.getModule());
        contextPathField.setText(configuration.getContextPath());
        portField.setText(String.valueOf(configuration.getPort()));
        sslPortField.setText(configuration.getSslPort() != null ? String.valueOf(configuration.getSslPort()) : "");
        adminPort.setText(String.valueOf(configuration.getAdminPort()));
        vmOptions.setText(configuration.getVmOptions());
        if (configuration.getEnvOptions() != null) {
            envOptions.setEnvs(configuration.getEnvOptions());
        }
        envOptions.setPassParentEnvs(configuration.isPassParentEnvs());
        extraClassPath.setText(configuration.getExtraClassPath());
    }

    public void applyTo(TomcatRunConfiguration configuration) throws ConfigurationException {
        try {
            configuration.setTomcatInfo((TomcatInfo) tomcatComboBox.getSelectedItem());
            configuration.setCatalinaBase(catalinaBaseField.getText());
            configuration.setDocBase(docBaseField.getText());
            configuration.setModule(modulesComboBox.getSelectedModule());
            configuration.setContextPath(contextPathField.getText());
            configuration.setPort(PluginUtils.parsePort(portField.getText()));
            configuration.setSslPort(StringUtil.isNotEmpty(sslPortField.getText()) ? PluginUtils.parsePort(sslPortField.getText()) : null);
            configuration.setAdminPort(PluginUtils.parsePort(adminPort.getText()));
            configuration.setVmOptions(vmOptions.getText());
            configuration.setEnvOptions(envOptions.getEnvs());
            configuration.setPassParentEnvironmentVariables(envOptions.isPassParentEnvs());
            configuration.setExtraClassPath(extraClassPath.getText());
        } catch (Exception e) {
            throw new ConfigurationException(e.getMessage());
        }
    }

    @Override
    public void dispose() {
        mainPanel = null;
    }

    private static class TomcatComboBox extends JComboBox<TomcatInfo> {

        TomcatComboBox() {
            super();

            List<TomcatInfo> tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos();
            ComboBoxModel<TomcatInfo> model = new CollectionComboBoxModel<>(tomcatInfos);
            setModel(model);

            initBrowsableEditor();
        }

        private void initBrowsableEditor() {
            ComboBoxEditor editor = new TomcatComboBoxEditor(this);
            setEditor(editor);
            setEditable(true);
        }

    }

    private static class TomcatComboBoxEditor extends BasicComboBoxEditor {
        private static final TomcatComboBoxTextComponentAccessor TEXT_COMPONENT_ACCESSOR = new TomcatComboBoxTextComponentAccessor();
        private final TomcatComboBox comboBox;
        private boolean fileDialogOpened;

        public TomcatComboBoxEditor(TomcatComboBox comboBox) {
            this.comboBox = comboBox;
        }

        @Override
        protected JTextField createEditorComponent() {
            ExtendableTextField editor = new ExtendableTextField();
            editor.addExtension(createBrowseExtension());
            editor.setBorder(null);
            editor.setEditable(false);
            editor.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1 && !fileDialogOpened) {
                        if (comboBox.isPopupVisible()) {
                            comboBox.hidePopup();
                        } else {
                            comboBox.showPopup();
                        }
                    }
                }
            });
            return editor;
        }

        private ExtendableTextComponent.Extension createBrowseExtension() {
            String tooltip = UIBundle.message("component.with.browse.button.browse.button.tooltip.text");
            Runnable browseRunnable = () -> {
                fileDialogOpened = true;
                PluginUtils.chooseTomcat(tomcatInfo -> TEXT_COMPONENT_ACCESSOR.setText(comboBox, tomcatInfo.getPath()));
                SwingUtilities.invokeLater(() -> fileDialogOpened = false);
            };
            return ExtendableTextComponent.Extension.create(AllIcons.General.OpenDisk, AllIcons.General.OpenDiskHover,
                    tooltip, browseRunnable);
        }
    }

    private static class TomcatComboBoxTextComponentAccessor implements TextComponentAccessor<JComboBox<TomcatInfo>> {

        @Override
        public String getText(JComboBox<TomcatInfo> component) {
            return component.getEditor().getItem().toString();
        }

        @Override
        public void setText(JComboBox<TomcatInfo> comboBox, @NotNull String text) {
            TomcatServerManagerState.createTomcatInfo(text).ifPresent(tomcatInfo -> {
                CollectionComboBoxModel<TomcatInfo> model = (CollectionComboBoxModel<TomcatInfo>) comboBox.getModel();
                model.add(tomcatInfo);
                comboBox.setSelectedItem(tomcatInfo);
            });
        }

    }

    //isFileVisible  is Non-extendable method usage violation,
    // use withExtensionFilter instead, but it's not support folder

    /*
    private static class IgnoreOutputFileChooserDescriptor extends FileChooserDescriptor {
        private static final FileChooserDescriptor singleFolderDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
        private final Project project;

        public IgnoreOutputFileChooserDescriptor(Project project) {
            super(singleFolderDescriptor);
            this.project = project;
        }

        @Override
        public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            Module[] modules = ModuleManager.getInstance(project).getModules();

            for (Module module : modules) {
                VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots();
                for (VirtualFile excludeFile : excludeRoots) {
                    if (excludeFile.equals(file)) {
                        return false;
                    }
                }
            }

            return super.isFileVisible(file, showHiddenFiles);
        }
    }
*/
}



================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatDebugger.java
================================================
package com.poratu.idea.plugins.tomcat.runner;

import com.intellij.debugger.impl.GenericDebuggerRunner;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration;
import org.jetbrains.annotations.NotNull;

/**
 * Author : zengkid
 * Date   : 2017-02-17
 * Time   : 11:00 AM
 */
public class TomcatDebugger extends GenericDebuggerRunner {
    private static final String RUNNER_ID = "SmartTomcatDebugger";

    @Override
    @NotNull
    public String getRunnerId() {
        return RUNNER_ID;
    }

    @Override
    public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
        return (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) && profile instanceof TomcatRunConfiguration);
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunConfigurationProducer.java
================================================
package com.poratu.idea.plugins.tomcat.runner;

import com.intellij.execution.Location;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.execution.actions.LazyRunConfigurationProducer;
import com.intellij.execution.application.ApplicationConfigurationType;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.util.containers.ContainerUtil;
import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration;
import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfigurationType;
import com.poratu.idea.plugins.tomcat.setting.TomcatInfo;
import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class TomcatRunConfigurationProducer extends LazyRunConfigurationProducer<TomcatRunConfiguration> {
    @NotNull
    @Override
    public ConfigurationFactory getConfigurationFactory() {
        return ConfigurationTypeUtil.findConfigurationType(TomcatRunConfigurationType.class);
    }

    @Override
    protected boolean setupConfigurationFromContext(@NotNull TomcatRunConfiguration configuration, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) {
        if (Registry.is("smartTomcat.disableRunConfigurationProducer")) {
            return false;
        }

        Module module = context.getModule();
        if (module == null) {
            return false;
        }

        // Skip if it contains a main class, to avoid conflict with the default Application run configuration
        PsiClass psiClass = ApplicationConfigurationType.getMainClass(context.getPsiLocation());
        if (psiClass != null) {
            return false;
        }

        List<VirtualFile> webRoots = findWebRoots(context.getLocation());
        if (webRoots.isEmpty()) {
            return false;
        }

        List<TomcatInfo> tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos();
        if (!tomcatInfos.isEmpty()) {
            configuration.setTomcatInfo(tomcatInfos.get(0));
        }
        String contextPath = PluginUtils.extractContextPath(module);
        configuration.setName("Tomcat: " + contextPath);
        configuration.setDocBase(webRoots.get(0).getPath());
        configuration.setContextPath("/" + contextPath);

        return true;
    }

    @Override
    public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) {
        return false;
    }

    @Override
    public boolean isConfigurationFromContext(@NotNull TomcatRunConfiguration configuration, @NotNull ConfigurationContext context) {
        if (Registry.is("smartTomcat.disableRunConfigurationProducer")) {
            return false;
        }

        List<VirtualFile> webRoots = findWebRoots(context.getLocation());
        return webRoots.stream().anyMatch(webRoot -> webRoot.getPath().equals(configuration.getDocBase()));
    }

    private List<VirtualFile> findWebRoots(@Nullable Location<?> location) {
        if (location == null) {
            return ContainerUtil.emptyList();
        }

        boolean isTestFile = PluginUtils.isUnderTestSources(location);
        if (isTestFile) {
            return ContainerUtil.emptyList();
        }

        return PluginUtils.findWebRoots(location.getModule());
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunner.java
================================================
package com.poratu.idea.plugins.tomcat.runner;

import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.impl.DefaultJavaProgramRunner;
import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration;
import org.jetbrains.annotations.NotNull;

/**
 * Author : zengkid
 * Date   : 2017-02-17
 * Time   : 11:01 AM
 */
public class TomcatRunner extends DefaultJavaProgramRunner {
    private static final String RUNNER_ID = "SmartTomcatRunner";

    @NotNull
    @Override
    public String getRunnerId() {
        return RUNNER_ID;
    }

    @Override
    public boolean canRun(@NotNull String executorId, @NotNull RunProfile runProfile) {
        return (DefaultRunExecutor.EXECUTOR_ID.equals(executorId)) && runProfile instanceof TomcatRunConfiguration;
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfo.java
================================================
package com.poratu.idea.plugins.tomcat.setting;

import java.io.Serializable;
import java.util.Objects;

/**
 * Author : zengkid
 * Date   : 2017-03-05
 * Time   : 16:17
 */
public class TomcatInfo implements Serializable {
    private String name;
    private String version;
    private String path;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TomcatInfo that = (TomcatInfo) o;
        return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(path, that.path);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, version, path);
    }

    @Override
    public String toString() {
        return name;
    }
}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoComponent.java
================================================
package com.poratu.idea.plugins.tomcat.setting;

import com.intellij.openapi.Disposable;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;

public class TomcatInfoComponent implements Disposable {

    private JPanel mainPanel;

    public TomcatInfoComponent(TomcatInfo tomcatInfo) {
        JBLabel versionLabel = new JBLabel(tomcatInfo.getVersion());
        JBLabel locationLabel = new JBLabel(tomcatInfo.getPath());
        mainPanel = FormBuilder.createFormBuilder()
                .setVerticalGap(UIUtil.LARGE_VGAP)
                .addLabeledComponent("Version:", versionLabel)
                .addLabeledComponent("Location:", locationLabel)
                .addComponentFillVertically(new JPanel(), 0)
                .getPanel();
        mainPanel.setBorder(JBUI.Borders.empty(0, 10));
    }

    public JComponent getMainPanel() {
        return mainPanel;
    }

    @Override
    public void dispose() {
        mainPanel = null;
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoConfigurable.java
================================================
package com.poratu.idea.plugins.tomcat.setting;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.NamedConfigurable;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class TomcatInfoConfigurable extends NamedConfigurable<TomcatInfo> {
    private final TomcatInfo tomcatInfo;
    private final TomcatInfoComponent tomcatInfoView;
    private String displayName;
    private final TomcatNameValidator<String> nameValidator;

    public TomcatInfoConfigurable(TomcatInfo tomcatInfo, Runnable treeUpdater, TomcatNameValidator<String> nameValidator) {
        super(true, treeUpdater);
        this.tomcatInfo = tomcatInfo;
        this.tomcatInfoView = new TomcatInfoComponent(tomcatInfo);
        this.displayName = tomcatInfo.getName();
        this.nameValidator = nameValidator;
    }

    @Override
    public void setDisplayName(String name) {
        this.displayName = name;
    }

    @Override
    public TomcatInfo getEditableObject() {
        return tomcatInfo;
    }

    @Override
    public String getBannerSlogan() {
        return null;
    }

    @Override
    public JComponent createOptionsPanel() {
        return tomcatInfoView.getMainPanel();
    }

    @Override
    public String getDisplayName() {
        return displayName;
    }

    @Override
    protected void checkName(@NonNls @NotNull String name) throws ConfigurationException {
        super.checkName(name);
        if (name.equals(tomcatInfo.getName())) {
            return;
        }
        nameValidator.validate(name);
    }

    @Override
    public boolean isModified() {
        return !displayName.equals(tomcatInfo.getName());
    }

    @Override
    public void apply() {
        tomcatInfo.setName(displayName);
    }
}

@FunctionalInterface
interface TomcatNameValidator<T> {
    void validate(T t) throws ConfigurationException;
}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServerManagerState.java
================================================
package com.poratu.idea.plugins.tomcat.setting;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.ui.Messages;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.XCollection;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.function.UnaryOperator;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;

/**
 * Author : zengkid
 * Date   : 2017-03-05
 * Time   : 15:20
 */

@State(name = "ServerConfiguration", storages = @Storage("smart.tomcat.xml"))
public class TomcatServerManagerState implements PersistentStateComponent<TomcatServerManagerState> {

    @XCollection(elementTypes = TomcatInfo.class)
    private final List<TomcatInfo> tomcatInfos = new ArrayList<>();

    public static TomcatServerManagerState getInstance() {
        return ApplicationManager.getApplication().getService(TomcatServerManagerState.class);
    }

    @NotNull
    public List<TomcatInfo> getTomcatInfos() {
        return tomcatInfos;
    }

    @Nullable
    @Override
    public TomcatServerManagerState getState() {
        return this;
    }

    @Override
    public void loadState(@NotNull TomcatServerManagerState tomcatSettingsState) {
        XmlSerializerUtil.copyBean(tomcatSettingsState, this);
    }

    public static Optional<TomcatInfo> createTomcatInfo(String tomcatHome) {
        return createTomcatInfo(tomcatHome, TomcatServerManagerState::generateTomcatName);
    }

    public static Optional<TomcatInfo> createTomcatInfo(String tomcatHome, UnaryOperator<String> nameGenerator) {
        File jarFile = Paths.get(tomcatHome, "lib/catalina.jar").toFile();
        if (!jarFile.exists()) {
            Messages.showErrorDialog("Can not find catalina.jar in " + tomcatHome, "Error");
            return Optional.empty();
        }

        final TomcatInfo tomcatInfo = new TomcatInfo();
        tomcatInfo.setPath(tomcatHome);

        try (JarFile jar = new JarFile(jarFile)) {
            ZipEntry entry = jar.getEntry("org/apache/catalina/util/ServerInfo.properties");
            Properties p = new Properties();
            try (InputStream is = jar.getInputStream(entry)) {
                p.load(is);
            }
            String serverInfo = p.getProperty("server.info");
            String serverNumber = p.getProperty("server.number");
            String name = nameGenerator == null ? generateTomcatName(serverInfo) : nameGenerator.apply(serverInfo);
            tomcatInfo.setName(name);
            tomcatInfo.setVersion(serverNumber);
        } catch (IOException e) {
            Messages.showErrorDialog("Can not read server version in " + tomcatHome, "Error");
            return Optional.empty();
        }

        return Optional.of(tomcatInfo);
    }

    private static String generateTomcatName(String name) {
        List<TomcatInfo> existingServers = getInstance().getTomcatInfos();
        List<String> existingNames = existingServers.stream()
                .map(TomcatInfo::getName)
                .collect(Collectors.toList());

        return PluginUtils.generateSequentName(existingNames, name);
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServersConfigurable.java
================================================
package com.poratu.idea.plugins.tomcat.setting;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MasterDetailsComponent;
import com.intellij.ui.CommonActionsPanel;
import com.intellij.util.IconUtil;
import com.poratu.idea.plugins.tomcat.utils.PluginUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * Author : zengkid
 * Date   : 2017-02-23
 * Time   : 00:14
 */
public class TomcatServersConfigurable extends MasterDetailsComponent {

    @Override
    public String getDisplayName() {
        return "Tomcat Server";
    }

    @Override
    public String getHelpTopic() {
        return "Smart Tomcat Help";
    }

    public TomcatServersConfigurable() {
        initTree();
    }

    @Override
    protected @Nullable List<AnAction> createActions(boolean fromPopup) {
        List<AnAction> actions = new ArrayList<>();
        actions.add(new AddTomcatAction());
        // noinspection MissingRecentApi - the inspection of the next line is incorrect. It is available in 193+, actually
        actions.add(new MyDeleteAction());
        return actions;
    }

    @Override
    public boolean isModified() {
        boolean modified = super.isModified();
        if (modified) {
            return true;
        }

        int size = TomcatServerManagerState.getInstance().getTomcatInfos().size();
        return myRoot.getChildCount() != size;
    }

    @Override
    public void reset() {
        myRoot.removeAllChildren();

        TomcatServerManagerState state = TomcatServerManagerState.getInstance();
        for (TomcatInfo info : state.getTomcatInfos()) {
            addNode(info, false);
        }
        super.reset();
    }

    @Override
    public void apply() throws ConfigurationException {
        super.apply();

        List<TomcatInfo> tomcatInfos = TomcatServerManagerState.getInstance().getTomcatInfos();
        tomcatInfos.clear();

        for (int i = 0; i < myRoot.getChildCount(); i++) {
            TomcatInfoConfigurable configurable = (TomcatInfoConfigurable) ((MyNode) myRoot.getChildAt(i)).getConfigurable();
            tomcatInfos.add(configurable.getEditableObject());
        }
    }

    @Override
    protected boolean wasObjectStored(Object editableObject) {
        // noinspection SuspiciousMethodCalls
        return TomcatServerManagerState.getInstance().getTomcatInfos().contains(editableObject);
    }

    private void addNode(TomcatInfo tomcatInfo, boolean selectInTree) {
        TomcatInfoConfigurable configurable = new TomcatInfoConfigurable(tomcatInfo, TREE_UPDATER, this::validateName);
        MyNode node = new MyNode(configurable);
        addNode(node, myRoot);

        if (selectInTree) {
            selectNodeInTree(node);
        }
    }

    private void validateName(String name) throws ConfigurationException {
        for (int i = 0; i < myRoot.getChildCount(); i++) {
            TomcatInfoConfigurable configurable = (TomcatInfoConfigurable) ((MyNode) myRoot.getChildAt(i)).getConfigurable();
            if (configurable.getEditableObject().getName().equals(name)) {
                throw new ConfigurationException("Duplicate name: \"" + name + "\"");
            }
        }
    }

    private class AddTomcatAction extends DumbAwareAction {
        public AddTomcatAction() {
            super("Add", "Add a Tomcat server", IconUtil.getAddIcon());
            registerCustomShortcutSet(CommonActionsPanel.getCommonShortcut(CommonActionsPanel.Buttons.ADD), myTree);
        }

        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
            PluginUtils.chooseTomcat(this::createUniqueName, tomcatInfo -> addNode(tomcatInfo, true));
        }

        private String createUniqueName(String preferredName) {
            List<String> existingNames = new ArrayList<>();

            for (int i = 0; i < myRoot.getChildCount(); i++) {
                String displayName = ((MyNode) myRoot.getChildAt(i)).getDisplayName();
                existingNames.add(displayName);
            }

            return PluginUtils.generateSequentName(existingNames, preferredName);
        }
    }

}


================================================
FILE: src/main/java/com/poratu/idea/plugins/tomcat/utils/PluginUtils.java
================================================
package com.poratu.idea.plugins.tomcat.utils;

import com.intellij.execution.Location;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleFileIndex;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.poratu.idea.plugins.tomcat.conf.TomcatRunConfiguration;
import com.poratu.idea.plugins.tomcat.setting.TomcatInfo;
import com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState;
import com.poratu.idea.plugins.tomcat.setting.TomcatServersConfigurable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Author : zengkid
 * Date   : 2017-03-06
 * Time   : 21:35
 */
public final class PluginUtils {
    private static final int MIN_PORT_VALUE = 0;
    private static final int MAX_PORT_VALUE = 65535;

    private PluginUtils() {
    }

    /**
     * Generate a sequent name based on the existing names
     *
     * @param existingNames existing names, e.g. ["tomcat 7", "tomcat 8", "tomcat 9"]
     * @param preferredName preferred name, e.g. "tomcat 8"
     * @return sequent name, e.g. "tomcat 8 (2)"
     */
    public static String generateSequentName(List<String> existingNames, String preferredName) {
        int maxSequent = 0;
        for (String existingName : existingNames) {
            Pattern pattern = Pattern.compile("^" + StringUtil.escapeToRegexp(preferredName) + "(?:\\s\\((\\d+)\\))?$");
            Matcher matcher = pattern.matcher(existingName);
            if (matcher.matches()) {
                String seq = matcher.group(1);
                if (seq == null) {
                    // No sequent implies that the sequent is 1
                    maxSequent = 1;
                } else {
                    maxSequent = Math.max(maxSequent, Integer.parseInt(seq));
                }
            }
        }

        return maxSequent == 0 ? preferredName : preferredName + " (" + (maxSequent + 1) + ")";
    }

    public static void chooseTomcat(Consumer<TomcatInfo> callback) {
        chooseTomcat(null, callback);
    }

    public static void chooseTomcat(UnaryOperator<String> nameGenerator, Consumer<TomcatInfo> callback) {
        FileChooserDescriptor descriptor = FileChooserDescriptorFactory
                .createSingleFolderDescriptor()
                .withTitle("Select Tomcat Server")
                .withDescription("Select the directory of the Tomcat Server");

        FileChooser.chooseFile(descriptor, null, null, file -> TomcatServerManagerState
                .createTomcatInfo(file.getPath(), nameGenerator)
                .ifPresent(callback));
    }

    @Nullable
    private static Path defaultCatalinaBase(TomcatRunConfiguration configuration) {
        String userHome = System.getProperty("user.home");
        Project project = configuration.getProject();
        Module module = configuration.getModule();

        if (module == null) {
            return null;
        }

        Path path = Paths.get(userHome, ".SmartTomcat", project.getName(), module.getName());
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                return null;
            }
        }

        return path;
    }

    @Nullable
    public static Path getCatalinaBase(TomcatRunConfiguration configuration) {
        if(!StringUtil.isEmptyOrSpaces(configuration.getCatalinaBase())) {
            /* CATALINA_BASE override from intellij run configuration */
            return Paths.get(configuration.getCatalinaBase());
        }

        return defaultCatalinaBase(configuration);
    }

    public static Path getTomcatLogsDirPath(TomcatRunConfiguration configuration) {
        Path catalinaBase = getCatalinaBase(configuration);
        if (catalinaBase != null) {
            return catalinaBase.resolve("logs");
        }
        return null;
    }

    @SuppressWarnings("HttpUrlsUsage")
    public static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
            dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        } catch (IllegalArgumentException ignored) {
            // Some Java implementations do not support these features
        }

        dbf.setExpandEntityReferences(false);

        return dbf.newDocumentBuilder();
    }

    @SuppressWarnings("HttpUrlsUsage")
    public static Transformer createTransformer() throws TransformerConfigurationException {
        TransformerFactory factory = TransformerFactory.newInstance();

        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

        Transformer transformer = factory.newTransformer();
        try {
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } catch (IllegalArgumentException ignored) {
            // ignore
        }
        return transformer;
    }

    public static void openTomcatConfiguration() {
        ShowSettingsUtil.getInstance().showSettingsDialog(null, TomcatServersConfigurable.class);
    }

    public static int parsePort(String text) throws ConfigurationException {
        if (StringUtil.isEmpty(text)) {
            throw new ConfigurationException("Port cannot be empty");
        }

        try {
            int port = Integer.parseInt(text);
            if (port < MIN_PORT_VALUE || port > MAX_PORT_VALUE) {
                throw new ConfigurationException("Port number must be between " + MIN_PORT_VALUE + " and " + MAX_PORT_VALUE);
            }
            return port;
        } catch (NumberFormatException e) {
            throw new ConfigurationException("Port number must be an integer");
        }
    }

    public static String extractContextPath(Module module) {
        String name = module.getName();
        String s = StringUtil.trimEnd(name, ".main");
        return ArrayUtil.getLastElement(s.split("\\."));
    }

    public static List<VirtualFile> findWebRoots(Module module) {
        List<VirtualFile> webRoots = new ArrayList<>();
        if (module == null) {
            return webRoots;
        }

        ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
        ModuleFileIndex fileIndex = moduleRootManager.getFileIndex();
        VirtualFile[] sourceRoots = moduleRootManager.getSourceRoots(false);
        List<VirtualFile> parentRoots = Stream.of(sourceRoots)
                .map(VirtualFile::getParent)
                .distinct()
                .toList();

        for (VirtualFile parentRoot : parentRoots) {
            fileIndex.iterateContentUnderDirectory(parentRoot, file -> {
                Path path = Paths.get(file.getPath(), "WEB-INF");
                if (Files.exists(path)) {
                    webRoots.add(file);
                }
                return true;
            }, file -> {
                if (file.isDirectory()) {
                    String path = file.getPath();
                    return webRoots.stream().noneMatch(root -> file.getPath().startsWith(root.getPath())) && !path.contains("node_modules");
                }
                return false;
            });
        }

        return webRoots;
    }

    public static List<VirtualFile> findWebRoots(Project project) {
        Module[] modules = ModuleManager.getInstance(project).getModules();
        List<VirtualFile> webRoots = new ArrayList<>();

        for (Module module : modules) {
            webRoots.addAll(findWebRoots(module));
        }

        return webRoots;
    }

    public static boolean isUnderTestSources(@Nullable Location<?> location) {
        if (location == null) {
            return false;
        }

        VirtualFile file = location.getVirtualFile();
        if (file == null) {
            return false;
        }

        return ProjectFileIndex.getInstance(location.getProject()).isInTestSourceContent(file);
    }

    /**
     * Get all modules except the module with name ends with ".test"
     */
    public static List<Module> getModules(Project project) {
        Module[] modules = ModuleManager.getInstance(project).getModules();
        return Arrays.stream(modules).filter(module -> !module.getName().endsWith(".test")).collect(Collectors.toList());
    }

    /**
     * Prefer the module with name ends with ".main" and has the least number of dots in the name,
     * e.g. `webapp.main` will be chosen over `webapp.library.main`
     * If no module with name ends with ".main", return the first module
     */
    public static @Nullable Module guessModule(Project project) {
        List<Module> modules = getModules(project);
        Module result = null;
        int dotCountInModuleName = Integer.MAX_VALUE;

        for (Module module : modules) {
            if (module.getName().endsWith(".main")) {
                int dotCount = StringUtil.countChars(module.getName(), '.');
                if (dotCount < dotCountInModuleName) {
                    result = module;
                    dotCountInModuleName = dotCount;
                }
            }
        }

        if (result != null) {
            return result;
        }

        return modules.stream().findFirst().orElse(null);
    }

    /**
     * Find the module containing the file
     */
    public static @Nullable Module findContainingModule(@Nullable String filePath, @NotNull Project project) {
        if (StringUtil.isEmpty(filePath)) {
            return null;
        }

        VirtualFile virtualFile = VfsUtil.findFile(Paths.get(filePath), true);
        if (virtualFile == null) {
            return null;
        }

        return ModuleUtilCore.findModuleForFile(virtualFile, project);
    }

    /**
     * Checks if the given folder is empty.
     *
     * @param path the path to the folder
     * @return {@code true} if the folder exists and is empty, {@code false} otherwise
     * @throws IOException if an I/O error occurs
     */

    public static boolean isEmptyFolder(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            try (Stream<Path> entries = Files.list(path)) {
                return entries.findFirst().isEmpty();
            }
        }
        return false;
    }

}


================================================
FILE: src/main/resources/META-INF/plugin.xml
================================================
<idea-plugin>
    <id>com.poratu.idea.plugins.tomcat</id>
    <name>Smart Tomcat</name>
    <vendor email="zengkid@msn.com">zengkid</vendor>
    <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
    <idea-version since-build="193.5233.102"/>

    <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
         on how to target different products -->
    <depends>com.intellij.modules.java</depends>

    <extensions defaultExtensionNs="com.intellij">
        <applicationConfigurable instance="com.poratu.idea.plugins.tomcat.setting.TomcatServersConfigurable"/>
        <applicationService serviceImplementation="com.poratu.idea.plugins.tomcat.setting.TomcatServerManagerState"/>
        <configurationType implementation="com.poratu.idea.plugins.tomcat.conf.TomcatRunConfigurationType"/>
        <runConfigurationProducer implementation="com.poratu.idea.plugins.tomcat.runner.TomcatRunConfigurationProducer"/>
        <programRunner implementation="com.poratu.idea.plugins.tomcat.runner.TomcatRunner"/>
        <programRunner implementation="com.poratu.idea.plugins.tomcat.runner.TomcatDebugger"/>
        <registryKey key="smartTomcat.disableRunConfigurationProducer" description="If enabled, the run configuration producer will be disabled." defaultValue="false" restartRequired="false" />
        <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" />
        <registryKey key="smartTomcat.resources.cacheMaxSize" description="The maximum size of the static resource cache in kilobytes." defaultValue="10240" restartRequired="false" />
    </extensions>

    <actions/>

</idea-plugin>
Download .txt
gitextract_inej82c3/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build.yml
│       ├── publish.yml
│       └── tagbuild.yml
├── .gitignore
├── .space.kts
├── CHANGELOG.md
├── LICENSE
├── README.md
├── build.gradle.kts
├── config-example.txt
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── poratu/
        │           └── idea/
        │               └── plugins/
        │                   └── tomcat/
        │                       ├── conf/
        │                       │   ├── ServerConsoleView.java
        │                       │   ├── TomcatCommandLineState.java
        │                       │   ├── TomcatLogFile.java
        │                       │   ├── TomcatRunConfiguration.java
        │                       │   ├── TomcatRunConfigurationType.java
        │                       │   ├── TomcatRunnerSettingsEditor.java
        │                       │   └── TomcatRunnerSettingsForm.java
        │                       ├── runner/
        │                       │   ├── TomcatDebugger.java
        │                       │   ├── TomcatRunConfigurationProducer.java
        │                       │   └── TomcatRunner.java
        │                       ├── setting/
        │                       │   ├── TomcatInfo.java
        │                       │   ├── TomcatInfoComponent.java
        │                       │   ├── TomcatInfoConfigurable.java
        │                       │   ├── TomcatServerManagerState.java
        │                       │   └── TomcatServersConfigurable.java
        │                       └── utils/
        │                           └── PluginUtils.java
        └── resources/
            └── META-INF/
                └── plugin.xml
Download .txt
SYMBOL INDEX (197 symbols across 16 files)

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/ServerConsoleView.java
  class ServerConsoleView (line 20) | public class ServerConsoleView extends ConsoleViewImpl {
    method ServerConsoleView (line 26) | public ServerConsoleView(TomcatRunConfiguration configuration) {
    method print (line 31) | @Override
    method parsePorts (line 73) | private boolean parsePorts(String s) {
    method buildServerUrls (line 97) | private List<Url> buildServerUrls() {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatCommandLineState.java
  class TomcatCommandLineState (line 53) | public class TomcatCommandLineState extends JavaCommandLineState {
    method TomcatCommandLineState (line 71) | protected TomcatCommandLineState(@NotNull ExecutionEnvironment environ...
    method TomcatCommandLineState (line 75) | protected TomcatCommandLineState(ExecutionEnvironment environment, Tom...
    method createCommandLine (line 80) | @Override
    method startProcess (line 90) | @Override
    method createJavaParameters (line 102) | @Override
    method createConsole (line 173) | @Nullable
    method updateServerConf (line 179) | private void updateServerConf(Path confPath, TomcatRunConfiguration cfg)
    method createContextFile (line 230) | private void createContextFile(String tomcatVersion, Module module, Pa...
    method createContextElement (line 256) | private Element createContextElement(Document doc, DocumentBuilder bui...
    method findContextFileInApp (line 267) | private Path findContextFileInApp() {
    method collectResources (line 286) | private void collectResources(Document doc, Element contextRoot, Modul...
    method createResourcesElementIfNecessary (line 331) | private Element createResourcesElementIfNecessary(Document doc, Elemen...
    method deleteTomcatWorkFiles (line 350) | private void deleteTomcatWorkFiles(Path tomcatHome) {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatLogFile.java
  class TomcatLogFile (line 10) | public class TomcatLogFile {
    method TomcatLogFile (line 22) | public TomcatLogFile(String id, String filename) {
    method TomcatLogFile (line 27) | public TomcatLogFile(String id, String filename, boolean enabled) {
    method getId (line 32) | public String getId() {
    method createLogFileOptions (line 36) | public LogFileOptions createLogFileOptions(PredefinedLogFile file, @Nu...
    method createPredefinedLogFile (line 41) | public PredefinedLogFile createPredefinedLogFile() {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfiguration.java
  class TomcatRunConfiguration (line 38) | public class TomcatRunConfiguration extends LocatableConfigurationBase<L...
    method createPredefinedLogFiles (line 48) | private static List<PredefinedLogFile> createPredefinedLogFiles() {
    method TomcatRunConfiguration (line 57) | protected TomcatRunConfiguration(@NotNull Project project, @NotNull Co...
    method getConfigurationEditor (line 69) | @NotNull
    method checkConfiguration (line 82) | @Override
    method onNewConfigurationCreated (line 105) | @Override
    method getModules (line 134) | @Override
    method getState (line 140) | @Nullable
    method getOptionsForPredefinedLogFile (line 146) | @Override
    method readExternal (line 157) | @Override
    method writeExternal (line 174) | @Override
    method addPredefinedTomcatLogFiles (line 183) | private void addPredefinedTomcatLogFiles() {
    method getModule (line 187) | @Nullable
    method setModule (line 192) | public void setModule(Module module) {
    method getTomcatInfo (line 196) | public TomcatInfo getTomcatInfo() {
    method setTomcatInfo (line 200) | public void setTomcatInfo(TomcatInfo tomcatInfo) {
    method getCatalinaBase (line 204) | public String getCatalinaBase() { return tomcatOptions.getCatalinaBase...
    method setCatalinaBase (line 205) | public void setCatalinaBase(String catalinaBase) { tomcatOptions.setCa...
    method getDocBase (line 206) | public String getDocBase() {
    method setDocBase (line 210) | public void setDocBase(String docBase) {
    method getContextPath (line 214) | public String getContextPath() {
    method setContextPath (line 218) | public void setContextPath(String contextPath) {
    method getPort (line 222) | public Integer getPort() {
    method setPort (line 226) | public void setPort(Integer port) {
    method getSslPort (line 230) | public Integer getSslPort() {
    method setSslPort (line 234) | public void setSslPort(Integer sslPort) {
    method getAdminPort (line 238) | public Integer getAdminPort() {
    method setAdminPort (line 242) | public void setAdminPort(Integer adminPort) {
    method getVmOptions (line 246) | public String getVmOptions() {
    method setVmOptions (line 250) | public void setVmOptions(String vmOptions) {
    method getEnvOptions (line 254) | public Map<String, String> getEnvOptions() {
    method setEnvOptions (line 258) | public void setEnvOptions(Map<String, String> envOptions) {
    method isPassParentEnvs (line 262) | public Boolean isPassParentEnvs() {
    method setPassParentEnvironmentVariables (line 266) | public void setPassParentEnvironmentVariables(Boolean passParentEnvs) {
    method getExtraClassPath (line 270) | public String getExtraClassPath() {
    method setExtraClassPath (line 274) | public void setExtraClassPath(String extraClassPath) {
    method clone (line 278) | @Override
    class TomcatRunConfigurationOptions (line 287) | private static class TomcatRunConfigurationOptions implements Serializ...
      method getTomcatInfo (line 301) | public TomcatInfo getTomcatInfo() {
      method setTomcatInfo (line 305) | public void setTomcatInfo(TomcatInfo tomcatInfo) {
      method getCatalinaBase (line 309) | @Nullable
      method setCatalinaBase (line 311) | public void setCatalinaBase(String catalinaBase) { this.catalinaBase...
      method getDocBase (line 313) | @Nullable
      method setDocBase (line 318) | public void setDocBase(String docBase) {
      method getContextPath (line 322) | public String getContextPath() {
      method setContextPath (line 326) | public void setContextPath(String contextPath) {
      method getPort (line 330) | public Integer getPort() {
      method setPort (line 334) | public void setPort(Integer port) {
      method getSslPort (line 338) | public Integer getSslPort() {
      method setSslPort (line 342) | public void setSslPort(Integer sslPort) {
      method getAdminPort (line 346) | public Integer getAdminPort() {
      method setAdminPort (line 350) | public void setAdminPort(Integer adminPort) {
      method getVmOptions (line 354) | public String getVmOptions() {
      method setVmOptions (line 358) | public void setVmOptions(String vmOptions) {
      method getEnvOptions (line 362) | public Map<String, String> getEnvOptions() {
      method setEnvOptions (line 366) | public void setEnvOptions(Map<String, String> envOptions) {
      method isPassParentEnvs (line 370) | public Boolean isPassParentEnvs() {
      method setPassParentEnvs (line 374) | public void setPassParentEnvs(Boolean passParentEnvs) {
      method getExtraClassPath (line 378) | public String getExtraClassPath() {
      method setExtraClassPath (line 382) | public void setExtraClassPath(String extraClassPath) {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfigurationType.java
  class TomcatRunConfigurationType (line 17) | public class TomcatRunConfigurationType extends SimpleConfigurationType {
    method TomcatRunConfigurationType (line 21) | protected TomcatRunConfigurationType() {
    method createTemplateConfiguration (line 28) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsEditor.java
  class TomcatRunnerSettingsEditor (line 10) | public class TomcatRunnerSettingsEditor extends SettingsEditor<TomcatRun...
    method TomcatRunnerSettingsEditor (line 14) | public TomcatRunnerSettingsEditor(Project project) {
    method resetEditorFrom (line 18) | @Override
    method applyEditorTo (line 23) | @Override
    method createEditor (line 28) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsForm.java
  class TomcatRunnerSettingsForm (line 41) | public class TomcatRunnerSettingsForm implements Disposable {
    method TomcatRunnerSettingsForm (line 71) | TomcatRunnerSettingsForm(Project project) {
    method createTomcatField (line 86) | private void createTomcatField() {
    method createClasspathField (line 93) | private void createClasspathField() {
    method createPortField (line 102) | private void createPortField() {
    method createAdminPortField (line 127) | private void createAdminPortField() {
    method initCatalinaBaseDirectory (line 139) | private void initCatalinaBaseDirectory() {
    method initDeploymentDirectory (line 150) | private void initDeploymentDirectory() {
    method buildForm (line 171) | private void buildForm() {
    method getMainPanel (line 188) | public JPanel getMainPanel() {
    method resetFrom (line 192) | public void resetFrom(TomcatRunConfiguration configuration) {
    method applyTo (line 216) | public void applyTo(TomcatRunConfiguration configuration) throws Confi...
    method dispose (line 235) | @Override
    class TomcatComboBox (line 240) | private static class TomcatComboBox extends JComboBox<TomcatInfo> {
      method TomcatComboBox (line 242) | TomcatComboBox() {
      method initBrowsableEditor (line 252) | private void initBrowsableEditor() {
    class TomcatComboBoxEditor (line 260) | private static class TomcatComboBoxEditor extends BasicComboBoxEditor {
      method TomcatComboBoxEditor (line 265) | public TomcatComboBoxEditor(TomcatComboBox comboBox) {
      method createEditorComponent (line 269) | @Override
      method createBrowseExtension (line 290) | private ExtendableTextComponent.Extension createBrowseExtension() {
    class TomcatComboBoxTextComponentAccessor (line 302) | private static class TomcatComboBoxTextComponentAccessor implements Te...
      method getText (line 304) | @Override
      method setText (line 309) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatDebugger.java
  class TomcatDebugger (line 14) | public class TomcatDebugger extends GenericDebuggerRunner {
    method getRunnerId (line 17) | @Override
    method canRun (line 23) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunConfigurationProducer.java
  class TomcatRunConfigurationProducer (line 27) | public class TomcatRunConfigurationProducer extends LazyRunConfiguration...
    method getConfigurationFactory (line 28) | @NotNull
    method setupConfigurationFromContext (line 34) | @Override
    method isPreferredConfiguration (line 68) | @Override
    method isConfigurationFromContext (line 73) | @Override
    method findWebRoots (line 83) | private List<VirtualFile> findWebRoots(@Nullable Location<?> location) {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunner.java
  class TomcatRunner (line 14) | public class TomcatRunner extends DefaultJavaProgramRunner {
    method getRunnerId (line 17) | @NotNull
    method canRun (line 23) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfo.java
  class TomcatInfo (line 11) | public class TomcatInfo implements Serializable {
    method getName (line 16) | public String getName() {
    method setName (line 20) | public void setName(String name) {
    method getVersion (line 24) | public String getVersion() {
    method setVersion (line 28) | public void setVersion(String version) {
    method getPath (line 32) | public String getPath() {
    method setPath (line 36) | public void setPath(String path) {
    method equals (line 40) | @Override
    method hashCode (line 48) | @Override
    method toString (line 53) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoComponent.java
  class TomcatInfoComponent (line 11) | public class TomcatInfoComponent implements Disposable {
    method TomcatInfoComponent (line 15) | public TomcatInfoComponent(TomcatInfo tomcatInfo) {
    method getMainPanel (line 27) | public JComponent getMainPanel() {
    method dispose (line 31) | @Override

FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoConfigurable.java
  class TomcatInfoConfigurable (line 10) | public class TomcatInfoConfigurable extends NamedConfigurable<TomcatInfo> {
    method TomcatInfoConfigurable (line 16) | public TomcatInfoConfigurable(TomcatInfo tomcatInfo, Runnable treeUpda...
    method setDisplayName (line 24) | @Override
    method getEditableObject (line 29) | @Override
    method getBannerSlogan (line 34) | @Override
    method createOptionsPanel (line 39) | @Override
    method getDisplayName (line 44) | @Override
    method checkName (line 49) | @Override
    method isModified (line 58) | @Override
    method apply (line 63) | @Override
  type TomcatNameValidator (line 69) | @FunctionalInterface
    method validate (line 71) | void validate(T t) throws ConfigurationException;

FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServerManagerState.java
  class TomcatServerManagerState (line 33) | @State(name = "ServerConfiguration", storages = @Storage("smart.tomcat.x...
    method getInstance (line 39) | public static TomcatServerManagerState getInstance() {
    method getTomcatInfos (line 43) | @NotNull
    method getState (line 48) | @Nullable
    method loadState (line 54) | @Override
    method createTomcatInfo (line 59) | public static Optional<TomcatInfo> createTomcatInfo(String tomcatHome) {
    method createTomcatInfo (line 63) | public static Optional<TomcatInfo> createTomcatInfo(String tomcatHome,...
    method generateTomcatName (line 92) | private static String generateTomcatName(String name) {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServersConfigurable.java
  class TomcatServersConfigurable (line 22) | public class TomcatServersConfigurable extends MasterDetailsComponent {
    method getDisplayName (line 24) | @Override
    method getHelpTopic (line 29) | @Override
    method TomcatServersConfigurable (line 34) | public TomcatServersConfigurable() {
    method createActions (line 38) | @Override
    method isModified (line 47) | @Override
    method reset (line 58) | @Override
    method apply (line 69) | @Override
    method wasObjectStored (line 82) | @Override
    method addNode (line 88) | private void addNode(TomcatInfo tomcatInfo, boolean selectInTree) {
    method validateName (line 98) | private void validateName(String name) throws ConfigurationException {
    class AddTomcatAction (line 107) | private class AddTomcatAction extends DumbAwareAction {
      method AddTomcatAction (line 108) | public AddTomcatAction() {
      method actionPerformed (line 113) | @Override
      method createUniqueName (line 118) | private String createUniqueName(String preferredName) {

FILE: src/main/java/com/poratu/idea/plugins/tomcat/utils/PluginUtils.java
  class PluginUtils (line 54) | public final class PluginUtils {
    method PluginUtils (line 58) | private PluginUtils() {
    method generateSequentName (line 68) | public static String generateSequentName(List<String> existingNames, S...
    method chooseTomcat (line 87) | public static void chooseTomcat(Consumer<TomcatInfo> callback) {
    method chooseTomcat (line 91) | public static void chooseTomcat(UnaryOperator<String> nameGenerator, C...
    method defaultCatalinaBase (line 102) | @Nullable
    method getCatalinaBase (line 124) | @Nullable
    method getTomcatLogsDirPath (line 134) | public static Path getTomcatLogsDirPath(TomcatRunConfiguration configu...
    method createDocumentBuilder (line 142) | @SuppressWarnings("HttpUrlsUsage")
    method createTransformer (line 161) | @SuppressWarnings("HttpUrlsUsage")
    method openTomcatConfiguration (line 179) | public static void openTomcatConfiguration() {
    method parsePort (line 183) | public static int parsePort(String text) throws ConfigurationException {
    method extractContextPath (line 199) | public static String extractContextPath(Module module) {
    method findWebRoots (line 205) | public static List<VirtualFile> findWebRoots(Module module) {
    method findWebRoots (line 238) | public static List<VirtualFile> findWebRoots(Project project) {
    method isUnderTestSources (line 249) | public static boolean isUnderTestSources(@Nullable Location<?> locatio...
    method getModules (line 265) | public static List<Module> getModules(Project project) {
    method guessModule (line 275) | public static @Nullable Module guessModule(Project project) {
    method findContainingModule (line 300) | public static @Nullable Module findContainingModule(@Nullable String f...
    method isEmptyFolder (line 321) | public static boolean isEmptyFolder(Path path) throws IOException {
Condensed preview — 32 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (127K chars).
[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 331,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: yuezk\n\n---\n\n**Describe t"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 595,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your fea"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 445,
    "preview": "name: build\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n  workflow_dispatch:\n"
  },
  {
    "path": ".github/workflows/publish.yml",
    "chars": 417,
    "preview": "name: publish\n\non: [workflow_dispatch]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/chec"
  },
  {
    "path": ".github/workflows/tagbuild.yml",
    "chars": 1298,
    "preview": "name: tagbuild\n\non:\n  push:\n    tags:\n      - 'release*'\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - "
  },
  {
    "path": ".gitignore",
    "chars": 297,
    "preview": "*.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, se"
  },
  {
    "path": ".space.kts",
    "chars": 239,
    "preview": "/**\n* JetBrains Space Automation\n* This Kotlin-script file lets you automate build activities\n* For more info, see https"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 2990,
    "preview": "<!-- Keep a Changelog guide -> https://keepachangelog.com -->\n# SmartTomcat Changelog\n\n## [4.8.0]\n\n### Changed\n- Require"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 3815,
    "preview": "# SmartTomcat\n<!-- Plugin description -->\nThe Tomcat plugin for Intellij IDEA\n\nThe SmartTomcat will auto load the Webapp"
  },
  {
    "path": "build.gradle.kts",
    "chars": 3055,
    "preview": "import org.jetbrains.changelog.Changelog\nimport org.jetbrains.changelog.markdownToHTML\nimport org.jetbrains.intellij.pla"
  },
  {
    "path": "config-example.txt",
    "chars": 264,
    "preview": "Config Example\n\nDeployment Directory:  project_name/web-module/src/main/webapp\nModules Root: project_name/web-module\nCon"
  },
  {
    "path": "gradlew",
    "chars": 8595,
    "preview": "#!/bin/sh\n\n#\n# Copyright © 2015 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "gradlew.bat",
    "chars": 2896,
    "preview": "@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 (th"
  },
  {
    "path": "settings.gradle.kts",
    "chars": 322,
    "preview": "rootProject.name = \"SmartTomcat\"\n//systemProp.system=systemValue\n\n\npluginManagement {\n    repositories {\n        mavenCe"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/ServerConsoleView.java",
    "chars": 4002,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.execution.impl.ConsoleViewImpl;\nimport com.intellij.ex"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatCommandLineState.java",
    "chars": 16379,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.debugger.settings.DebuggerSettings;\nimport com.intelli"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatLogFile.java",
    "chars": 1512,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.execution.configurations.LogFileOptions;\nimport com.in"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfiguration.java",
    "chars": 12675,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.configurationStore.XmlSerializer;\nimport com.intellij."
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunConfigurationType.java",
    "chars": 1080,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.execution.configurations.RunConfiguration;\nimport com."
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsEditor.java",
    "chars": 950,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.openapi.options.ConfigurationException;\nimport com.int"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/conf/TomcatRunnerSettingsForm.java",
    "chars": 15054,
    "preview": "package com.poratu.idea.plugins.tomcat.conf;\n\nimport com.intellij.application.options.ModulesComboBox;\nimport com.intell"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatDebugger.java",
    "chars": 851,
    "preview": "package com.poratu.idea.plugins.tomcat.runner;\n\nimport com.intellij.debugger.impl.GenericDebuggerRunner;\nimport com.inte"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunConfigurationProducer.java",
    "chars": 3824,
    "preview": "package com.poratu.idea.plugins.tomcat.runner;\n\nimport com.intellij.execution.Location;\nimport com.intellij.execution.ac"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/runner/TomcatRunner.java",
    "chars": 856,
    "preview": "package com.poratu.idea.plugins.tomcat.runner;\n\nimport com.intellij.execution.configurations.RunProfile;\nimport com.inte"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfo.java",
    "chars": 1212,
    "preview": "package com.poratu.idea.plugins.tomcat.setting;\n\nimport java.io.Serializable;\nimport java.util.Objects;\n\n/**\n * Author :"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoComponent.java",
    "chars": 1081,
    "preview": "package com.poratu.idea.plugins.tomcat.setting;\n\nimport com.intellij.openapi.Disposable;\nimport com.intellij.ui.componen"
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatInfoConfigurable.java",
    "chars": 1939,
    "preview": "package com.poratu.idea.plugins.tomcat.setting;\n\nimport com.intellij.openapi.options.ConfigurationException;\nimport com."
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServerManagerState.java",
    "chars": 3654,
    "preview": "package com.poratu.idea.plugins.tomcat.setting;\n\nimport com.intellij.openapi.application.ApplicationManager;\nimport com."
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/setting/TomcatServersConfigurable.java",
    "chars": 4398,
    "preview": "package com.poratu.idea.plugins.tomcat.setting;\n\nimport com.intellij.openapi.actionSystem.AnAction;\nimport com.intellij."
  },
  {
    "path": "src/main/java/com/poratu/idea/plugins/tomcat/utils/PluginUtils.java",
    "chars": 12258,
    "preview": "package com.poratu.idea.plugins.tomcat.utils;\n\nimport com.intellij.execution.Location;\nimport com.intellij.openapi.fileC"
  },
  {
    "path": "src/main/resources/META-INF/plugin.xml",
    "chars": 1918,
    "preview": "<idea-plugin>\n    <id>com.poratu.idea.plugins.tomcat</id>\n    <name>Smart Tomcat</name>\n    <vendor email=\"zengkid@msn.c"
  }
]

About this extraction

This page contains the full source code of the zengkid/SmartTomcat GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 32 files (117.7 KB), approximately 27.0k tokens, and a symbol index with 197 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!