├── .github └── workflows │ └── build.yaml ├── .gitignore ├── LICENSE.md ├── README.md ├── VERSION ├── build.gradle.kts ├── gradle.properties_sample ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample_projects ├── apply_from │ ├── build.gradle │ ├── gradle │ │ └── exec.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── build.gradle ├── env_vars │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── jacoco │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── java_toolchains │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── long_classpath │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── redirect_output │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── gradle │ │ └── example │ │ └── Main.java ├── redirect_output_and_error │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── settings.gradle ├── shell_script │ ├── build.gradle │ └── src │ │ └── main │ │ └── bash │ │ └── com │ │ └── github │ │ └── psxpaul │ │ ├── example-win │ │ ├── Main.bat │ │ └── SubProcess.bat │ │ └── example │ │ ├── Main.sh │ │ └── SubProcess.sh ├── simple │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── spring_boot │ ├── build.gradle │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── psxpaul │ │ │ └── example │ │ │ └── Main.java │ │ └── test │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── MainTest.java ├── spring_boot_with_dependency │ ├── build.gradle │ └── src │ │ └── main │ │ ├── bash │ │ └── com │ │ │ └── github │ │ │ └── psxpaul │ │ │ └── example │ │ │ └── Main.sh │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java ├── wait_output │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── psxpaul │ │ └── example │ │ └── Main.java └── war │ ├── build.gradle │ └── src │ ├── main │ └── webapp │ │ ├── WEB-INF │ │ └── web.xml │ │ └── index.jsp │ └── test │ └── java │ └── com │ └── github │ └── psxpaul │ └── example │ └── MainTest.java ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── github │ │ └── psxpaul │ │ ├── ExecForkPlugin.kt │ │ ├── ForkTaskTerminationService.kt │ │ ├── stream │ │ ├── InputStreamPipe.kt │ │ └── OutputStreamLogger.kt │ │ ├── task │ │ ├── AbstractExecFork.kt │ │ ├── ExecFork.kt │ │ ├── ExecJoin.kt │ │ └── JavaExecFork.kt │ │ └── util │ │ ├── PortUtils.kt │ │ └── ThrowableUtils.kt └── resources │ └── META-INF │ └── gradle-plugins │ └── gradle-execfork-plugin.properties └── test └── kotlin └── com └── github └── psxpaul ├── ExecForkPluginTest.kt ├── stream └── InputStreamPipeTest.kt ├── task └── ExecJoinTest.kt └── util └── PortUtilsTest.kt /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: [push, pull_request] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v3 8 | - name: Set up JDK 19 9 | uses: actions/setup-java@v3 10 | with: 11 | java-version: '19' 12 | distribution: 'adopt' 13 | - name: Validate Gradle wrapper 14 | uses: gradle/wrapper-validation-action@v1.0.4 15 | - name: Build with Gradle 16 | uses: gradle/gradle-build-action@v2.3.1 17 | with: 18 | arguments: build 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /sample_projects/*/build/ 3 | /sample_projects/build/ 4 | /plugin/build/ 5 | gradle.properties 6 | .gradle 7 | .classpath 8 | .project 9 | .settings 10 | .idea 11 | *.iml 12 | *.ipr 13 | *.iws 14 | *.swp 15 | .DS_Store 16 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gradle-execfork-plugin 2 | 3 | Gradle plugin for running background processes during a build. Both standard executables and java classes are supported. 4 | 5 | ## Usage 6 | For running a standard executable: 7 | 8 | ```groovy 9 | plugins { 10 | id 'com.github.psxpaul.execfork' version '0.2.0' 11 | } 12 | 13 | task startDaemon(type: com.github.psxpaul.task.ExecFork) { 14 | executable = './MainScript.sh' 15 | args = [ '-d', '/foo/bar/data', '-v', '-l', '3' ] 16 | workingDir = "$projectDir/src/main/bash" 17 | standardOutput = "$buildDir/daemon.log" 18 | errorOutput = "$buildDir/daemon-error.log" 19 | stopAfter = verify 20 | waitForPort = 8080 21 | waitForOutput = 'has started' 22 | environment = ['JAVA_HOME': "$buildDir/java", 'USER_HOME': "$buildDir/userhome"] 23 | } 24 | ``` 25 | 26 | For running a java main class: 27 | 28 | ```groovy 29 | plugins { 30 | id 'com.github.psxpaul.execfork' version '0.2.0' 31 | } 32 | 33 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork) { 34 | classpath = sourceSets.main.runtimeClasspath 35 | main = 'com.sample.application.MainApp' 36 | args = [ '-d', '/foo/bar/data', '-v', '-l', '3' ] 37 | jvmArgs = [ '-Xmx500m', '-Djava.awt.headless=true' ] 38 | workingDir = "$buildDir/server" 39 | standardOutput = "$buildDir/daemon.log" 40 | errorOutput = "$buildDir/daemon-error.log" 41 | stopAfter = verify 42 | waitForPort = 8443 43 | waitForOutput = 'has started' 44 | environment 'JAVA_HOME', "$buildDir/java" 45 | } 46 | ``` 47 | 48 | ### Supported Properties 49 | #### ExecFork: 50 | 51 | Name | Type | Description 52 | --- | --- | --- 53 | workingDir | String | *Optional.* The path of the working directory to run the executable from. This is treated as a relative path, so specifying an absolute path should be preferred. Default: `project.projectDir.absolutePath` 54 | args | List | *Optional.* A list of arguments to give to the executable. 55 | standardOutput | String | *Optional.* The path of the file to write standard output to. If none is specified, process output is written to gradle's console output. 56 | errorOutput | String | *Optional.* The path of the file to write error output to. If none is specified, the error output is directed to the same destination as the standard output. 57 | waitForPort | Int | *Optional.* A port number to watch for to be open. Until opened, the task will block. If none is specified, the task will return immediately after launching the process. 58 | waitForOutput | String | *Optional.* A string to look for in standardOutput. The task will block until this pattern appeared or the timeout is reached. If not specified, the task will return immediately after launching the process. 59 | timeout | Long | *Optional.* The maximum number of seconds associated with the waitForPort or waitForOutput task. Default: `60` 60 | stopAfter | org.gradle.api.Task | *Optional.* A task that, when finished, will cause the process to stop. If none is specified, the process will stop at the very end of a build (whether successful or not). 61 | executable | String | *Required.* The path to the executable. 62 | environment | Two Strings OR one Map | *Optional.* Environment variables to launch the executable with. You can either assign a Map with the '=' operator, or pass 2 Strings as key/value to the function. Note that multiple calls to this function are supported. 63 | forceKill | Boolean | *Optional.* Kills the process foricbly. Forcible process destruction is defined as the immediate termination of a process, whereas normal termination allows the process to shut down cleanly. 64 | killDescendants | Boolean | *Optional.* Kill all descendents of the started process. Default: `true` 65 | 66 | 67 | #### JavaExecFork: 68 | 69 | Name | Type | Description 70 | --- | --- | --- 71 | workingDir | String | *Optional.* The path of the working directory to run the executable from. This is treated as a relative path, so specifying an absolute path should be preferred. Default: `project.projectDir.absolutePath` 72 | args | List | *Optional.* A list of arguments to give to the executable. 73 | standardOutput | String | *Optional.* The path of the file to write standard output to. If none is specified, process output is written to gradle's console output. 74 | errorOutput | String | *Optional.* The path of the file to write error output to. If none is specified, the error output is directed to the same destination as the standard output. 75 | waitForPort | Int | *Optional.* A port number to watch for to be open. Until opened, the task will block. If none is specified, the task will return immediately after launching the process. 76 | waitForOutput | String | *Optional.* A string to look for in standardOutput. The task will block until this pattern appeared or the timeout is reached. If not specified, the task will return immediately after launching the process. 77 | timeout | Long | *Optional.* The maximum number of seconds associated with the waitForPort or waitForOutput task. Default: `60` 78 | stopAfter | org.gradle.api.Task | *Optional.* A task that, when finished, will cause the process to stop. If none is specified, the process will stop at the very end of a build (whether successful or not). 79 | classpath | org.gradle.api.file.FileCollection | *Required.* The classpath to use to launch the java main class. 80 | main | String | *Required.* The qualified name of the main java class to execute. 81 | jvmArgs | List | *Optional.* The list of arguments to give to the jvm when launching the java main class. 82 | environment | Two Strings OR one Map | *Optional.* Environment variables to launch the java main class with. You can either assign a Map with the '=' operator, or pass 2 Strings as key/value to the function. Note that multiple calls to this function are supported. 83 | forceKill | Boolean | *Optional.* Kills the process foricbly. Forcible process destruction is defined as the immediate termination of a process, whereas normal termination allows the process to shut down cleanly. 84 | killDescendants | Boolean | *Optional.* Kill all descendents of the started process. Default: `true` 85 | 86 | ## Compatibility 87 | 88 | Gradle Version | ExecFork version 89 | --- | --- 90 | < 4.10 | 0.1.8 91 | 4.10 - 5.2.x | 0.1.9 92 | 5.3.0 - 5.5.x | 0.1.11+ 93 | 5.6.0 - 6.6.x | 0.1.12 - 0.1.15 94 | 6.7.0+ | 0.2.+ -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.2.2 2 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.api.internal.classpath.ModuleRegistry 2 | import org.gradle.api.tasks.testing.logging.TestExceptionFormat 3 | import org.gradle.configurationcache.extensions.serviceOf 4 | 5 | allprojects { 6 | repositories { 7 | mavenLocal() 8 | mavenCentral() 9 | } 10 | } 11 | 12 | plugins { 13 | id("com.gradle.plugin-publish").version("1.0.0") 14 | kotlin("jvm") version "1.7.21" 15 | id("idea") 16 | id("maven-publish") 17 | id("java-gradle-plugin") 18 | } 19 | 20 | group = "com.github.psxpaul" 21 | version = File(rootDir, "VERSION").readText().trim() 22 | 23 | java { 24 | toolchain { 25 | targetCompatibility = JavaVersion.VERSION_1_8 26 | } 27 | } 28 | 29 | dependencies { 30 | implementation(gradleApi()) 31 | implementation("org.jetbrains.kotlin:kotlin-stdlib:1.7.21") 32 | implementation("org.jetbrains.kotlin:kotlin-reflect:1.7.21") 33 | 34 | testImplementation("junit:junit:4.12") 35 | testImplementation("org.hamcrest:hamcrest-all:1.3") 36 | // https://github.com/gradle/gradle/issues/16774 37 | testRuntimeOnly( 38 | files( 39 | serviceOf().getModule("gradle-tooling-api-builders") 40 | .classpath.asFiles 41 | ) 42 | ) 43 | } 44 | 45 | pluginBundle { 46 | website = "http://github.com/psxpaul" 47 | vcsUrl = "https://github.com/psxpaul/gradle-execfork-plugin" 48 | tags = listOf("java", "exec", "background", "process") 49 | } 50 | 51 | gradlePlugin { 52 | plugins { 53 | create("execForkPlugin") { 54 | id = "com.github.psxpaul.execfork" 55 | displayName = "Gradle Exec Fork Plugin" 56 | description = "Execute Java or shell processes in the background during a build" 57 | implementationClass = "com.github.psxpaul.ExecForkPlugin" 58 | } 59 | } 60 | } 61 | 62 | tasks { 63 | val sampleProjects by creating(GradleBuild::class) { 64 | buildFile = File("${project.rootDir}/sample_projects/build.gradle") 65 | tasks = listOf("clean", "build") 66 | } 67 | sampleProjects.dependsOn("publishToMavenLocal") 68 | "test" { finalizedBy(sampleProjects) } 69 | named("test") { 70 | testLogging.showStandardStreams = false 71 | testLogging.exceptionFormat = TestExceptionFormat.FULL 72 | } 73 | } 74 | 75 | val javadocJar by tasks.creating(Jar::class) { 76 | archiveClassifier.set("javadoc") 77 | from("javadoc") 78 | } 79 | 80 | val sourcesJar by tasks.creating(Jar::class) { 81 | archiveClassifier.set("sources") 82 | from(sourceSets["main"].allSource) 83 | } 84 | 85 | artifacts { 86 | add("archives", javadocJar) 87 | add("archives", sourcesJar) 88 | } 89 | -------------------------------------------------------------------------------- /gradle.properties_sample: -------------------------------------------------------------------------------- 1 | signing.keyId= 2 | signing.password= 3 | signing.secretKeyRingFile= 4 | ossrhUser= 5 | ossrhPassword= 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/psxpaul/gradle-execfork-plugin/8328794ae4b107576e67fa358bfa7ba3d69269df/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /sample_projects/apply_from/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply from: 'gradle/exec.gradle' 3 | 4 | task integrationTest(dependsOn: 'startDaemon') { 5 | doLast { 6 | sleep(500) 7 | println "I hope the daemon is running" 8 | } 9 | } 10 | build.dependsOn integrationTest 11 | -------------------------------------------------------------------------------- /sample_projects/apply_from/gradle/exec.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenLocal() 4 | mavenCentral() 5 | } 6 | dependencies { 7 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 8 | } 9 | } 10 | 11 | apply plugin: com.github.psxpaul.ExecForkPlugin 12 | 13 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 14 | classpath = sourceSets.main.runtimeClasspath 15 | main = 'com.github.psxpaul.example.Main' 16 | } 17 | startDaemon.mustRunAfter('jar', 'test') 18 | -------------------------------------------------------------------------------- /sample_projects/apply_from/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon is now running!"); 6 | while(true) { 7 | System.out.println("PING"); 8 | Thread.sleep(500); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /sample_projects/build.gradle: -------------------------------------------------------------------------------- 1 | subprojects { 2 | apply plugin: 'java' 3 | apply plugin: 'eclipse' 4 | apply plugin: 'idea' 5 | 6 | eclipse.project.name = "gradle-javaexecfork-plugin-sample-${project.name}" 7 | eclipse.classpath.downloadSources = true 8 | eclipse.classpath.downloadJavadoc = true 9 | eclipse.jdt.sourceCompatibility=1.8 10 | eclipse.classpath.defaultOutputDir = file('build/eclipse') 11 | 12 | ext.pluginVersion = new File(project.parent.projectDir, '../VERSION').text.trim() 13 | 14 | repositories { 15 | mavenLocal() 16 | mavenCentral() 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /sample_projects/env_vars/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task verify(dependsOn: 'startDaemon') { 15 | doLast { 16 | sleep(2000) 17 | assert file("$buildDir/daemon.log").text.contains("VAR_ONE = $buildDir/value_one") == true 18 | assert file("$buildDir/daemon.log").text.contains("VAR_TWO = $buildDir/value_two") == true 19 | assert file("$buildDir/daemon.log").text.contains("VAR_THREE = /tmp/value_three") == true 20 | } 21 | } 22 | 23 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 24 | classpath = sourceSets.main.runtimeClasspath 25 | main = 'com.github.psxpaul.example.Main' 26 | standardOutput = layout.buildDirectory.file("daemon.log") 27 | environment = ['VAR_TWO': "$buildDir/value_two", 'VAR_THREE': "/tmp/value_three"] 28 | environment 'VAR_ONE', "$buildDir/value_one" 29 | stopAfter = verify 30 | } 31 | startDaemon.mustRunAfter('jar', 'test') 32 | 33 | build.dependsOn verify 34 | -------------------------------------------------------------------------------- /sample_projects/env_vars/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon is now running!"); 6 | 7 | System.out.println("VAR_ONE = " + System.getenv("VAR_ONE")); 8 | System.out.println("VAR_TWO = " + System.getenv("VAR_TWO")); 9 | System.out.println("VAR_THREE = " + System.getenv("VAR_THREE")); 10 | 11 | while(true) { 12 | System.out.println("PING"); 13 | Thread.sleep(500); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /sample_projects/jacoco/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'jacoco' 3 | apply plugin: 'gradle-execfork-plugin' 4 | 5 | buildscript { 6 | repositories { 7 | mavenLocal() 8 | mavenCentral() 9 | } 10 | dependencies { 11 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 12 | } 13 | } 14 | 15 | task workerTask(dependsOn: 'startDaemon') { 16 | doLast { 17 | sleep(1000) 18 | assert file("$buildDir/daemon.log").text.contains("PING") == true 19 | } 20 | } 21 | 22 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 23 | classpath = sourceSets.main.runtimeClasspath 24 | main = 'com.github.psxpaul.example.Main' 25 | standardOutput = layout.buildDirectory.file("daemon.log") 26 | waitForOutput = 'PING' 27 | stopAfter = workerTask 28 | jacoco.applyTo(it) 29 | } 30 | startDaemon.mustRunAfter('jar', 'test') 31 | 32 | task daemonCodeCoverageReport(type: JacocoReport) { 33 | executionData startDaemon.jacoco.destinationFile 34 | classDirectories.setFrom(sourceSets.main.runtimeClasspath) 35 | sourceSets sourceSets.main 36 | reports.xml.required = true 37 | reports.html.required = false 38 | } 39 | daemonCodeCoverageReport.mustRunAfter stopDaemon 40 | workerTask.finalizedBy daemonCodeCoverageReport 41 | 42 | 43 | task verify(dependsOn: 'daemonCodeCoverageReport') { 44 | doLast { 45 | assert file("$buildDir/reports/jacoco/daemonCodeCoverageReport/daemonCodeCoverageReport.xml").text.contains(' "${'a' * 128}/${s}" } 28 | .toList() 29 | )) 30 | main = 'com.github.psxpaul.example.Main' 31 | args = [ '--someArg', "$buildDir/somePath" ] 32 | } 33 | startDaemon.mustRunAfter('jar', 'test') 34 | -------------------------------------------------------------------------------- /sample_projects/long_classpath/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon started with args: " + String.join(", ", args)); 6 | System.out.println("Daemon is now running!"); 7 | while(true) { 8 | System.out.println("PING"); 9 | Thread.sleep(500); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /sample_projects/redirect_output/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task verify(dependsOn: 'startDaemon') { 15 | doLast { 16 | sleep(250) 17 | assert file("$buildDir/daemon.log").text.contains("PING") == true 18 | assert file("$buildDir/daemon.log").text.contains("PONG") == true 19 | } 20 | } 21 | 22 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 23 | classpath = sourceSets.main.runtimeClasspath 24 | main = 'com.github.psxpaul.example.Main' 25 | standardOutput = layout.buildDirectory.file("daemon.log") 26 | stopAfter = verify 27 | } 28 | startDaemon.mustRunAfter('jar', 'test') 29 | 30 | build.dependsOn verify 31 | -------------------------------------------------------------------------------- /sample_projects/redirect_output/src/main/java/com/github/psxpaul/gradle/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon is now running!"); 6 | while(true) { 7 | System.out.println("PING"); 8 | System.err.println("PONG"); 9 | Thread.sleep(500); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /sample_projects/redirect_output_and_error/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task verify(dependsOn: 'startDaemon') { 15 | doLast { 16 | sleep(250) 17 | assert file("$buildDir/daemon.log").text.contains("PING") == true 18 | assert file("$buildDir/daemon.log").text.contains("PONG") == false 19 | assert file("$buildDir/daemon-error.log").text.contains("PING") == false 20 | assert file("$buildDir/daemon-error.log").text.contains("PONG") == true 21 | } 22 | } 23 | 24 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 25 | classpath = sourceSets.main.runtimeClasspath 26 | main = 'com.github.psxpaul.example.Main' 27 | standardOutput = layout.buildDirectory.file("daemon.log") 28 | errorOutput = layout.buildDirectory.file("daemon-error.log") 29 | stopAfter = verify 30 | } 31 | startDaemon.mustRunAfter('jar', 'test') 32 | 33 | build.dependsOn verify 34 | -------------------------------------------------------------------------------- /sample_projects/redirect_output_and_error/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon is now running!"); 6 | while(true) { 7 | System.out.println("PING"); 8 | System.err.println("PONG"); 9 | Thread.sleep(500); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /sample_projects/settings.gradle: -------------------------------------------------------------------------------- 1 | include 'apply_from' 2 | include 'env_vars' 3 | include 'jacoco' 4 | include 'java_toolchains' 5 | include 'long_classpath' 6 | include 'redirect_output' 7 | include 'redirect_output_and_error' 8 | include 'shell_script' 9 | include 'simple' 10 | include 'spring_boot' 11 | //include 'spring_boot_with_dependency' test this project manually :-( (run `gradle bootRun`, then press ctrl-c) 12 | include 'wait_output' 13 | include 'war' 14 | -------------------------------------------------------------------------------- /sample_projects/shell_script/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task verify(dependsOn: 'startDaemon') { 15 | doLast { 16 | sleep(2000) 17 | assert file("$buildDir/daemon.log").text.contains("PING") == true 18 | assert file("$buildDir/daemon.log").text.contains("PONG") == false 19 | assert file("$buildDir/daemon-error.log").text.contains("PING") == false 20 | assert file("$buildDir/daemon-error.log").text.contains("PONG") == true 21 | } 22 | } 23 | 24 | task postVerify(dependsOn: 'stopDaemon') { 25 | doLast { 26 | assert file("$buildDir/daemon.log").text.contains("PANG") == true 27 | def previousMatches = file("$buildDir/daemon.log").text.findAll("PANG").size() 28 | sleep(250) 29 | assert previousMatches == file("$buildDir/daemon.log").text.findAll("PANG").size() 30 | } 31 | } 32 | 33 | task startDaemon(type: com.github.psxpaul.task.ExecFork) { 34 | if(org.gradle.internal.os.OperatingSystem.current().isWindows()) { 35 | executable = layout.projectDirectory.file("src\\main\\bash\\com\\github\\psxpaul\\example-win\\Main.bat") 36 | } else { 37 | executable = layout.projectDirectory.file("src/main/bash/com/github/psxpaul/example/Main.sh") 38 | } 39 | workingDir = layout.projectDirectory.file("src/main/bash") 40 | standardOutput = layout.buildDirectory.file("daemon.log") 41 | errorOutput = layout.buildDirectory.file("daemon-error.log") 42 | stopAfter = verify 43 | } 44 | startDaemon.mustRunAfter('jar', 'test') 45 | 46 | build.dependsOn verify, postVerify 47 | -------------------------------------------------------------------------------- /sample_projects/shell_script/src/main/bash/com/github/psxpaul/example-win/Main.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | set DIR=%~dp0 4 | 5 | echo "starting subprocess from %DIR%" 6 | start /b cmd /c call "%DIR%/SubProcess.bat" 7 | 8 | :loop 9 | echo "PING" 10 | echo "PONG" 1>&2 11 | :: Use powershell as this does /not/ require streams attached and can sleep milliseconds. It is present on all supported Windows versions. 12 | powershell -command "sleep -Milliseconds 100" 13 | goto loop -------------------------------------------------------------------------------- /sample_projects/shell_script/src/main/bash/com/github/psxpaul/example-win/SubProcess.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | :loop 4 | echo "PANG" 5 | :: Use powershell as this does /not/ require streams attached and can sleep milliseconds. It is present on all supported Windows versions. 6 | powershell -command "sleep -Milliseconds 100" 7 | goto loop -------------------------------------------------------------------------------- /sample_projects/shell_script/src/main/bash/com/github/psxpaul/example/Main.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 4 | 5 | echo "starting subprocess from $DIR" 6 | bash -c ""${DIR}/SubProcess.sh"" & 7 | 8 | while true 9 | do 10 | echo "PING" 11 | echo "PONG" >&2 12 | sleep 0.1 13 | done 14 | -------------------------------------------------------------------------------- /sample_projects/shell_script/src/main/bash/com/github/psxpaul/example/SubProcess.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while true 4 | do 5 | echo "PANG" 6 | sleep 0.1 7 | done 8 | 9 | -------------------------------------------------------------------------------- /sample_projects/simple/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task integrationTest(dependsOn: 'startDaemon') { 15 | doLast { 16 | sleep(500) 17 | println "I hope the daemon is running" 18 | } 19 | } 20 | build.dependsOn integrationTest 21 | 22 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 23 | classpath = sourceSets.main.runtimeClasspath 24 | main = 'com.github.psxpaul.example.Main' 25 | args = [ '--someArg', "$buildDir/somePath" ] 26 | } 27 | startDaemon.mustRunAfter('jar', 'test') 28 | -------------------------------------------------------------------------------- /sample_projects/simple/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Daemon started with args: " + String.join(", ", args)); 6 | System.out.println("Daemon is now running!"); 7 | while(true) { 8 | System.out.println("PING"); 9 | Thread.sleep(500); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /sample_projects/spring_boot/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenLocal() 4 | mavenCentral() 5 | } 6 | dependencies { 7 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 8 | } 9 | } 10 | 11 | plugins { 12 | id 'org.springframework.boot' version '2.6.3' 13 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 14 | } 15 | 16 | apply plugin: 'gradle-execfork-plugin' 17 | 18 | dependencies { 19 | implementation 'org.springframework.boot:spring-boot-starter-web' 20 | testImplementation 'junit:junit' 21 | testImplementation 'org.hamcrest:hamcrest-library' 22 | testImplementation 'org.apache.httpcomponents:fluent-hc:4.5.2' 23 | } 24 | 25 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 26 | classpath = sourceSets.main.runtimeClasspath 27 | main = 'com.github.psxpaul.example.Main' 28 | jvmArgs = [ '-Dserver.port=9201' ] 29 | standardOutput = layout.buildDirectory.file("springboot.log") 30 | errorOutput = layout.buildDirectory.file("springboot-error.log") 31 | waitForPort = 9201 32 | timeout = 90 33 | stopAfter = test 34 | } 35 | startDaemon.mustRunAfter('compileTestJava', 'jar', 'bootJar') 36 | 37 | test.dependsOn startDaemon 38 | -------------------------------------------------------------------------------- /sample_projects/spring_boot/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @EnableAutoConfiguration 10 | public class Main { 11 | 12 | @RequestMapping("/") 13 | public String home() { 14 | return "PING"; 15 | } 16 | 17 | public static void main(String[] args) throws Exception { 18 | SpringApplication.run(Main.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sample_projects/spring_boot/src/test/java/com/github/psxpaul/example/MainTest.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | import static org.hamcrest.Matchers.equalTo; 4 | import static org.junit.Assert.assertThat; 5 | 6 | import org.apache.http.client.fluent.Request; 7 | import org.junit.Test; 8 | 9 | public class MainTest { 10 | 11 | @Test 12 | public void testResponse() throws Exception { 13 | String responseBody = Request.Get("http://localhost:9201/") 14 | .connectTimeout(1000) 15 | .socketTimeout(1000) 16 | .execute().returnContent().asString(); 17 | 18 | assertThat(responseBody, equalTo("PING")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sample_projects/spring_boot_with_dependency/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenLocal() 4 | mavenCentral() 5 | } 6 | dependencies { 7 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 8 | } 9 | } 10 | 11 | plugins { 12 | id 'org.springframework.boot' version '1.5.3.RELEASE' 13 | } 14 | 15 | repositories { 16 | mavenLocal() 17 | mavenCentral() 18 | } 19 | 20 | dependencies { 21 | compile 'org.springframework.boot:spring-boot-starter-web' 22 | testCompile 'junit:junit' 23 | testCompile 'org.hamcrest:hamcrest-library' 24 | testCompile 'org.apache.httpcomponents:fluent-hc:4.5.2' 25 | } 26 | 27 | task startDaemon(type: com.github.psxpaul.task.ExecFork) { 28 | commandLine = './com/github/psxpaul/example/Main.sh' 29 | workingDir = "$projectDir/src/main/bash" 30 | standardOutput = "$buildDir/daemon.log" 31 | errorOutput = "$buildDir/daemon-error.log" 32 | stopAfter = bootRun 33 | } 34 | 35 | bootRun.dependsOn startDaemon 36 | -------------------------------------------------------------------------------- /sample_projects/spring_boot_with_dependency/src/main/bash/com/github/psxpaul/example/Main.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | while true 4 | do 5 | echo "PING" 6 | echo "PONG" >&2 7 | sleep 0.1 8 | done 9 | -------------------------------------------------------------------------------- /sample_projects/spring_boot_with_dependency/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @EnableAutoConfiguration 10 | public class Main { 11 | 12 | @RequestMapping("/") 13 | public String home() { 14 | return "PING"; 15 | } 16 | 17 | public static void main(String[] args) throws Exception { 18 | SpringApplication.run(Main.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /sample_projects/wait_output/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'gradle-execfork-plugin' 3 | 4 | buildscript { 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 11 | } 12 | } 13 | 14 | task integrationTest(dependsOn: 'startDaemon') { 15 | def daemonFile = file("${buildDir}/daemon.out") 16 | doLast { 17 | def content = daemonFile.text 18 | assert content.contains('Important work being done!') 19 | assert content.contains('Daemon is up!') 20 | assert !content.contains('PING') 21 | Thread.sleep(1500) 22 | content = daemonFile.text 23 | assert content.contains('PING') 24 | } 25 | } 26 | build.dependsOn integrationTest 27 | 28 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: 'classes') { 29 | classpath = sourceSets.main.runtimeClasspath 30 | main = 'com.github.psxpaul.example.Main' 31 | standardOutput = layout.buildDirectory.file("daemon.out") 32 | waitForOutput = 'Daemon is up!' 33 | } 34 | startDaemon.mustRunAfter('jar', 'test') 35 | -------------------------------------------------------------------------------- /sample_projects/wait_output/src/main/java/com/github/psxpaul/example/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | public class Main { 4 | public static void main(String[] args) throws Exception { 5 | System.out.println("Starting the daemon!"); 6 | Thread.sleep(100); 7 | System.out.println("Important work being done!"); 8 | Thread.sleep(200); 9 | System.out.println("Daemon is up!"); 10 | Thread.sleep(100); 11 | while(true) { 12 | System.out.println("PING"); 13 | Thread.sleep(500); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /sample_projects/war/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'war' 3 | apply plugin: 'gradle-execfork-plugin' 4 | 5 | buildscript { 6 | repositories { 7 | mavenLocal() 8 | mavenCentral() 9 | } 10 | dependencies { 11 | classpath "com.github.psxpaul:gradle-execfork-plugin:$pluginVersion" 12 | } 13 | } 14 | 15 | configurations { 16 | jetty 17 | } 18 | 19 | dependencies { 20 | jetty 'org.eclipse.jetty:jetty-runner:9.3.14.v20161028' 21 | testImplementation 'junit:junit:4.12' 22 | testImplementation 'org.hamcrest:hamcrest-library:1.3' 23 | testImplementation 'org.apache.httpcomponents:fluent-hc:4.5.2' 24 | } 25 | 26 | task startDaemon(type: com.github.psxpaul.task.JavaExecFork, dependsOn: war) { 27 | classpath = configurations.jetty 28 | main = 'org.eclipse.jetty.runner.Runner' 29 | args = [ '--port', '9201', war.archivePath.absolutePath ] 30 | waitForPort = 9201 31 | timeout = 90 32 | stopAfter = test 33 | } 34 | startDaemon.mustRunAfter('compileTestJava') 35 | 36 | test.dependsOn startDaemon 37 | -------------------------------------------------------------------------------- /sample_projects/war/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /sample_projects/war/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | PING 2 | -------------------------------------------------------------------------------- /sample_projects/war/src/test/java/com/github/psxpaul/example/MainTest.java: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.example; 2 | 3 | import static org.hamcrest.Matchers.equalTo; 4 | import static org.junit.Assert.assertThat; 5 | 6 | import org.apache.http.client.fluent.Request; 7 | import org.junit.Test; 8 | 9 | public class MainTest { 10 | 11 | @Test 12 | public void testResponse() throws Exception { 13 | String responseBody = Request.Get("http://localhost:9201/") 14 | .connectTimeout(1000) 15 | .socketTimeout(1000) 16 | .execute().returnContent().asString(); 17 | 18 | assertThat(responseBody.trim(), equalTo("PING")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "gradle-execfork-plugin" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/ExecForkPlugin.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul 2 | 3 | import com.github.psxpaul.task.AbstractExecFork 4 | import org.gradle.api.GradleException 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | import org.gradle.api.provider.Provider 8 | import org.gradle.build.event.BuildEventsListenerRegistry 9 | import org.gradle.util.GradleVersion 10 | import javax.inject.Inject 11 | 12 | /** 13 | * Gradle plugin that will allow for 'com.github.psxpaul.ExecFork' and 'com.github.psxpaul.JavaExecFork' task 14 | * types. This plugin will make sure all of those tasks are stopped when a build completes, and optionally 15 | * create stop tasks for each one that specifies a 'stopAfter' task. 16 | * 17 | * Note: it is important to apply this plugin to your project for your ExecFork and JavaExecFork tasks to 18 | * work. E.g.: 19 | * apply plugin: 'gradle-execfork-plugin' 20 | */ 21 | class ExecForkPlugin @Inject constructor(private val buildEventsListenerRegistry: BuildEventsListenerRegistry) : Plugin { 22 | 23 | override fun apply(project: Project) { 24 | if (GradleVersion.current() < GradleVersion.version("6.7")) { 25 | throw GradleException("This version of the plugin is incompatible with Gradle < 6.7! Please use execfork version 0.1.15, or upgrade Gradle.") 26 | } 27 | 28 | // We have to create a separate service per project due to https://github.com/gradle/gradle/issues/17559 29 | val forkTaskTerminationServiceProvider: Provider = project.gradle.sharedServices.registerIfAbsent("fork-task-termination-"+project.path, ForkTaskTerminationService::class.java) {} 30 | 31 | project.tasks.withType(AbstractExecFork::class.java) { 32 | @Suppress("UNCHECKED_CAST", "PLATFORM_CLASS_MAPPED_TO_KOTLIN") 33 | it.forkTaskTerminationService.set(forkTaskTerminationServiceProvider as Provider) 34 | } 35 | 36 | buildEventsListenerRegistry.onTaskCompletion(forkTaskTerminationServiceProvider) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/ForkTaskTerminationService.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul 2 | 3 | import com.github.psxpaul.task.AbstractExecFork 4 | import org.gradle.api.services.BuildService 5 | import org.gradle.api.services.BuildServiceParameters 6 | import org.gradle.tooling.events.FinishEvent 7 | import org.gradle.tooling.events.OperationCompletionListener 8 | import org.slf4j.Logger 9 | import org.slf4j.LoggerFactory 10 | 11 | /** 12 | * Shared service that collects all started AbstractExecFork tasks and stops the daemons when the build finished 13 | * in case they have not already been stopped. 14 | */ 15 | abstract class ForkTaskTerminationService : BuildService, AutoCloseable, OperationCompletionListener { 16 | 17 | private val logger: Logger = LoggerFactory.getLogger(javaClass.simpleName) 18 | 19 | /** Holds references to all AbstractExecFork tasks that have been started during this build. */ 20 | private val forkTasks: MutableList = mutableListOf() 21 | 22 | fun addAbstractExecForkTask(task: AbstractExecFork) { 23 | forkTasks.add(task) 24 | } 25 | 26 | override fun onFinish(event: FinishEvent?) { 27 | // We are not actually interested in task execution events. 28 | // We just want to be notified in #close() when no more task execution events can arrive, which means build has finished. 29 | // We still need to implement the method to conform to the OperationCompletionListener interface. 30 | } 31 | 32 | /** 33 | * Will be called after the build finished. 34 | */ 35 | override fun close() { 36 | for (forkTask: AbstractExecFork in forkTasks) { 37 | try { 38 | forkTask.stop() 39 | } catch (e: InterruptedException) { 40 | logger.error("Error stopping daemon for {} task '{}'", forkTask.javaClass.simpleName, forkTask.name, e) 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/stream/InputStreamPipe.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.stream 2 | 3 | import org.gradle.api.GradleException 4 | import org.slf4j.Logger 5 | import org.slf4j.LoggerFactory 6 | import java.io.IOException 7 | import java.io.InputStream 8 | import java.io.OutputStream 9 | import java.util.* 10 | import java.util.concurrent.CountDownLatch 11 | import java.util.concurrent.TimeUnit 12 | 13 | /** 14 | * Object that will copy the inputStream to the outputStream. You can optionally call waitForPattern() 15 | * to block until the pattern is seen in the given stream 16 | * 17 | * @param inputStream the InputStream to copy to the outputFile 18 | * @param outputStream the outputStream to copy to 19 | * @param pattern the optional pattern to wait for when calling waitForPattern() 20 | */ 21 | class InputStreamPipe(private val inputStream: InputStream, private val outputStream: OutputStream, private val pattern: String?) : AutoCloseable { 22 | private val log: Logger = LoggerFactory.getLogger(InputStreamPipe::class.java) 23 | 24 | private val patternLength: Int = pattern?.toByteArray()?.size ?: 0 25 | private val patternLatch: CountDownLatch = CountDownLatch(if (pattern != null) 1 else 0) 26 | private val buffer: LinkedList = LinkedList() 27 | private val thread: Thread = Thread { 28 | 29 | var byte: Int = inputStream.safeRead() 30 | while (byte != -1) { 31 | outputStream.write(byte) 32 | outputStream.flush() 33 | 34 | if (patternLength == 0 || patternLatch.count == 0L) { 35 | log.debug("skipping pattern checking") 36 | } else if (buffer.size < patternLength - 1) { 37 | buffer.addLast(byte) 38 | } else { 39 | buffer.addLast(byte) 40 | val bufferStr = String(buffer.map(Int::toByte).toByteArray()) 41 | 42 | log.debug("checking if |${bufferStr.replace("\n", "\\n")}| equals |$pattern|") 43 | if (bufferStr == pattern) { 44 | patternLatch.countDown() 45 | } 46 | buffer.removeFirst() 47 | } 48 | 49 | byte = inputStream.safeRead() 50 | } 51 | close() 52 | } 53 | 54 | init { 55 | thread.start() 56 | } 57 | 58 | /** 59 | * Block until the pattern has been seen in the InputStream 60 | */ 61 | fun waitForPattern() { 62 | patternLatch.await() 63 | } 64 | 65 | /** 66 | * Block until the pattern has been seen in the InputStream 67 | * 68 | * @param timeout the maximum number of TimeUnits to wait 69 | * @param unit the unit of time to wait 70 | */ 71 | fun waitForPattern(timeout: Long, unit: TimeUnit) { 72 | if (!patternLatch.await(timeout, unit)) { 73 | throw GradleException("The waitForOutput pattern did not appear before timeout was reached.") 74 | } 75 | } 76 | 77 | /** 78 | * Close the outputFile 79 | */ 80 | override fun close() { 81 | log.debug("closing given outputstream") 82 | outputStream.close() 83 | } 84 | } 85 | 86 | fun InputStream.safeRead(): Int { 87 | return try { 88 | read() 89 | } catch (e: IOException) { 90 | if (e.message == "Stream closed") { 91 | -1 92 | } else { 93 | throw e 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/stream/OutputStreamLogger.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.stream 2 | 3 | import org.gradle.api.logging.Logger 4 | import java.io.OutputStream 5 | 6 | /** 7 | * This output stream logs all content written to it using the provided logger. 8 | */ 9 | class OutputStreamLogger(private val logger: Logger) : OutputStream() { 10 | 11 | var sb = StringBuilder() 12 | 13 | override fun write(b: Int) { 14 | val character = b.toChar() 15 | if (character == '\n') { 16 | logger.lifecycle(sb.toString()) 17 | sb = StringBuilder() 18 | } else 19 | sb.append(character) 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/task/AbstractExecFork.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.task 2 | 3 | import com.github.psxpaul.ForkTaskTerminationService 4 | import com.github.psxpaul.stream.InputStreamPipe 5 | import com.github.psxpaul.stream.OutputStreamLogger 6 | import com.github.psxpaul.util.waitForPortOpen 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.GradleException 9 | import org.gradle.api.Task 10 | import org.gradle.api.file.RegularFileProperty 11 | import org.gradle.api.model.ObjectFactory 12 | import org.gradle.api.provider.Property 13 | import org.gradle.api.tasks.* 14 | import org.gradle.process.ProcessForkOptions 15 | import java.io.File 16 | import java.io.FileOutputStream 17 | import java.io.OutputStream 18 | import java.util.concurrent.TimeUnit 19 | import java.util.stream.Stream 20 | import kotlin.concurrent.thread 21 | import kotlin.reflect.* 22 | import kotlin.reflect.full.* 23 | import kotlin.reflect.jvm.* 24 | 25 | /** 26 | * An abstract task that will launch an executable as a background process, optionally 27 | * waiting until a specific port is opened. The task will also stop the process if given 28 | * a stopAfter or joinTask 29 | * 30 | * @see ExecFork 31 | * @see JavaExecFork 32 | * @see ProcessForkOptions 33 | * 34 | * @param args the arguments to give the executable 35 | * @param standardOutput the name of the file to write the process's standard output to 36 | * @param errorOutput the name of the file to write the process's error output to 37 | * @param waitForPort if specified, block the task from completing until the given port is 38 | * open locally 39 | * @param timeout the length of time in seconds that the task will wait for the port to be 40 | * be opened, before failing 41 | * @param stopAfter if specified, this task will stop the running process after the stopAfter 42 | * task has been completed 43 | */ 44 | abstract class AbstractExecFork(objectFactory: ObjectFactory) : DefaultTask(), ProcessForkOptions { 45 | 46 | @Input 47 | abstract override fun getEnvironment(): MutableMap 48 | 49 | @Input 50 | abstract override fun getExecutable(): String? 51 | 52 | @Input 53 | var args: MutableList = mutableListOf() 54 | 55 | @InputDirectory 56 | abstract override fun getWorkingDir(): File 57 | 58 | @OutputFile 59 | @Optional 60 | val standardOutput: RegularFileProperty = objectFactory.fileProperty() 61 | 62 | @OutputFile 63 | @Optional 64 | val errorOutput: RegularFileProperty = objectFactory.fileProperty() 65 | 66 | @Input 67 | @Optional 68 | var waitForPort: Int? = null 69 | 70 | @Input 71 | @Optional 72 | var waitForOutput: String? = null 73 | 74 | @Input 75 | @Optional 76 | var waitForError: String? = null 77 | 78 | @Input 79 | var forceKill: Boolean = false 80 | 81 | @Input 82 | var killDescendants: Boolean = true 83 | 84 | @Internal 85 | var process: Process? = null 86 | 87 | @Input 88 | var timeout: Long = 60 89 | 90 | private val shutdownHook = thread(start = false) { stop() } 91 | 92 | @Internal 93 | var stopAfter: TaskProvider? = null 94 | set(stopAfterValue: TaskProvider?) { 95 | if (stopAfterValue == null) { 96 | return 97 | } 98 | if (field != null) { 99 | throw GradleException("Cannot reassign stopAfter! Was set to ${field!!.name} already when attempting to set to ${stopAfterValue.name}") 100 | } 101 | val joinTask = project.tasks.register(createNameFor(this), ExecJoin::class.java) { 102 | it.forkTask = this 103 | } 104 | logger.info("Adding {} as a finalizing task to {}", joinTask.name, stopAfterValue.name) 105 | stopAfterValue.configure { 106 | it.finalizedBy(joinTask) 107 | } 108 | field = stopAfterValue 109 | } 110 | 111 | // It should be Property but because of a bug in Gradle 112 | // we have to use a more generic type, see https://github.com/gradle/gradle/issues/17559 113 | // This can be reproduced in the spring_boot sample project 114 | @Internal 115 | @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") 116 | val forkTaskTerminationService: Property = objectFactory.property(Object::class.java) 117 | 118 | init { 119 | // The exec fork task should be executed in any case if not manually specified otherwise. 120 | // By default, this is the case as the task has only inputs defined, but e.g. jacoco attaches a jvm argument 121 | // provider, which in turn contributes an output property, which causes the task to be considered up-to-date. 122 | outputs.upToDateWhen { false } 123 | } 124 | 125 | @TaskAction 126 | open fun exec() { 127 | val processBuilder: ProcessBuilder = ProcessBuilder(getProcessArgs()) 128 | redirectStreams(processBuilder) 129 | 130 | val processWorkingDir: File = workingDir 131 | processWorkingDir.mkdirs() 132 | processBuilder.directory(processWorkingDir) 133 | 134 | environment.forEach { processBuilder.environment()[it.key] = it.value.toString() } 135 | 136 | logger.info("running process: {}", processBuilder.command().joinToString(separator = " ")) 137 | 138 | this.process = processBuilder.start() 139 | installPipesAndWait(this.process!!) 140 | 141 | val waitForPortVal: Int? = waitForPort 142 | if (waitForPortVal != null) 143 | waitForPortOpen(waitForPortVal, timeout, TimeUnit.SECONDS, process!!) 144 | 145 | Runtime.getRuntime().addShutdownHook(shutdownHook) 146 | (forkTaskTerminationService.get() as ForkTaskTerminationService).addAbstractExecForkTask(this) 147 | } 148 | 149 | @Input 150 | abstract fun getProcessArgs(): List? 151 | 152 | private fun installPipesAndWait(process: Process) { 153 | val processOut: OutputStream = if (standardOutput.isPresent) { 154 | standardOutput.asFile.get().parentFile.mkdirs() 155 | FileOutputStream(standardOutput.asFile.get()) 156 | } else OutputStreamLogger(logger) 157 | val outPipe: InputStreamPipe = InputStreamPipe(process.inputStream, processOut, waitForOutput) 158 | if (errorOutput.isPresent) { 159 | errorOutput.asFile.get().parentFile.mkdirs() 160 | 161 | val errPipe: InputStreamPipe = InputStreamPipe(process.errorStream, FileOutputStream(errorOutput.asFile.get()), waitForError) 162 | errPipe.waitForPattern(timeout, TimeUnit.SECONDS) 163 | } 164 | outPipe.waitForPattern(timeout, TimeUnit.SECONDS) 165 | } 166 | 167 | private fun redirectStreams(processBuilder: ProcessBuilder) { 168 | if (!errorOutput.isPresent) { 169 | processBuilder.redirectErrorStream(true) 170 | } 171 | } 172 | 173 | /** 174 | * Stop the process that this task has spawned 175 | */ 176 | fun stop() { 177 | try { 178 | if (killDescendants) { 179 | stopDescendants() 180 | } 181 | } catch (e: Exception) { 182 | logger.warn("Failed to stop descendants", e) 183 | } 184 | 185 | stopRootProcess() 186 | Runtime.getRuntime().removeShutdownHook(shutdownHook) 187 | } 188 | 189 | private fun stopRootProcess() { 190 | val process: Process = process ?: return 191 | if (process.isAlive && !forceKill) { 192 | process.destroy() 193 | process.waitFor(15, TimeUnit.SECONDS) 194 | } 195 | if (process.isAlive) { 196 | process.destroyForcibly().waitFor(15, TimeUnit.SECONDS) 197 | } 198 | } 199 | 200 | private fun stopDescendants() { 201 | val process: Process = process ?: return 202 | if (!process.isAlive) { 203 | return 204 | } 205 | 206 | val toHandle = process::class.memberFunctions.singleOrNull { it.name == "toHandle" } 207 | if (toHandle == null) { 208 | logger.error("Could not load Process.toHandle(). The killDescendants flag requires Java 9+. Please set killDescendants=false, or upgrade to Java 9+.") 209 | return // not supported, pre java 9? 210 | } 211 | 212 | toHandle.isAccessible = true 213 | val handle = toHandle.call(process) 214 | if (handle == null) { 215 | logger.warn("Could not get process handle. Process descendants may not be stopped.") 216 | return 217 | } 218 | val descendants = handle::class.memberFunctions.single { it.name == "descendants" } 219 | descendants.isAccessible = true 220 | val children: Stream<*> = descendants.call(handle) as Stream<*>; 221 | val destroy = handle::class.memberFunctions.single { it.name == if (forceKill) "destroyForcibly" else "destroy" } 222 | destroy.isAccessible = true 223 | 224 | children.forEach { 225 | destroy.call(it) 226 | } 227 | } 228 | 229 | @Deprecated("Use a task provider instead of a concrete Task instance", ReplaceWith("stopAfter = tasks.named(':myTask')")) 230 | fun setStopAfter(task: Task) { 231 | stopAfter = task.project.tasks.named(task.name) 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/task/ExecFork.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.task 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.tasks.Input 5 | import org.gradle.process.ProcessForkOptions 6 | import org.gradle.process.internal.JavaForkOptionsFactory 7 | import javax.inject.Inject 8 | 9 | /** 10 | * A task that will run a command in a separate process, optionally 11 | * writing stdout and stderr to disk, and waiting for a specified 12 | * port to be open. 13 | * 14 | * @see AbstractExecFork 15 | * @see ProcessForkOptions for all available configuration options 16 | */ 17 | open class ExecFork @Inject constructor(forkOptionsFactory: JavaForkOptionsFactory, objectFactory: ObjectFactory) : AbstractExecFork(objectFactory), 18 | ProcessForkOptions by forkOptionsFactory.newJavaForkOptions() { 19 | 20 | /** 21 | * The path to the executable to run 22 | * @deprecated Use #executable instead 23 | */ 24 | @get:Input 25 | var commandLine: String? 26 | get() = executable 27 | set(value) { 28 | executable = value 29 | } 30 | 31 | override fun getProcessArgs(): List? { 32 | val processArgs: MutableList = mutableListOf() 33 | processArgs.add(executable!!) 34 | processArgs.addAll(args.map(CharSequence::toString)) 35 | return processArgs 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/task/ExecJoin.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.task 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.tasks.Internal 5 | import org.gradle.api.tasks.TaskAction 6 | import org.slf4j.Logger 7 | import org.slf4j.LoggerFactory 8 | 9 | /** 10 | * A gradle task that is linked to an AbstractExecTask, that will 11 | * call AbstractExecTask.stop() when this task is run. You should 12 | * not need to create these tasks, as the ExecForkPlugin will create 13 | * them for any AbstractExecTask that has a stopAfter task specified. 14 | * 15 | * @param forkTask the task to call stop() on 16 | */ 17 | open class ExecJoin : DefaultTask() { 18 | private val log: Logger = LoggerFactory.getLogger(ExecJoin::class.java) 19 | 20 | @Internal 21 | var forkTask: AbstractExecFork? = null 22 | 23 | @TaskAction 24 | fun exec() { 25 | log.info("Stopping {} task {}", forkTask!!.javaClass.simpleName, forkTask!!.name) 26 | forkTask!!.stop() 27 | } 28 | } 29 | 30 | /** 31 | * Create a human-readable name for an ExecJoin task, given a corresponding 32 | * AbstractExecFork task. 33 | * 34 | * @return a human-readable string for an ExecJoin task 35 | * e.g. 36 | * startFoo -> stopFoo 37 | * runJob -> stopJob 38 | * execPoodleDaemon -> stopPoodleDaemon 39 | */ 40 | fun createNameFor(startTask: AbstractExecFork):String { 41 | val taskName:String = startTask.name 42 | 43 | if (hasWord(taskName, "start")) return replaceWord(taskName, "start", "stop") 44 | if (hasWord(taskName, "Start")) return replaceWord(taskName, "Start", "Stop") 45 | if (hasWord(taskName, "START")) return replaceWord(taskName, "START", "STOP") 46 | 47 | if (hasWord(taskName, "run")) return replaceWord(taskName, "run", "stop") 48 | if (hasWord(taskName, "Run")) return replaceWord(taskName, "Run", "Stop") 49 | if (hasWord(taskName, "RUN")) return replaceWord(taskName, "RUN", "STOP") 50 | 51 | if (hasWord(taskName, "exec")) return replaceWord(taskName, "exec", "stop") 52 | if (hasWord(taskName, "Exec")) return replaceWord(taskName, "Exec", "Stop") 53 | if (hasWord(taskName, "EXEC")) return replaceWord(taskName, "EXEC", "STOP") 54 | 55 | return taskName + "_stop" 56 | } 57 | 58 | private fun hasWord(input:String, pattern:String):Boolean { 59 | return input.startsWith(pattern) || input.endsWith(pattern) 60 | } 61 | 62 | private fun replaceWord(input:String, pattern:String, replacement:String):String { 63 | return input.replace(Regex("^$pattern"), replacement).replace(Regex("$pattern$"), replacement) 64 | } 65 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/task/JavaExecFork.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.task 2 | 3 | import org.gradle.api.file.FileCollection 4 | import org.gradle.api.model.ObjectFactory 5 | import org.gradle.api.provider.Property 6 | import org.gradle.api.tasks.Input 7 | import org.gradle.api.tasks.InputFiles 8 | import org.gradle.api.tasks.Nested 9 | import org.gradle.api.tasks.Optional 10 | import org.gradle.internal.jvm.Jvm 11 | import org.gradle.jvm.toolchain.JavaLauncher 12 | import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform 13 | import org.gradle.process.JavaForkOptions 14 | import org.gradle.process.internal.JavaForkOptionsFactory 15 | import java.io.File 16 | import java.io.FileOutputStream 17 | import java.net.URI 18 | import java.util.jar.Attributes 19 | import java.util.jar.JarOutputStream 20 | import java.util.jar.Manifest 21 | import java.util.stream.Collectors 22 | import java.util.zip.ZipEntry 23 | import javax.inject.Inject 24 | 25 | /** 26 | * A task that will run a java class in a separate process, optionally 27 | * writing stdout and stderr to disk, and waiting for a specified 28 | * port to be open. 29 | * 30 | * @see AbstractExecFork 31 | * 32 | * @param classpath the classpath to call java with 33 | * @param main the fully qualified name of the class to execute (e.g. 'com.foo.bar.MainExecutable') 34 | */ 35 | open class JavaExecFork @Inject constructor(forkOptionsFactory: JavaForkOptionsFactory, objectFactory: ObjectFactory) : 36 | AbstractExecFork(objectFactory), 37 | JavaForkOptions by forkOptionsFactory.newJavaForkOptions() { 38 | /** 39 | * Configures the java executable to be used to run the tests. 40 | */ 41 | @Nested 42 | @Optional 43 | val javaLauncher: Property = objectFactory.property(JavaLauncher::class.java) 44 | 45 | @InputFiles 46 | var classpath: FileCollection? = null 47 | 48 | @Input 49 | var main: String? = null 50 | 51 | override fun getProcessArgs(): List? { 52 | val processArgs: MutableList = mutableListOf() 53 | processArgs.add(getEffectiveExecutable()) 54 | processArgs.add("-cp") 55 | processArgs.add((bootstrapClasspath + classpath!!).asPath) 56 | processArgs.addAll(allJvmArgs) 57 | processArgs.add(main!!) 58 | processArgs.addAll(args.map(CharSequence::toString)) 59 | 60 | if (hasCommandLineExceedMaxLength(processArgs)) { 61 | processArgs[processArgs.indexOf("-cp") + 1] = 62 | writePathingJarFile(bootstrapClasspath + classpath!!).path 63 | } 64 | 65 | return processArgs 66 | } 67 | 68 | private fun writePathingJarFile(classPath: FileCollection): File { 69 | val pathingJarFile = File.createTempFile("gradle-javaexec-classpath", ".jar") 70 | FileOutputStream(pathingJarFile).use { fileOutputStream -> 71 | JarOutputStream(fileOutputStream, toManifest(classPath)).use { jarOutputStream -> 72 | jarOutputStream.putNextEntry(ZipEntry("META-INF/")) 73 | } 74 | } 75 | return pathingJarFile 76 | } 77 | 78 | private fun toManifest(classPath: FileCollection): Manifest { 79 | val manifest = Manifest() 80 | val attributes = manifest.mainAttributes 81 | attributes[Attributes.Name.MANIFEST_VERSION] = "1.0" 82 | attributes.putValue( 83 | "Class-Path", 84 | classPath.files.stream().map(File::toURI).map(URI::toString).collect(Collectors.joining(" ")) 85 | ) 86 | return manifest 87 | } 88 | 89 | private fun hasCommandLineExceedMaxLength(args: List): Boolean { 90 | // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx 91 | // Derived from MAX_ARG_STRLEN as per http://man7.org/linux/man-pages/man2/execve.2.html 92 | val maxCommandLineLength = if (DefaultNativePlatform.getCurrentOperatingSystem().isWindows()) 32767 else 131072 93 | return args.joinToString(" ").length > maxCommandLineLength 94 | } 95 | 96 | private fun getEffectiveExecutable(): String { 97 | if (javaLauncher.isPresent) { 98 | return javaLauncher.get().executablePath.toString() 99 | } 100 | return executable ?: Jvm.current().javaExecutable.absolutePath 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/util/PortUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.util 2 | 3 | import org.gradle.api.GradleException 4 | import java.net.* 5 | import java.util.concurrent.TimeUnit 6 | 7 | /** 8 | * Find a random port that is available to listen on 9 | * @return a port number that is available 10 | */ 11 | fun findOpenPort(): Int { 12 | ServerSocket(0).use { return it.localPort } 13 | } 14 | 15 | /** 16 | * Check if a given port is in use 17 | * @param port the port number to check 18 | * @return true if the port is open, false otherwise 19 | */ 20 | private fun isPortOpen(port: Int): Boolean { 21 | Socket().use { 22 | val inetAddress: InetAddress = InetAddress.getByName("127.0.0.1") 23 | val socketAddress: InetSocketAddress = InetSocketAddress(inetAddress, port) 24 | return try { 25 | it.connect(socketAddress) 26 | true 27 | } catch (e: ConnectException) { 28 | false 29 | } 30 | } 31 | } 32 | 33 | /** 34 | * Wait for a given amount of time for a port to be opened locally, by a given 35 | * process. This method will poll every 100 ms and try to connect to the port. If 36 | * the amount of time is reached and the port is not yet open, a GradleException 37 | * is thrown. If the given process terminates before the port is open, a 38 | * GradleException is thrown. 39 | * 40 | * @param port the port number to check 41 | * @param timeout the maximum number of TimeUnits to wait 42 | * @param unit the unit of time to wait 43 | * @param process the process to monitor for early termination 44 | * 45 | * @throws GradleException when the timeout has elapsed and the port is still 46 | * not open, OR the given process has terminated before the port is 47 | * opened (whichever occurs first) 48 | */ 49 | fun waitForPortOpen(port: Int, timeout: Long, unit: TimeUnit, process: Process) { 50 | val millisToWait: Long = unit.toMillis(timeout) 51 | val waitUntil: Long = System.currentTimeMillis() + millisToWait 52 | 53 | while (System.currentTimeMillis() < waitUntil) { 54 | Thread.sleep(100) 55 | if (!process.isAlive) throw GradleException("Process died before port $port was opened") 56 | if (isPortOpen(port)) return 57 | } 58 | 59 | throw GradleException("Timed out waiting for port $port to be opened") 60 | } 61 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/psxpaul/util/ThrowableUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.util 2 | 3 | /** 4 | * Loop through the causes of a Throwable, until the root 5 | * cause is found. 6 | * 7 | * @param t the Throwable to find nested causes in 8 | * @return the most-nestedest Throwable 9 | */ 10 | fun rootCauseOf(t: Throwable): Throwable { 11 | val cause: Throwable = t.cause ?: return t 12 | return rootCauseOf(cause) 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/gradle-execfork-plugin.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.github.psxpaul.ExecForkPlugin 2 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/psxpaul/ExecForkPluginTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul 2 | 3 | import com.github.psxpaul.task.AbstractExecFork 4 | import com.github.psxpaul.task.ExecJoin 5 | import com.github.psxpaul.task.JavaExecFork 6 | import org.gradle.api.Project 7 | import org.gradle.testfixtures.ProjectBuilder 8 | import org.hamcrest.Matchers.instanceOf 9 | import org.hamcrest.Matchers.sameInstance 10 | import org.junit.Assert.assertThat 11 | import org.junit.Test 12 | 13 | class ExecForkPluginTest { 14 | @Test 15 | fun shouldCreateStopTasks() { 16 | val project: Project = ProjectBuilder.builder().build() 17 | project.pluginManager.apply("gradle-execfork-plugin") 18 | 19 | val someTask = project.tasks.register("someTask") 20 | 21 | val opts = hashMapOf("type" to JavaExecFork::class.java) 22 | val startTestTask = project.task(opts, "startTestTask") as JavaExecFork 23 | startTestTask.stopAfter = someTask 24 | 25 | val startTask = project.tasks.getByName("startTestTask") 26 | assertThat(startTask, instanceOf(JavaExecFork::class.java)) 27 | val forkTask = startTask as AbstractExecFork 28 | 29 | val stopTask = project.tasks.getByName("stopTestTask") 30 | assertThat(stopTask, instanceOf(ExecJoin::class.java)) 31 | 32 | val joinTask = stopTask as ExecJoin 33 | assertThat(joinTask.forkTask, sameInstance(forkTask)) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/psxpaul/stream/InputStreamPipeTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.stream 2 | 3 | import org.hamcrest.Matchers.contains 4 | import org.hamcrest.Matchers.`is` 5 | import org.junit.After 6 | import org.junit.Assert.assertThat 7 | import org.junit.Test 8 | import java.io.* 9 | import java.util.concurrent.CountDownLatch 10 | 11 | class InputStreamPipeTest { 12 | val outputStream: PipedOutputStream = PipedOutputStream() 13 | val outputBuffer: BufferedWriter = outputStream.bufferedWriter() 14 | val inputStream: InputStream = PipedInputStream(outputStream) 15 | val pipeOutput = ByteArrayOutputStream() 16 | val waitForPattern = "Server Started!" 17 | val logger = InputStreamPipe(inputStream, pipeOutput, waitForPattern) 18 | val latch: CountDownLatch = CountDownLatch(1) 19 | 20 | @Test 21 | fun shouldCopyInputStreamToOutputStream() { 22 | shouldFindPatternFromLines("Line One", "Line Two", "Line Three", "Line Four", "Server Started!", "Line Five", "Line Six") 23 | } 24 | 25 | @Test 26 | fun shouldFindInLastLine() { 27 | shouldFindPatternFromLines("Line One", "Line Two", "Server Started!") 28 | } 29 | 30 | @Test 31 | fun shouldFindInFirstLine() { 32 | shouldFindPatternFromLines("Server Started!","Line Two","Line Three") 33 | } 34 | 35 | private fun shouldFindPatternFromLines(vararg lines: String) { 36 | Thread({ 37 | lines.forEach { line -> writeLine(line, 100) } 38 | latch.countDown() 39 | }).start() 40 | logger.waitForPattern() 41 | 42 | val outputFileContents:List = splitAndRemoveExtraEmptyString() 43 | val msg = "outputFileContents: ${outputFileContents.joinToString(separator = System.lineSeparator())}" 44 | 45 | assertThat(msg, outputFileContents, `is`(allLinesUntilPattern(lines))) 46 | 47 | latch.await() 48 | 49 | val outputFileContentsTwo:List = splitAndRemoveExtraEmptyString() 50 | val msgTwo = "outputFileContents: ${outputFileContents.joinToString(separator = System.lineSeparator())}" 51 | assertThat(msgTwo, outputFileContentsTwo, contains(*lines)) 52 | } 53 | 54 | private fun allLinesUntilPattern(lines: Array): List { 55 | val takeWhile: MutableList = lines.takeWhile { i -> i != "Server Started!" }.toMutableList() 56 | takeWhile.add("Server Started!") 57 | return takeWhile.toList() 58 | } 59 | 60 | private fun splitAndRemoveExtraEmptyString() = String(pipeOutput.toByteArray()).split(System.lineSeparator()).filter { i -> i != "" } 61 | 62 | @After 63 | fun cleanup() { 64 | outputBuffer.close() 65 | outputStream.close() 66 | } 67 | 68 | private fun writeLine(output:String, postDelay:Long) { 69 | outputBuffer.appendLine(output) 70 | outputBuffer.flush() 71 | Thread.sleep(postDelay) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/psxpaul/task/ExecJoinTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.task 2 | 3 | import org.gradle.testfixtures.ProjectBuilder 4 | import org.hamcrest.Matchers.equalTo 5 | import org.junit.Assert.assertThat 6 | import org.junit.Test 7 | 8 | class ExecJoinTest { 9 | @Test 10 | fun testCreateNameFor() { 11 | assertName("startJohnnie", "stopJohnnie") 12 | assertName("johnnie_start", "johnnie_stop") 13 | assertName("johnnieStart", "johnnieStop") 14 | assertName("johnnie_Start", "johnnie_Stop") 15 | assertName("johnnieSTART", "johnnieSTOP") 16 | assertName("STARTjohnnie", "STOPjohnnie") 17 | 18 | assertName("runJohnnie", "stopJohnnie") 19 | assertName("johnnie_run", "johnnie_stop") 20 | assertName("johnnieRun", "johnnieStop") 21 | assertName("johnnie_Run", "johnnie_Stop") 22 | assertName("johnnieRUN", "johnnieSTOP") 23 | assertName("RUNjohnnie", "STOPjohnnie") 24 | 25 | assertName("execJohnnie", "stopJohnnie") 26 | assertName("johnnie_exec", "johnnie_stop") 27 | assertName("johnnieExec", "johnnieStop") 28 | assertName("johnnie_Exec", "johnnie_Stop") 29 | assertName("johnnieEXEC", "johnnieSTOP") 30 | assertName("EXECjohnnie", "STOPjohnnie") 31 | 32 | assertName("joseph", "joseph_stop") 33 | } 34 | 35 | fun assertName(given:String, expected:String) { 36 | val project = ProjectBuilder.builder().build() 37 | val startTask = project.tasks.create(given, JavaExecFork::class.java) 38 | assertThat(createNameFor(startTask), equalTo(expected)) 39 | } 40 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/github/psxpaul/util/PortUtilsTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.psxpaul.util 2 | 3 | import org.gradle.api.GradleException 4 | import org.hamcrest.Matchers.* 5 | import org.junit.Assert.assertThat 6 | import org.junit.Assert.fail 7 | import org.junit.Test 8 | import java.io.InputStream 9 | import java.io.OutputStream 10 | import java.net.ConnectException 11 | import java.net.InetAddress 12 | import java.net.ServerSocket 13 | import java.net.Socket 14 | import java.util.concurrent.CountDownLatch 15 | import java.util.concurrent.TimeUnit 16 | 17 | class PortUtilsTest { 18 | @Test 19 | fun testFindOpenPort() { 20 | val port = findOpenPort() 21 | assertThat(port, greaterThanOrEqualTo(1024)) 22 | assertThat(port, lessThanOrEqualTo(65535)) 23 | 24 | try { 25 | Socket(InetAddress.getLoopbackAddress(), port).use { fail("Socket should not have been in use already!") } 26 | } catch (e: ConnectException) { 27 | assertThat(e.message, containsString("Connection refused")) 28 | } 29 | } 30 | 31 | @Test(timeout=2000) 32 | fun testWaitForPortOpen_timeout() { 33 | val stubProcess:Process = StubProcess() 34 | val port = findOpenPort() 35 | 36 | try { 37 | waitForPortOpen(port, 1, TimeUnit.SECONDS, stubProcess) 38 | } catch (e:Exception) { 39 | assertThat(e, instanceOf(GradleException::class.java)) 40 | assertThat(e.message, equalTo("Timed out waiting for port $port to be opened")) 41 | } 42 | } 43 | 44 | @Test(timeout=2000) 45 | fun testWaitForPortOpen_processDied() { 46 | val stubProcess:Process = StubProcess(false) 47 | val port = findOpenPort() 48 | 49 | try { 50 | waitForPortOpen(port, 1, TimeUnit.MINUTES, stubProcess) 51 | } catch (e:Exception) { 52 | assertThat(e, instanceOf(GradleException::class.java)) 53 | assertThat(e.message, equalTo("Process died before port $port was opened")) 54 | } 55 | } 56 | 57 | @Test(timeout=2000) 58 | fun testWaitForPortOpen_success() { 59 | val stubProcess: Process = StubProcess() 60 | val port = findOpenPort() 61 | val latch = CountDownLatch(1) 62 | 63 | Thread({ 64 | ServerSocket(port, 1, InetAddress.getLoopbackAddress()).use { 65 | it.accept() 66 | latch.countDown() 67 | } 68 | }).start() 69 | 70 | waitForPortOpen(port, 1, TimeUnit.MINUTES, stubProcess) 71 | latch.await(1, TimeUnit.SECONDS) 72 | assertThat(latch.count, equalTo(0L)) 73 | } 74 | 75 | class StubProcess(val alive:Boolean = true) : Process() { 76 | override fun destroy() {} 77 | override fun exitValue(): Int { return 0 } 78 | override fun getOutputStream(): OutputStream? { return null } 79 | override fun getErrorStream(): InputStream? { return null } 80 | override fun getInputStream(): InputStream? { return null } 81 | override fun waitFor(): Int { return 0 } 82 | 83 | override fun isAlive():Boolean { 84 | return alive 85 | } 86 | } 87 | } --------------------------------------------------------------------------------