├── .github ├── CODEOWNERS ├── dependabot.yml ├── release-drafter.yml └── workflows │ ├── build.yaml │ ├── cd.yaml │ ├── jenkins-security-scan.yml │ └── release-drafter.yml ├── .gitignore ├── .mvn ├── extensions.xml └── maven.config ├── Jenkinsfile ├── LICENSE ├── README.md ├── docs ├── developer.md ├── job.md └── run.md ├── pom.xml └── src ├── main ├── java │ └── io │ │ └── jenkins │ │ └── plugins │ │ └── generic │ │ └── event │ │ ├── Event.java │ │ ├── EventGlobalConfiguration.java │ │ ├── EventSender.java │ │ ├── HttpEventSender.java │ │ ├── MetaData.java │ │ ├── data │ │ └── WorkflowRunData.java │ │ ├── json │ │ ├── EventJsonConfig.java │ │ ├── ExportedBeanProcessor.java │ │ └── InstantProcessor.java │ │ ├── listener │ │ ├── GenericEventItemListener.java │ │ └── GenericEventRunListener.java │ │ └── transformer │ │ ├── EnhancedData.java │ │ ├── EventDataTransformer.java │ │ └── EventDataTransformers.java └── resources │ ├── index.jelly │ └── io │ └── jenkins │ └── plugins │ └── generic │ └── event │ └── EventGlobalConfiguration │ └── config.jelly └── test └── java └── io └── jenkins └── plugins └── generic └── event ├── json ├── ExportedBeanProcessorTest.java └── InstantProcessorTest.java └── listener ├── ItemListenerTest.java └── RunListenerTest.java /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @jenkinsci/generic-event-plugin-developers 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 2 | 3 | version: 2 4 | updates: 5 | - package-ecosystem: "maven" 6 | directory: "/" 7 | schedule: 8 | interval: "weekly" 9 | - package-ecosystem: "github-actions" 10 | directory: "/" 11 | schedule: 12 | interval: "weekly" 13 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | _extends: .github 2 | 3 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up JDK 17 12 | uses: actions/setup-java@v4 13 | with: 14 | java-version: '17' 15 | distribution: 'temurin' 16 | cache: 'maven' 17 | - name: Build with Maven 18 | run: mvn --batch-mode --update-snapshots verify 19 | -------------------------------------------------------------------------------- /.github/workflows/cd.yaml: -------------------------------------------------------------------------------- 1 | name: cd 2 | on: 3 | workflow_dispatch: 4 | check_run: 5 | types: 6 | - completed 7 | 8 | jobs: 9 | maven-cd: 10 | uses: jenkins-infra/github-reusable-workflows/.github/workflows/maven-cd.yml@v1 11 | secrets: 12 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 13 | MAVEN_TOKEN: ${{ secrets.MAVEN_TOKEN }} 14 | 15 | -------------------------------------------------------------------------------- /.github/workflows/jenkins-security-scan.yml: -------------------------------------------------------------------------------- 1 | name: Jenkins Security Scan 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: [ opened, synchronize, reopened ] 9 | workflow_dispatch: 10 | 11 | permissions: 12 | security-events: write 13 | contents: read 14 | actions: read 15 | 16 | jobs: 17 | security-scan: 18 | uses: jenkins-infra/jenkins-security-scan/.github/workflows/jenkins-security-scan.yaml@v2 19 | with: 20 | java-cache: 'maven' # Optionally enable use of a build dependency cache. Specify 'maven' or 'gradle' as appropriate. 21 | # java-version: 21 # Optionally specify what version of Java to set up for the build, or remove to use a recent default. 22 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | # Automates creation of Release Drafts using Release Drafter 2 | # More Info: https://github.com/jenkinsci/.github/blob/master/.github/release-drafter.adoc 3 | 4 | on: 5 | push: 6 | branches: 7 | - master 8 | - main 9 | 10 | jobs: 11 | update_release_draft: 12 | runs-on: ubuntu-latest 13 | steps: 14 | # Drafts your next Release notes as Pull Requests are merged into the default branch 15 | - uses: release-drafter/release-drafter@v5.13.0 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | 3 | # mvn hpi:run 4 | work 5 | .mvn 6 | 7 | # IntelliJ IDEA project files 8 | *.iml 9 | *.iws 10 | *.ipr 11 | .idea 12 | 13 | # Eclipse project files 14 | .settings 15 | .classpath 16 | .project 17 | 18 | # Visual Studio Code files 19 | .vscode 20 | -------------------------------------------------------------------------------- /.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | io.jenkins.tools.incrementals 4 | git-changelist-maven-extension 5 | 1.2 6 | 7 | 8 | -------------------------------------------------------------------------------- /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | -Pconsume-incrementals 2 | -Pmight-produce-incrementals 3 | -Dchangelist.format=%d.v%s 4 | 5 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | /* 2 | See the documentation for more options: 3 | https://github.com/jenkins-infra/pipeline-library/ 4 | */ 5 | buildPlugin(useContainerAgent: true, jdkVersions: [17]) 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Generic Event Plugin 2 | 3 | ## Introduction 4 | 5 | The Generic Event Plugin built for Jenkins is mainly to solve the interaction problem between the third-party system and 6 | Jenkins. 7 | 8 | By using the plugin, the third-party system can receive the events it is interested in more quickly and respond quickly. 9 | 10 | At present, our event body mainly refers to CloudEvents, and CloudEvents specification may be supported in the future. 11 | We look forward to more people to push this goal. 12 | 13 | ## Getting Started 14 | 15 | You can configure the event receiver in system management: 16 | 17 | ```txt 18 | Event Dispatcher 19 | 20 | Event Receiver 21 | ,-----------------------------------------------. 22 | |http://localhost:8000/v1alpha1/webhooks/jenkins| 23 | `-----------------------------------------------' 24 | The receiver that can receive the event fired by system. 25 | ``` 26 | 27 | ## Events Documentation 28 | 29 | After the event receiver is configured, we can easily receive events from Jenkins. The following is the detailed 30 | document of the corresponding event: 31 | 32 | - [Run Event](docs/run.md) 33 | - [Job Event](docs/job.md) 34 | 35 | ## TODOs 36 | 37 | - [ ] Send events asynchronously 38 | - [ ] Support custom filter to filter events 39 | - [ ] Collect more events 40 | 41 | ## Contributing 42 | 43 | Please refer to [Developer Guide](docs/developer.md). 44 | 45 | ## LICENSE 46 | 47 | Licensed under Apache 2.0, see [LICENSE](LICENSE) 48 | 49 | -------------------------------------------------------------------------------- /docs/developer.md: -------------------------------------------------------------------------------- 1 | # Developer Guide 2 | 3 | TODO 4 | 5 | -------------------------------------------------------------------------------- /docs/job.md: -------------------------------------------------------------------------------- 1 | # Item Event 2 | 3 | ## Item Create 4 | 5 | ```json 6 | { 7 | "data": { 8 | "_class": "org.jvnet.hudson.test.MockFolder", 9 | "actions": [ 10 | {}, 11 | {}, 12 | { 13 | "_class": "com.cloudbees.plugins.credentials.ViewCredentialsAction" 14 | } 15 | ], 16 | "description": null, 17 | "displayName": "my-devops-project", 18 | "displayNameOrNull": null, 19 | "fullDisplayName": "my-devops-project", 20 | "fullName": "my-devops-project", 21 | "name": "my-devops-project" 22 | }, 23 | "dataType": "org.jvnet.hudson.test.MockFolder", 24 | "id": "10f94a34-587d-43cd-a296-3051f922dc72", 25 | "source": "", 26 | "time": "2022-02-06T13:48:15.041+0800", 27 | "type": "item.created" 28 | } 29 | ``` 30 | 31 | ```json 32 | { 33 | "data": { 34 | "_class": "org.jenkinsci.plugins.workflow.job.WorkflowJob", 35 | "actions": [ 36 | {}, 37 | {}, 38 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.JobDisplayAction"}, 39 | {}, 40 | {}, 41 | {"_class": "com.cloudbees.plugins.credentials.ViewCredentialsAction"} 42 | ], 43 | "description": null, 44 | "displayName": "example-pipeline", 45 | "displayNameOrNull": null, 46 | "fullDisplayName": "my-devops-project » example-pipeline", 47 | "fullName": "my-devops-project/example-pipeline", 48 | "name": "example-pipeline", 49 | "buildable": true, 50 | "builds": [], 51 | "color": "notbuilt", 52 | "firstBuild": null, 53 | "healthReport": [], 54 | "inQueue": false, 55 | "keepDependencies": false, 56 | "lastBuild": null, 57 | "lastCompletedBuild": null, 58 | "lastFailedBuild": null, 59 | "lastStableBuild": null, 60 | "lastSuccessfulBuild": null, 61 | "lastUnstableBuild": null, 62 | "lastUnsuccessfulBuild": null, 63 | "nextBuildNumber": 1, 64 | "property": [], 65 | "queueItem": null, 66 | "concurrentBuild": true, 67 | "resumeBlocked": false 68 | }, 69 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowJob", 70 | "id": "ea8b623e-d2b2-45d5-8f1c-65b3ac153e39", 71 | "source": "job/my-devops-project/", 72 | "time": "2022-02-06T13:48:15.204+0800", 73 | "type": "item.created" 74 | } 75 | ``` 76 | 77 | ## Item Updated 78 | 79 | ```json 80 | { 81 | "data": { 82 | "_class": "org.jvnet.hudson.test.MockFolder", 83 | "actions": [ 84 | {}, 85 | {}, 86 | {"_class": "com.cloudbees.plugins.credentials.ViewCredentialsAction"} 87 | ], 88 | "description": "Fake description", 89 | "displayName": "my-devops-project", 90 | "displayNameOrNull": null, 91 | "fullDisplayName": "my-devops-project", 92 | "fullName": "my-devops-project", 93 | "name": "my-devops-project" 94 | }, 95 | "dataType": "org.jvnet.hudson.test.MockFolder", 96 | "id": "2934f42b-a6bb-47f4-9f39-7638bbbc967e", 97 | "source": "", 98 | "time": "2022-02-07T09:05:13.397+0800", 99 | "type": "item.updated" 100 | } 101 | ``` 102 | 103 | ## Item Deleted 104 | 105 | ```json 106 | { 107 | "data": { 108 | "_class": "org.jvnet.hudson.test.MockFolder", 109 | "actions": [ 110 | {}, 111 | {}, 112 | {"_class": "com.cloudbees.plugins.credentials.ViewCredentialsAction"} 113 | ], 114 | "description": "Fake description", 115 | "displayName": "my-devops-project", 116 | "displayNameOrNull": null, 117 | "fullDisplayName": "my-devops-project", 118 | "fullName": "my-devops-project", 119 | "name": "my-devops-project" 120 | }, 121 | "dataType": "org.jvnet.hudson.test.MockFolder", 122 | "id": "3df06edd-3822-4d8b-b70f-ed13b36a6851", 123 | "source": "", 124 | "time": "2022-02-07T09:07:05.993+0800", 125 | "type": "item.deleted" 126 | } 127 | ``` 128 | -------------------------------------------------------------------------------- /docs/run.md: -------------------------------------------------------------------------------- 1 | # Run Event 2 | 3 | ## Run Initialize 4 | 5 | ```json 6 | { 7 | "data": { 8 | "_class": "io.jenkins.plugins.generic.event.data.WorkflowRunData", 9 | "actions": [ 10 | { 11 | "_class": "hudson.model.ParametersAction", 12 | "parameters": [ { 13 | "_class": "hudson.model.BooleanParameterValue", 14 | "name": "skip", 15 | "value": false 16 | }] 17 | }, 18 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"}, 19 | {"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"}, 20 | {}, 21 | {"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"}, 22 | {}, 23 | {}, 24 | {} 25 | ], 26 | "artifacts": [], 27 | "building": true, 28 | "description": null, 29 | "displayName": "#1", 30 | "duration": 0, 31 | "estimatedDuration": -1, 32 | "executor": {"_class": "hudson.model.OneOffExecutor"}, 33 | "fullDisplayName": "my-devops-project » example-pipeline #1", 34 | "id": "1", 35 | "keepLog": false, 36 | "number": 1, 37 | "queueId": 1, 38 | "result": null, 39 | "timestamp": 1644126495293, 40 | "changeSets": [], 41 | "culprits": [], 42 | "nextBuild": null, 43 | "previousBuild": null, 44 | "_multiBranch": false, 45 | "_parentFullName": "my-devops-project", 46 | "_projectName": "example-pipeline" 47 | }, 48 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowRun", 49 | "id": "50c33b0e-d7f1-4a34-b57e-bb82cd453894", 50 | "source": "job/my-devops-project/job/example-pipeline/", 51 | "time": "2022-02-06T13:48:15.307+0800", 52 | "type": "run.initialize" 53 | } 54 | ``` 55 | 56 | ## Run started 57 | 58 | ```json 59 | { 60 | "data": { 61 | "_class": "io.jenkins.plugins.generic.event.data.WorkflowRunData", 62 | "actions": [ 63 | { 64 | "_class": "hudson.model.ParametersAction", 65 | "parameters": [ { 66 | "_class": "hudson.model.BooleanParameterValue", 67 | "name": "skip", 68 | "value": false 69 | }] 70 | }, 71 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"}, 72 | {"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"}, 73 | {}, 74 | {"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"}, 75 | {}, 76 | {}, 77 | {} 78 | ], 79 | "artifacts": [], 80 | "building": true, 81 | "description": null, 82 | "displayName": "#1", 83 | "duration": 0, 84 | "estimatedDuration": -1, 85 | "executor": {"_class": "hudson.model.OneOffExecutor"}, 86 | "fullDisplayName": "my-devops-project » example-pipeline #1", 87 | "id": "1", 88 | "keepLog": false, 89 | "number": 1, 90 | "queueId": 1, 91 | "result": null, 92 | "timestamp": 1644126495293, 93 | "changeSets": [], 94 | "culprits": [], 95 | "nextBuild": null, 96 | "previousBuild": null, 97 | "_multiBranch": false, 98 | "_parentFullName": "my-devops-project", 99 | "_projectName": "example-pipeline" 100 | }, 101 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowRun", 102 | "id": "eb227ba6-9135-45ff-bec5-a28ccb587bb9", 103 | "source": "job/my-devops-project/job/example-pipeline/", 104 | "time": "2022-02-06T13:48:15.333+0800", 105 | "type": "run.started" 106 | } 107 | ``` 108 | 109 | ## Run Completed 110 | 111 | ```json 112 | { 113 | "data": { 114 | "_class": "io.jenkins.plugins.generic.event.data.WorkflowRunData", 115 | "actions": [ 116 | { 117 | "_class": "hudson.model.ParametersAction", 118 | "parameters": [ { 119 | "_class": "hudson.model.BooleanParameterValue", 120 | "name": "skip", 121 | "value": false 122 | }] 123 | }, 124 | {"_class": "org.jenkinsci.plugins.workflow.libs.LibrariesAction"}, 125 | {}, 126 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"}, 127 | {"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"}, 128 | {}, 129 | {"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"}, 130 | {}, 131 | {}, 132 | {} 133 | ], 134 | "artifacts": [], 135 | "building": false, 136 | "description": null, 137 | "displayName": "#1", 138 | "duration": 1715, 139 | "estimatedDuration": 1715, 140 | "executor": {"_class": "hudson.model.OneOffExecutor"}, 141 | "fullDisplayName": "my-devops-project » example-pipeline #1", 142 | "id": "1", 143 | "keepLog": false, 144 | "number": 1, 145 | "queueId": 1, 146 | "result": "SUCCESS", 147 | "timestamp": 1644126495293, 148 | "changeSets": [], 149 | "culprits": [], 150 | "nextBuild": null, 151 | "previousBuild": null, 152 | "_multiBranch": false, 153 | "_parentFullName": "my-devops-project", 154 | "_projectName": "example-pipeline" 155 | }, 156 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowRun", 157 | "id": "aaf73c16-574b-4c1b-a740-4494318a59d5", 158 | "source": "job/my-devops-project/job/example-pipeline/", 159 | "time": "2022-02-06T13:48:17.022+0800", 160 | "type": "run.completed" 161 | } 162 | ``` 163 | 164 | ## Run Finalized 165 | 166 | ```json 167 | { 168 | "data": { 169 | "_class": "io.jenkins.plugins.generic.event.data.WorkflowRunData", 170 | "actions": [ 171 | { 172 | "_class": "hudson.model.ParametersAction", 173 | "parameters": [ { 174 | "_class": "hudson.model.BooleanParameterValue", 175 | "name": "skip", 176 | "value": false 177 | }] 178 | }, 179 | {"_class": "org.jenkinsci.plugins.workflow.libs.LibrariesAction"}, 180 | {}, 181 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"}, 182 | {"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"}, 183 | {}, 184 | {"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"}, 185 | {}, 186 | {}, 187 | {} 188 | ], 189 | "artifacts": [], 190 | "building": false, 191 | "description": null, 192 | "displayName": "#1", 193 | "duration": 1715, 194 | "estimatedDuration": 1715, 195 | "executor": {"_class": "hudson.model.OneOffExecutor"}, 196 | "fullDisplayName": "my-devops-project » example-pipeline #1", 197 | "id": "1", 198 | "keepLog": false, 199 | "number": 1, 200 | "queueId": 1, 201 | "result": "SUCCESS", 202 | "timestamp": 1644126495293, 203 | "changeSets": [], 204 | "culprits": [], 205 | "nextBuild": null, 206 | "previousBuild": null, 207 | "_multiBranch": false, 208 | "_parentFullName": "my-devops-project", 209 | "_projectName": "example-pipeline" 210 | }, 211 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowRun", 212 | "id": "bc11e508-a3ee-4900-8864-2be30e1ffda5", 213 | "source": "job/my-devops-project/job/example-pipeline/", 214 | "time": "2022-02-06T13:48:17.055+0800", 215 | "type": "run.finalized" 216 | } 217 | ``` 218 | 219 | ## Run Deleted 220 | 221 | ```json 222 | { 223 | "data": { 224 | "_class": "io.jenkins.plugins.generic.event.data.WorkflowRunData", 225 | "actions": [ 226 | { 227 | "_class": "hudson.model.ParametersAction", 228 | "parameters": [ { 229 | "_class": "hudson.model.BooleanParameterValue", 230 | "name": "skip", 231 | "value": false 232 | }] 233 | }, 234 | {"_class": "org.jenkinsci.plugins.workflow.libs.LibrariesAction"}, 235 | {}, 236 | {"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"}, 237 | {"_class": "org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction"}, 238 | {}, 239 | {"_class": "org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"}, 240 | {}, 241 | {}, 242 | {} 243 | ], 244 | "artifacts": [], 245 | "building": false, 246 | "description": null, 247 | "displayName": "#1", 248 | "duration": 1584, 249 | "estimatedDuration": 1584, 250 | "executor": null, 251 | "fullDisplayName": "my-devops-project » example-pipeline #1", 252 | "id": "1", 253 | "keepLog": false, 254 | "number": 1, 255 | "queueId": 1, 256 | "result": "SUCCESS", 257 | "timestamp": 1644126900080, 258 | "changeSets": [], 259 | "culprits": [], 260 | "nextBuild": null, 261 | "previousBuild": null, 262 | "_multiBranch": false, 263 | "_parentFullName": "my-devops-project", 264 | "_projectName": "example-pipeline" 265 | }, 266 | "dataType": "org.jenkinsci.plugins.workflow.job.WorkflowRun", 267 | "id": "af7e9187-c244-46ac-8e4c-15335f38550c", 268 | "source": "job/my-devops-project/job/example-pipeline/", 269 | "time": "2022-02-06T13:55:01.792+0800", 270 | "type": "run.deleted" 271 | } 272 | ``` 273 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | org.jenkins-ci.plugins 6 | plugin 7 | 5.7 8 | 9 | 10 | io.jenkins.plugins 11 | generic-event 12 | ${changelist} 13 | hpi 14 | Generic Event Plugin 15 | https://github.com/jenkinsci/${project.artifactId}-plugin 16 | 17 | Allows users to receive events fired by system via webhook. 18 | 19 | 20 | 21 | Apache License, Version 2.0 22 | https://opensource.org/licenses/Apache-2.0 23 | 24 | 25 | 26 | 27 | scm:git:https://github.com/${gitHubRepo} 28 | scm:git:https://github.com/${gitHubRepo} 29 | ${scmTag} 30 | https://github.com/${gitHubRepo} 31 | 32 | 33 | 999999-SNAPSHOT 34 | 35 | 2.479 36 | 37 | 38 | ${jenkins.baseline}.1 39 | jenkinsci/${project.artifactId}-plugin 40 | 41 | 42 | 43 | 44 | 45 | 46 | io.jenkins.tools.bom 47 | bom-${jenkins.baseline}.x 48 | 52 | 4136.vca_c3202a_7fd1 53 | pom 54 | import 55 | 56 | 57 | 58 | 59 | 60 | org.jenkins-ci.plugins 61 | structs 62 | 63 | 64 | org.jenkins-ci.plugins.workflow 65 | workflow-job 66 | 67 | 68 | org.jenkins-ci.plugins.workflow 69 | workflow-api 70 | 71 | 72 | org.jenkins-ci.plugins.workflow 73 | workflow-step-api 74 | 75 | 76 | 77 | org.jenkins-ci.plugins.workflow 78 | workflow-multibranch 79 | 80 | 81 | 82 | org.apache.httpcomponents.client5 83 | httpclient5 84 | 5.1.2 85 | 86 | 87 | net.jodah 88 | typetools 89 | 0.6.3 90 | 91 | 92 | 93 | org.jenkinsci.plugins 94 | pipeline-model-definition 95 | test 96 | 97 | 98 | org.jenkins-ci.plugins 99 | git 100 | test 101 | 102 | 103 | org.jenkins-ci.plugins 104 | git 105 | test 106 | tests 107 | 108 | 109 | 110 | org.jenkins-ci.plugins 111 | scm-api 112 | 113 | 114 | 115 | org.jenkins-ci.plugins 116 | scm-api 117 | tests 118 | test 119 | 120 | 121 | 122 | org.mockito 123 | mockito-core 124 | test 125 | 126 | 127 | 128 | 129 | 130 | repo.jenkins-ci.org 131 | https://repo.jenkins-ci.org/public/ 132 | 133 | 134 | 135 | 136 | repo.jenkins-ci.org 137 | https://repo.jenkins-ci.org/public/ 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/Event.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event; 2 | 3 | import java.time.Instant; 4 | import java.util.Objects; 5 | import java.util.UUID; 6 | 7 | import org.apache.commons.lang.StringUtils; 8 | 9 | /** 10 | * Event structure. 11 | * 12 | * @author johnniang 13 | */ 14 | public class Event { 15 | 16 | private String type; 17 | 18 | private String source; 19 | 20 | private String url; 21 | 22 | private String id; 23 | 24 | private Instant time; 25 | 26 | private String dataType; 27 | 28 | private Object data; 29 | private MetaData metaData; 30 | 31 | public Event(EventBuilder builder) { 32 | this.type = builder.type; 33 | this.source = builder.source; 34 | this.url = builder.url; 35 | this.id = builder.id; 36 | this.time = builder.time; 37 | this.dataType = builder.dataType; 38 | this.data = builder.data; 39 | this.metaData = builder.metaData; 40 | } 41 | 42 | public static class EventBuilder { 43 | 44 | private String type; 45 | 46 | private String source; 47 | 48 | private String url; 49 | 50 | private String id; 51 | 52 | private Instant time; 53 | 54 | private String dataType; 55 | 56 | private Object data; 57 | 58 | private MetaData metaData; 59 | 60 | public EventBuilder() { 61 | } 62 | 63 | public EventBuilder type(String type) { 64 | this.type = type; 65 | return this; 66 | } 67 | 68 | public EventBuilder source(String source) { 69 | this.source = source; 70 | return this; 71 | } 72 | 73 | public EventBuilder url(String url) { 74 | this.url = url; 75 | return this; 76 | } 77 | 78 | public EventBuilder dataType(String dataType) { 79 | this.dataType = dataType; 80 | return this; 81 | } 82 | 83 | public EventBuilder data(Object data) { 84 | this.data = data; 85 | return this; 86 | } 87 | 88 | public EventBuilder metaData(MetaData metaData) { 89 | this.metaData = metaData; 90 | return this; 91 | } 92 | 93 | public Event build() { 94 | if (StringUtils.isBlank(dataType) && data != null) { 95 | dataType = data.getClass().getName(); 96 | } 97 | id = UUID.randomUUID().toString(); 98 | time = Instant.now(); 99 | // TODO Validate other fields. 100 | return new Event(this); 101 | } 102 | } 103 | 104 | public String getType() { 105 | return type; 106 | } 107 | 108 | public void setType(String type) { 109 | this.type = type; 110 | } 111 | 112 | public String getSource() { 113 | return source; 114 | } 115 | 116 | public void setSource(String source) { 117 | this.source = source; 118 | } 119 | 120 | public String getUrl() { 121 | return url; 122 | } 123 | 124 | public void setUrl(String url) { 125 | this.url = url; 126 | } 127 | 128 | public String getId() { 129 | return id; 130 | } 131 | 132 | public void setId(String id) { 133 | this.id = id; 134 | } 135 | 136 | public Instant getTime() { 137 | return time; 138 | } 139 | 140 | public void setTime(Instant time) { 141 | this.time = time; 142 | } 143 | 144 | public String getDataType() { 145 | return dataType; 146 | } 147 | 148 | public void setDataType(String dataType) { 149 | this.dataType = dataType; 150 | } 151 | 152 | public Object getData() { 153 | return data; 154 | } 155 | 156 | public void setData(Object data) { 157 | this.data = data; 158 | } 159 | 160 | public MetaData getMetaData() { 161 | return metaData; 162 | } 163 | 164 | public void setMetaData(MetaData metaData) { 165 | this.metaData = metaData; 166 | } 167 | 168 | @Override 169 | public boolean equals(Object o) { 170 | if (this == o) return true; 171 | if (o == null || getClass() != o.getClass()) return false; 172 | Event event = (Event) o; 173 | return Objects.equals(type, event.type) 174 | && Objects.equals(source, event.source) 175 | && Objects.equals(url, event.url) 176 | && Objects.equals(id, event.id) 177 | && Objects.equals(time, event.time) 178 | && Objects.equals(dataType, event.dataType) 179 | && Objects.equals(data, event.data); 180 | } 181 | 182 | @Override 183 | public int hashCode() { 184 | return Objects.hash(type, source, url, id, time, dataType, data); 185 | } 186 | 187 | public String getUrlData() { 188 | return "item.locationChanged".equals(type) ? ", metaData=" + metaData.toString() : ", url=" + url; 189 | } 190 | 191 | @Override 192 | public String toString() { 193 | return "Event [data=" + data + ", dataType=" + dataType + ", id=" + id + 194 | ", source=" + source + this.getUrlData() + ", time=" + time + ", type=" + type + "]"; 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/EventGlobalConfiguration.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event; 2 | 3 | import hudson.Extension; 4 | import jenkins.model.GlobalConfiguration; 5 | import net.sf.json.JSONObject; 6 | import org.jenkinsci.Symbol; 7 | import org.kohsuke.stapler.DataBoundSetter; 8 | import org.kohsuke.stapler.StaplerRequest2; 9 | 10 | @Extension(ordinal = 100) 11 | @Symbol("eventDispatcher") 12 | public class EventGlobalConfiguration extends GlobalConfiguration { 13 | 14 | private String receiver; 15 | 16 | public EventGlobalConfiguration() { 17 | this.load(); 18 | } 19 | 20 | public static EventGlobalConfiguration get() { 21 | return GlobalConfiguration.all().get(EventGlobalConfiguration.class); 22 | } 23 | 24 | @Override 25 | public boolean configure(StaplerRequest2 req, JSONObject json) { 26 | req.bindJSON(this, json); 27 | this.save(); 28 | return true; 29 | } 30 | 31 | @Override 32 | public String getDisplayName() { 33 | return "Event Dispatcher"; 34 | } 35 | 36 | public String getReceiver() { 37 | return this.receiver; 38 | } 39 | 40 | @DataBoundSetter 41 | public void setReceiver(String receiver) { 42 | this.receiver = receiver; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/EventSender.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event; 2 | 3 | import java.util.logging.Logger; 4 | 5 | import io.jenkins.plugins.generic.event.transformer.EventDataTransformers; 6 | 7 | /** 8 | * An interface for sending event by various methods, like asynchronization or 9 | * synchronization. 10 | * 11 | * @author johnniang 12 | */ 13 | public interface EventSender { 14 | 15 | void send(Event event); 16 | 17 | public static class NoopEventSender implements EventSender { 18 | 19 | private final Logger logger = Logger.getLogger(NoopEventSender.class.getName()); 20 | 21 | @Override 22 | public void send(Event event) { 23 | // try to transform data 24 | EventDataTransformers.INSTANCE.transform(event); 25 | 26 | // Just log the event 27 | logger.info("Sent event: " + event.toString()); 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/HttpEventSender.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event; 2 | 3 | import java.util.concurrent.Future; 4 | import java.util.logging.Level; 5 | import java.util.logging.Logger; 6 | 7 | import jenkins.model.Jenkins; 8 | import org.apache.commons.lang.StringUtils; 9 | import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; 10 | import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; 11 | import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; 12 | import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; 13 | import org.apache.hc.client5.http.impl.async.HttpAsyncClients; 14 | import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; 15 | import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; 16 | import org.apache.hc.core5.concurrent.FutureCallback; 17 | import org.apache.hc.core5.http.*; 18 | import io.jenkins.plugins.generic.event.json.EventJsonConfig; 19 | import io.jenkins.plugins.generic.event.transformer.EventDataTransformers; 20 | import net.sf.json.JSONObject; 21 | import org.apache.hc.core5.util.TimeValue; 22 | 23 | /** 24 | * An implementation of EventSender, which sends event body via HTTP. 25 | * 26 | * @author johnniang 27 | */ 28 | public class HttpEventSender implements EventSender { 29 | 30 | private final Logger logger = Logger.getLogger(HttpEventSender.class.getName()); 31 | private final CustomCloseableHttpAsyncClient myClient = new CustomCloseableHttpAsyncClient(); 32 | 33 | @Override 34 | public void send(Event event) { 35 | EventDataTransformers.INSTANCE.transform(event); 36 | 37 | final String receiver = EventGlobalConfiguration.get().getReceiver(); 38 | 39 | if (StringUtils.isBlank(receiver)) { 40 | logger.info("Skipped event sending due to receiver URL not set"); 41 | return; 42 | } 43 | 44 | try { 45 | myClient.sendPost(receiver, event, new FutureCallback() { 46 | @Override 47 | public void completed(SimpleHttpResponse response) { 48 | logger.info("Event send succeeded, response: " + response.getBodyText() + ", data: " + event.toString()); 49 | } 50 | 51 | @Override 52 | public void failed(Exception e) { 53 | logger.info("Event send has been failed, response: " + e + ", data: " + event.toString()); 54 | } 55 | 56 | @Override 57 | public void cancelled() { 58 | logger.info("Event send has been cancelled"); 59 | } 60 | }); 61 | } catch (Exception e) { 62 | logger.log(Level.WARNING, "Failed to send event to " + receiver, e); 63 | } 64 | 65 | } 66 | 67 | static public class CustomCloseableHttpAsyncClient { 68 | 69 | private static final CloseableHttpAsyncClient httpClient; 70 | private static String rootUrl = null; 71 | 72 | static { 73 | PoolingAsyncClientConnectionManager cmb = PoolingAsyncClientConnectionManagerBuilder 74 | .create() 75 | .setMaxConnPerRoute(1) 76 | .setMaxConnTotal(1) 77 | .setConnectionTimeToLive(TimeValue.ofSeconds(10L)) 78 | .build(); 79 | 80 | httpClient = HttpAsyncClients.custom().setConnectionManager(cmb).build(); 81 | httpClient.start(); 82 | 83 | Jenkins j = Jenkins.getInstanceOrNull(); 84 | if (j != null) { 85 | rootUrl = j.getRootUrl(); 86 | } 87 | } 88 | public void sendPost(String receiver, Event event, final FutureCallback callback) { 89 | 90 | String eventJSON = JSONObject.fromObject(event, new EventJsonConfig()).toString(4); 91 | 92 | SimpleHttpRequest request = SimpleRequestBuilder 93 | .post(receiver) 94 | .setBody(eventJSON, ContentType.APPLICATION_JSON) 95 | .addHeader("X-Event-Type", event.getType()) 96 | .addHeader("Referrer", rootUrl) 97 | .build(); 98 | 99 | httpClient.execute(request, callback); 100 | } 101 | } 102 | } 103 | 104 | 105 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/MetaData.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event; 2 | 3 | public class MetaData { 4 | 5 | private String oldName; 6 | 7 | private String newName; 8 | 9 | private String oldUrl; 10 | 11 | private String newUrl; 12 | 13 | public MetaData(MetaDataBuilder builder) { 14 | this.oldName = builder.oldName; 15 | this.newName = builder.newName; 16 | this.oldUrl = builder.oldUrl; 17 | this.newUrl = builder.newUrl; 18 | } 19 | 20 | public static class MetaDataBuilder { 21 | private String oldName; 22 | 23 | private String newName; 24 | 25 | private String oldUrl; 26 | 27 | private String newUrl; 28 | 29 | public MetaDataBuilder() { 30 | 31 | } 32 | 33 | public MetaDataBuilder oldName(String oldName) { 34 | this.oldName = oldName; 35 | return this; 36 | } 37 | 38 | public MetaDataBuilder newName(String newName) { 39 | this.newName = newName; 40 | return this; 41 | } 42 | 43 | public MetaDataBuilder oldUrl(String oldUrl) { 44 | this.oldUrl = oldUrl; 45 | return this; 46 | } 47 | 48 | public MetaDataBuilder newUrl(String newUrl) { 49 | this.newUrl = newUrl; 50 | return this; 51 | } 52 | 53 | public MetaData build() { 54 | return new MetaData(this); 55 | } 56 | } 57 | 58 | public String getOldName() { 59 | return oldName; 60 | } 61 | 62 | public void setOldName(String oldName) { 63 | this.oldName = oldName; 64 | } 65 | 66 | public String getNewName() { 67 | return newName; 68 | } 69 | 70 | public void setNewName(String newName) { 71 | this.newName = newName; 72 | } 73 | 74 | public String getOldUrl() { 75 | return oldUrl; 76 | } 77 | 78 | public void setOldUrl(String oldUrl) { 79 | this.oldUrl = oldUrl; 80 | } 81 | 82 | public String getNewUrl() { 83 | return newUrl; 84 | } 85 | 86 | public void setNewUrl(String newUrl) { 87 | this.newUrl = newUrl; 88 | } 89 | 90 | @Override 91 | public String toString() { 92 | return "MetaData [oldUrl=" + oldUrl + ", newUrl=" + newUrl + 93 | ", oldName=" + oldName + ", newName=" + newName + "]"; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/data/WorkflowRunData.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.data; 2 | 3 | import io.jenkins.plugins.generic.event.transformer.EnhancedData; 4 | import jenkins.branch.MultiBranchProject; 5 | import org.jenkinsci.plugins.workflow.job.WorkflowJob; 6 | import org.jenkinsci.plugins.workflow.job.WorkflowRun; 7 | import org.kohsuke.stapler.export.Exported; 8 | 9 | import java.util.Objects; 10 | 11 | /** 12 | * WorkflowRun data structure. It contains the raw data of WorkflowRun. 13 | * 14 | * @author johnniang 15 | */ 16 | public class WorkflowRunData extends EnhancedData { 17 | 18 | private String parentFullName; 19 | 20 | private String projectName; 21 | 22 | private boolean isMultiBranch; 23 | 24 | private final WorkflowRun run; 25 | 26 | public WorkflowRunData(WorkflowRun run) { 27 | this.run = run; 28 | WorkflowJob project = run.getParent(); 29 | this.setProjectName(project.getName()); 30 | this.setParentFullName(project.getParent().getFullName()); 31 | if (project.getParent() instanceof MultiBranchProject) { 32 | this.setMultiBranch(true); 33 | } 34 | } 35 | 36 | @Exported(name = "_parentFullName") 37 | public String getParentFullName() { 38 | return parentFullName; 39 | } 40 | 41 | public void setParentFullName(String parentFullName) { 42 | this.parentFullName = parentFullName; 43 | } 44 | 45 | @Exported(name = "_projectName") 46 | public String getProjectName() { 47 | return projectName; 48 | } 49 | 50 | public void setProjectName(String projectName) { 51 | this.projectName = projectName; 52 | } 53 | 54 | @Exported(name = "_multiBranch") 55 | public boolean isMultiBranch() { 56 | return isMultiBranch; 57 | } 58 | 59 | public void setMultiBranch(boolean isMultiBranch) { 60 | this.isMultiBranch = isMultiBranch; 61 | } 62 | 63 | @Override 64 | public boolean equals(Object o) { 65 | if (this == o) return true; 66 | if (o == null || getClass() != o.getClass()) return false; 67 | WorkflowRunData that = (WorkflowRunData) o; 68 | return isMultiBranch == that.isMultiBranch && Objects.equals(parentFullName, that.parentFullName) 69 | && Objects.equals(projectName, that.projectName) && Objects.equals(run, that.run); 70 | } 71 | 72 | @Override 73 | public int hashCode() { 74 | return Objects.hash(parentFullName, projectName, isMultiBranch, run); 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "WorkflowRunData{" + 80 | "parentFullName='" + parentFullName + '\'' + 81 | ", projectName='" + projectName + '\'' + 82 | ", isMultiBranch=" + isMultiBranch + 83 | ", run=" + run + 84 | '}'; 85 | } 86 | 87 | @Override 88 | public WorkflowRun getRaw() { 89 | return run; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/json/EventJsonConfig.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.json; 2 | 3 | import java.time.Instant; 4 | 5 | import org.kohsuke.stapler.export.ExportedBean; 6 | 7 | import net.sf.json.JsonConfig; 8 | 9 | /** 10 | * JSON configuration for event serialization. 11 | * 12 | * @author johnniang 13 | */ 14 | public class EventJsonConfig extends JsonConfig { 15 | 16 | public EventJsonConfig() { 17 | registerJsonValueProcessor(Instant.class, new InstantProcessor()); 18 | registerJsonBeanProcessor(ExportedBean.class, new ExportedBeanProcessor()); 19 | setJsonBeanProcessorMatcher(new ExportedBeanProcessor.Matcher()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/json/ExportedBeanProcessor.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.json; 2 | 3 | import java.io.IOException; 4 | import java.io.StringWriter; 5 | import java.util.Set; 6 | import java.util.logging.Level; 7 | import java.util.logging.Logger; 8 | 9 | import net.sf.json.JSONException; 10 | import org.kohsuke.stapler.export.DataWriter; 11 | import org.kohsuke.stapler.export.ExportConfig; 12 | import org.kohsuke.stapler.export.ExportInterceptor; 13 | import org.kohsuke.stapler.export.ExportedBean; 14 | import org.kohsuke.stapler.export.Flavor; 15 | import org.kohsuke.stapler.export.Model; 16 | import org.kohsuke.stapler.export.ModelBuilder; 17 | import org.kohsuke.stapler.export.Property; 18 | 19 | import net.sf.json.JSONObject; 20 | import net.sf.json.JsonConfig; 21 | import net.sf.json.processors.JsonBeanProcessor; 22 | import net.sf.json.processors.JsonBeanProcessorMatcher; 23 | 24 | /** 25 | * ExportedBeanProcessor is a JSON bean processor for object 26 | * annotated @ExportedBean. 27 | * 28 | * @author johnniang 29 | */ 30 | public class ExportedBeanProcessor implements JsonBeanProcessor { 31 | 32 | private final Logger logger = Logger.getLogger(ExportedBeanProcessor.class.getName()); 33 | 34 | @Override 35 | @SuppressWarnings({ "rawtypes", "unchecked" }) 36 | public JSONObject processBean(Object value, JsonConfig jsonConfig) { 37 | final StringWriter stringWriter = new StringWriter(); 38 | final DataWriter dataWriter; 39 | try { 40 | ExportConfig exportConfig = new ExportConfig().withExportInterceptor(new IgnoreURLExportInterceptor()); 41 | dataWriter = Flavor.JSON.createDataWriter(value, stringWriter, exportConfig); 42 | Model model = new ModelBuilder().get(value.getClass()); 43 | model.writeTo(value, dataWriter); 44 | // return the JSON but as an object 45 | return JSONObject.fromObject(stringWriter.toString()); 46 | } catch (IOException e) { 47 | throw new JSONException("Failed to serialize @Exported model", e); 48 | } 49 | } 50 | 51 | public static class Matcher extends JsonBeanProcessorMatcher { 52 | 53 | @Override 54 | @SuppressWarnings({"unchecked" }) 55 | public Object getMatch(Class target, Set set) { 56 | if (target != null && target.isAnnotationPresent(ExportedBean.class)) { 57 | return ExportedBean.class; 58 | } 59 | return DEFAULT.getMatch(target, set); 60 | } 61 | 62 | } 63 | 64 | public static class IgnoreURLExportInterceptor extends ExportInterceptor { 65 | 66 | @Override 67 | public Object getValue(Property property, Object model, ExportConfig config) throws IOException { 68 | if (property.name.equals("url")) { 69 | return SKIP; 70 | } 71 | return DEFAULT.getValue(property, model, config); 72 | } 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/json/InstantProcessor.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.json; 2 | 3 | import java.time.Instant; 4 | import java.time.ZoneId; 5 | import java.time.format.DateTimeFormatter; 6 | 7 | import net.sf.json.JsonConfig; 8 | import net.sf.json.processors.JsonValueProcessor; 9 | 10 | /** 11 | * InstantProcessor is a JSON value processor for instant type. 12 | * 13 | * @author johnniang 14 | */ 15 | public class InstantProcessor implements JsonValueProcessor { 16 | 17 | public static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; 18 | 19 | private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_STRING) 20 | .withZone(ZoneId.systemDefault()); 21 | 22 | @Override 23 | public Object processArrayValue(Object value, JsonConfig jsonConfig) { 24 | return value == null ? null : formatter.format((Instant) value); 25 | } 26 | 27 | @Override 28 | public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { 29 | return processArrayValue(value, jsonConfig); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/listener/GenericEventItemListener.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.listener; 2 | 3 | import com.cloudbees.hudson.plugins.folder.Folder; 4 | import hudson.Extension; 5 | import hudson.Util; 6 | import hudson.model.*; 7 | import hudson.model.listeners.ItemListener; 8 | import io.jenkins.plugins.generic.event.Event; 9 | import io.jenkins.plugins.generic.event.EventSender; 10 | import io.jenkins.plugins.generic.event.HttpEventSender; 11 | import io.jenkins.plugins.generic.event.MetaData; 12 | import org.kohsuke.stapler.Ancestor; 13 | import org.kohsuke.stapler.Stapler; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * This listener collects events about all items. 20 | * 21 | * @author johnniang 22 | */ 23 | @Extension 24 | public class GenericEventItemListener extends ItemListener { 25 | 26 | private EventSender eventSender; 27 | 28 | public GenericEventItemListener() { 29 | this.setEventSender(new HttpEventSender()); 30 | } 31 | 32 | public void setEventSender(EventSender eventSender) { 33 | this.eventSender = eventSender; 34 | } 35 | 36 | /** 37 | * Normalizes url for canonical representation 38 | * 39 | *

40 | * For example, if the url was "view/myView/job/folder/job/taskName/", 41 | * then result will be "job/folder/job/taskName/" 42 | * 43 | * @param fullName Project name 44 | */ 45 | public String getCanonicalEventUrl(String fullName) { 46 | 47 | StringBuilder resultUrl = new StringBuilder(); 48 | 49 | if (Stapler.getCurrentRequest2() == null) { 50 | return ""; 51 | } 52 | 53 | List ancs = Stapler.getCurrentRequest2().getAncestors(); 54 | for (Ancestor anc : ancs) { 55 | if (anc.equals(ancs.get(ancs.size()-1))) { 56 | String uri = Stapler.getCurrentRequest2().getOriginalRequestURI(); 57 | if (uri.endsWith("confirmRename") || uri.endsWith("configSubmit")) { 58 | continue; 59 | } 60 | } 61 | 62 | Object o = anc.getObject(); 63 | if (o instanceof Folder) { 64 | String urlToAdd = ((Folder) o).getName(); 65 | resultUrl.append("job/"); 66 | resultUrl.append(Util.rawEncode(urlToAdd)); 67 | resultUrl.append("/"); 68 | } 69 | } 70 | 71 | String entityName = fullName.substring(fullName.lastIndexOf('/') + 1); 72 | resultUrl.append("job/"); 73 | resultUrl.append(Util.rawEncode(entityName)); 74 | resultUrl.append("/"); 75 | 76 | return resultUrl.toString(); 77 | } 78 | 79 | public String getCanonicalEventUrlNewLocation(Item item, String newFullName) { 80 | 81 | String jobName = newFullName.substring(newFullName.lastIndexOf('/') + 1); 82 | List urls_list = new ArrayList<>(); 83 | AbstractItem _item = (AbstractItem) item; 84 | while (_item.getParent() != null) { 85 | if (_item.getParent() instanceof Hudson) { 86 | break; 87 | } 88 | String _url = ((AbstractItem) _item.getParent()).getShortUrl(); 89 | urls_list.add(0, _url); 90 | _item = (AbstractItem) _item.getParent(); 91 | } 92 | 93 | return String.join("", urls_list) + item.getParent().getUrlChildPrefix() + '/' + Util.rawEncode(jobName) + '/'; 94 | } 95 | 96 | @Override 97 | public void onCreated(Item item) { 98 | eventSender.send(new Event.EventBuilder() 99 | .type("item.created") 100 | .source(item.getParent().getUrl()) 101 | .url(this.getCanonicalEventUrl(item.getName())) 102 | .data(item) 103 | .build()); 104 | } 105 | 106 | @Override 107 | public void onDeleted(Item item) { 108 | eventSender.send(new Event.EventBuilder() 109 | .type("item.deleted") 110 | .source(item.getParent().getUrl()) 111 | .url(this.getCanonicalEventUrl(item.getName())) 112 | .data(item) 113 | .build()); 114 | } 115 | 116 | @Override 117 | public void onUpdated(Item item) { 118 | eventSender.send(new Event.EventBuilder() 119 | .type("item.updated") 120 | .source(item.getParent().getUrl()) 121 | .url(this.getCanonicalEventUrl(item.getName())) 122 | .data(item) 123 | .build()); 124 | } 125 | 126 | @Override 127 | public void onLocationChanged(Item item, String oldFullName, String newFullName) { 128 | eventSender.send(new Event.EventBuilder() 129 | .type("item.locationChanged") 130 | .source(item.getParent().getUrl()) 131 | .data(item) 132 | .metaData(new MetaData.MetaDataBuilder() 133 | .oldName(oldFullName) 134 | .newName(newFullName) 135 | .oldUrl(this.getCanonicalEventUrl(oldFullName)) 136 | .newUrl(this.getCanonicalEventUrlNewLocation(item, newFullName)) 137 | .build()) 138 | .build()); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/listener/GenericEventRunListener.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.listener; 2 | 3 | import edu.umd.cs.findbugs.annotations.NonNull; 4 | import hudson.Extension; 5 | import hudson.model.Run; 6 | import hudson.model.TaskListener; 7 | import hudson.model.listeners.RunListener; 8 | import io.jenkins.plugins.generic.event.Event; 9 | import io.jenkins.plugins.generic.event.EventSender; 10 | import io.jenkins.plugins.generic.event.HttpEventSender; 11 | 12 | @Extension 13 | public class GenericEventRunListener extends RunListener> { 14 | 15 | private EventSender eventSender; 16 | 17 | public GenericEventRunListener() { 18 | this.setEventSender(new HttpEventSender()); 19 | } 20 | 21 | public void setEventSender(EventSender eventSender) { 22 | this.eventSender = eventSender; 23 | } 24 | 25 | @Override 26 | public void onCompleted(Run r, @NonNull TaskListener listener) { 27 | eventSender.send(new Event.EventBuilder() 28 | .type("run.completed") 29 | .source(r.getParent().getUrl()) 30 | .url(r.getUrl()) 31 | .data(r) 32 | .build()); 33 | } 34 | 35 | 36 | @Override 37 | public void onDeleted(Run r) { 38 | eventSender.send(new Event.EventBuilder() 39 | .type("run.deleted") 40 | .source(r.getParent().getUrl()) 41 | .url(r.getUrl()) 42 | .data(r) 43 | .build()); 44 | } 45 | 46 | @Override 47 | public void onFinalized(Run r) { 48 | eventSender.send(new Event.EventBuilder() 49 | .type("run.finalized") 50 | .source(r.getParent().getUrl()) 51 | .url(r.getUrl()) 52 | .data(r) 53 | .build()); 54 | } 55 | 56 | @Override 57 | public void onInitialize(Run r) { 58 | eventSender.send(new Event.EventBuilder() 59 | .type("run.initialize") 60 | .source(r.getParent().getUrl()) 61 | .url(r.getUrl()) 62 | .data(r) 63 | .build()); 64 | } 65 | 66 | @Override 67 | public void onStarted(Run r, TaskListener listener) { 68 | eventSender.send(new Event.EventBuilder() 69 | .type("run.started") 70 | .source(r.getParent().getUrl()) 71 | .url(r.getUrl()) 72 | .data(r) 73 | .build()); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/transformer/EnhancedData.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.transformer; 2 | 3 | import org.kohsuke.stapler.export.Exported; 4 | import org.kohsuke.stapler.export.ExportedBean; 5 | 6 | /** 7 | * EnhancedData has ability to merge raw data into current object. 8 | * 9 | * @param Type of raw data, must be annotated by @ExportedBean. 10 | * @author johnniang 11 | */ 12 | @ExportedBean 13 | public abstract class EnhancedData { 14 | 15 | @Exported(name = "raw", merge = true) 16 | public abstract RAW getRaw(); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/transformer/EventDataTransformer.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.transformer; 2 | 3 | /** 4 | * This interface is responsible for transforming object with specific type to 5 | * another structure. 6 | * 7 | * @author johnniang 8 | */ 9 | public interface EventDataTransformer { 10 | 11 | /** 12 | * Transform object with specific type to another structure. 13 | * 14 | * @param data object data to be transformed. 15 | * @return target object. 16 | */ 17 | Object transform(T data); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/jenkins/plugins/generic/event/transformer/EventDataTransformers.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.transformer; 2 | 3 | import io.jenkins.plugins.generic.event.Event; 4 | import io.jenkins.plugins.generic.event.data.WorkflowRunData; 5 | import net.jodah.typetools.TypeResolver; 6 | import org.jenkinsci.plugins.workflow.job.WorkflowRun; 7 | 8 | import java.lang.reflect.ParameterizedType; 9 | import java.lang.reflect.Type; 10 | import java.util.Collection; 11 | import java.util.Collections; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | /** 16 | * EventDataTransformers is a set of event data transformers and is responsible 17 | * for picking a proper transformer to transform an object. It also supports 18 | * transformer registering and unregistering. 19 | *

20 | * It's lazy-load and a singleton type. 21 | * 22 | * @author johnniang 23 | */ 24 | public enum EventDataTransformers { 25 | 26 | INSTANCE; 27 | 28 | private final Map> transformers; 29 | 30 | EventDataTransformers() { 31 | this.transformers = new HashMap<>(); 32 | register((EventDataTransformer) WorkflowRunData::new); 33 | // TODO register other event data transformers. 34 | } 35 | 36 | public void register(EventDataTransformer transformer) { 37 | transformers.put(getActualArgumentType(transformer), transformer); 38 | } 39 | 40 | public void unregister(EventDataTransformer transformer) { 41 | transformers.remove(getActualArgumentType(transformer), transformer); 42 | } 43 | 44 | public Collection> getAllTransformers() { 45 | return Collections.unmodifiableCollection(transformers.values()); 46 | } 47 | 48 | @SuppressWarnings({"rawtypes", "unchecked"}) 49 | public void transform(Event event) { 50 | if (event == null || event.getData() == null) { 51 | return; 52 | } 53 | EventDataTransformer transformer = transformers.get(event.getData().getClass()); 54 | if (transformer == null) { 55 | // if not transformer found, nothing need to do 56 | return; 57 | } 58 | Object transformedData = transformer.transform(event.getData()); 59 | event.setData(transformedData); 60 | } 61 | 62 | private Type getActualArgumentType(EventDataTransformer transformer) { 63 | return TypeResolver.resolveRawArgument(EventDataTransformer.class, transformer.getClass()); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/resources/index.jelly: -------------------------------------------------------------------------------- 1 | 2 |

3 | Allows users to receive events fired by system via webhook. 4 |
5 | -------------------------------------------------------------------------------- /src/main/resources/io/jenkins/plugins/generic/event/EventGlobalConfiguration/config.jelly: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/test/java/io/jenkins/plugins/generic/event/json/ExportedBeanProcessorTest.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.json; 2 | 3 | import net.sf.json.JSONException; 4 | import net.sf.json.JSONObject; 5 | import net.sf.json.JsonConfig; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.kohsuke.stapler.export.Exported; 10 | import org.kohsuke.stapler.export.ExportedBean; 11 | 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | 15 | public class ExportedBeanProcessorTest { 16 | 17 | private JsonConfig jsonConfig; 18 | 19 | @Before 20 | public void setUp() { 21 | jsonConfig = new EventJsonConfig(); 22 | } 23 | 24 | @Test 25 | public void serializeNullEntity() { 26 | Map entityMap = new HashMap<>(1); 27 | entityMap.put("entity", null); 28 | String json = JSONObject.fromObject(entityMap, jsonConfig).toString(); 29 | Assert.assertEquals("{\"entity\":null}", json); 30 | } 31 | 32 | @Test 33 | public void shouldIgnoreURLandName() { 34 | ExportedEntity entity = new ExportedEntity(18, "fake/url", "fake name"); 35 | String json = JSONObject.fromObject(entity, jsonConfig).toString(); 36 | Assert.assertEquals("{\"_class\":\"io.jenkins.plugins.generic.event.json.ExportedBeanProcessorTest$ExportedEntity\",\"age\":18}", json); 37 | } 38 | 39 | @Test 40 | public void shouldFallbackToNormalSerialization() { 41 | ExportedEntity entity = new ExportedEntity(-1, "fake/url", "fake name"); 42 | JSONException jsonException = Assert.assertThrows(JSONException.class, () -> JSONObject.fromObject(entity, jsonConfig)); 43 | Assert.assertEquals("Failed to serialize @Exported model", jsonException.getMessage()); 44 | // Get the root cause of the problem. Exception chain: JSONException <- IOException <- IllegalStateException. 45 | Throwable realCause = jsonException.getCause().getCause().getCause(); 46 | Assert.assertEquals(IllegalStateException.class, realCause.getClass()); 47 | Assert.assertEquals("Age must not be less than 1", realCause.getMessage()); 48 | } 49 | 50 | @ExportedBean 51 | public class ExportedEntity { 52 | 53 | private int age; 54 | 55 | private String url; 56 | 57 | private String name; 58 | 59 | public ExportedEntity(int age, String url, String name) { 60 | this.age = age; 61 | this.url = url; 62 | this.name = name; 63 | } 64 | 65 | @Exported 66 | public int getAge() { 67 | if (age <= 0) { 68 | throw new IllegalStateException("Age must not be less than 1"); 69 | } 70 | return age; 71 | } 72 | 73 | public String getName() { 74 | return name; 75 | } 76 | 77 | @Exported 78 | public String getUrl() { 79 | return url; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/io/jenkins/plugins/generic/event/json/InstantProcessorTest.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.json; 2 | 3 | import net.sf.json.JSONObject; 4 | import net.sf.json.JsonConfig; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import java.time.Instant; 10 | import java.time.ZoneId; 11 | import java.time.format.DateTimeFormatter; 12 | import java.time.temporal.TemporalAccessor; 13 | 14 | public class InstantProcessorTest { 15 | 16 | private JsonConfig jsonConfig; 17 | 18 | private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(InstantProcessor.DATE_FORMAT_STRING) 19 | .withZone(ZoneId.systemDefault()); 20 | 21 | private String format(TemporalAccessor temporal) { 22 | return formatter.format(temporal); 23 | } 24 | 25 | @Before 26 | public void setUp() { 27 | jsonConfig = new EventJsonConfig(); 28 | } 29 | 30 | @Test 31 | public void serializeNullInstant() { 32 | InstantBean instant = new InstantBean(null); 33 | String instantJSON = JSONObject.fromObject(instant, jsonConfig).toString(); 34 | Assert.assertEquals("{\"times\":[],\"time\":null}", instantJSON); 35 | } 36 | 37 | @Test 38 | public void shouldSerializeInstantCorrectly() { 39 | Instant time = Instant.parse("2022-01-14T06:49:30.00Z"); 40 | InstantBean instant = new InstantBean(time); 41 | String instantJSON = JSONObject.fromObject(instant, jsonConfig).toString(); 42 | 43 | Assert.assertEquals("{\"times\":[],\"time\":\""+format(time)+"\"}", instantJSON); 44 | } 45 | 46 | @Test 47 | public void shouldSerializeInstantArrayCorrectly() { 48 | Instant time = Instant.parse("2022-01-14T06:49:30.00Z"); 49 | InstantBean instant = new InstantBean(time); 50 | instant.setTimes(new Instant[]{time}); 51 | String instantJSON = JSONObject.fromObject(instant, jsonConfig).toString(); 52 | Assert.assertEquals("{\"times\":[\""+format(time)+"\"],\"time\":\""+format(time)+"\"}", instantJSON); 53 | } 54 | 55 | public static class InstantBean { 56 | private final Instant time; 57 | 58 | private Instant[] times; 59 | 60 | public InstantBean(Instant time) { 61 | this.time = time; 62 | } 63 | 64 | public Instant getTime() { 65 | return time; 66 | } 67 | 68 | public void setTimes(Instant[] times) { 69 | this.times = times; 70 | } 71 | 72 | public Instant[] getTimes() { 73 | return times; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/io/jenkins/plugins/generic/event/listener/ItemListenerTest.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.listener; 2 | 3 | import hudson.ExtensionList; 4 | import hudson.model.FreeStyleProject; 5 | import hudson.model.Item; 6 | import hudson.model.Items; 7 | import hudson.model.listeners.ItemListener; 8 | import io.jenkins.plugins.generic.event.Event; 9 | import io.jenkins.plugins.generic.event.EventGlobalConfiguration; 10 | import io.jenkins.plugins.generic.event.EventSender; 11 | import jenkins.model.JenkinsLocationConfiguration; 12 | import org.junit.Before; 13 | import org.junit.Rule; 14 | import org.junit.Test; 15 | import org.jvnet.hudson.test.JenkinsRule; 16 | import org.jvnet.hudson.test.MockFolder; 17 | import org.jvnet.hudson.test.TestExtension; 18 | import org.mockito.*; 19 | 20 | import static org.junit.Assert.*; 21 | import static org.mockito.ArgumentMatchers.any; 22 | import static org.mockito.Mockito.*; 23 | 24 | public class ItemListenerTest { 25 | 26 | @Rule public JenkinsRule r = new JenkinsRule(); 27 | 28 | @Mock 29 | EventSender mockSender; 30 | 31 | @Before 32 | public void setUp() { 33 | EventGlobalConfiguration config = EventGlobalConfiguration.get(); 34 | config.setReceiver("http://localhost:8000"); 35 | JenkinsLocationConfiguration.get().setUrl(null); 36 | 37 | MockitoAnnotations.openMocks(this); 38 | ExtensionList listeners = ExtensionList.lookup(GenericEventItemListener.class); 39 | listeners.forEach((listener) -> listener.setEventSender(mockSender)); 40 | } 41 | 42 | @Test public void renameFreeStyleJob() throws Exception { 43 | MockFolder folder = r.createFolder("folder"); 44 | FreeStyleProject project = folder.createProject(FreeStyleProject.class, "old-job-name"); 45 | assertNews("created=folder created=folder/old-job-name"); 46 | assertSame(r.jenkins.getItemByFullName("folder/old-job-name"), project); 47 | reset(mockSender); 48 | 49 | project.renameTo("new-job-name"); 50 | assertNews("renamed=folder/new-job-name;from=old-job-name moved=folder/new-job-name;from=folder/old-job-name"); 51 | verify(mockSender, times(1)).send(any(Event.class)); 52 | assertNull(r.jenkins.getItemByFullName("folder/old-job-name")); 53 | assertSame(r.jenkins.getItemByFullName("folder/new-job-name"), project); 54 | } 55 | 56 | @Test public void renameFolder() throws Exception { 57 | MockFolder folder = r.createFolder("folder"); 58 | MockFolder subFolder = folder.createProject(MockFolder.class, "old-subfolder"); 59 | assertNews("created=folder created=folder/old-subfolder"); 60 | assertSame(r.jenkins.getItemByFullName("folder/old-subfolder"), subFolder); 61 | reset(mockSender); 62 | 63 | subFolder.renameTo("new-subfolder"); 64 | assertNews("renamed=folder/new-subfolder;from=old-subfolder moved=folder/new-subfolder;from=folder/old-subfolder"); 65 | verify(mockSender, times(1)).send(any(Event.class)); 66 | assertNull(r.jenkins.getItemByFullName("folder/old-subfolder")); 67 | assertSame(r.jenkins.getItemByFullName("folder/new-subfolder"), subFolder); 68 | } 69 | 70 | @Test public void moveFreeStyleJob() throws Exception { 71 | 72 | MockFolder folder1 = r.createFolder("folder1"); 73 | MockFolder folder2 = r.createFolder("folder2"); 74 | FreeStyleProject project = folder1.createProject(FreeStyleProject.class, "freestyle-job"); 75 | assertNews("created=folder1 created=folder2 created=folder1/freestyle-job"); 76 | assertSame(r.jenkins.getItemByFullName("folder1/freestyle-job"), project); 77 | reset(mockSender); 78 | 79 | Items.move(project, folder2); 80 | assertNews("moved=folder2/freestyle-job;from=folder1/freestyle-job"); 81 | verify(mockSender, times(1)).send(any(Event.class)); 82 | assertNull(r.jenkins.getItemByFullName("folder1/freestyle-job")); 83 | assertSame(r.jenkins.getItemByFullName("folder2/freestyle-job"), project); 84 | } 85 | 86 | @Test public void moveFolder() throws Exception { 87 | 88 | MockFolder folder1 = r.createFolder("folder1"); 89 | MockFolder folder2 = r.createFolder("folder2"); 90 | MockFolder subFolder = folder1.createProject(MockFolder.class, "subfolder"); 91 | assertNews("created=folder1 created=folder2 created=folder1/subfolder"); 92 | assertSame(r.jenkins.getItemByFullName("folder1/subfolder"), subFolder); 93 | 94 | Items.move(subFolder, folder2); 95 | assertNews("moved=folder2/subfolder;from=folder1/subfolder"); 96 | verify(mockSender, times(4)).send(any(Event.class)); 97 | assertNull(r.jenkins.getItemByFullName("folder1/subfolder")); 98 | assertSame(r.jenkins.getItemByFullName("folder2/subfolder"), subFolder); 99 | } 100 | 101 | @Test public void deleteFreeStyleJobAndFolder() throws Exception { 102 | 103 | MockFolder folder = r.createFolder("folder"); 104 | FreeStyleProject project = folder.createProject(FreeStyleProject.class, "freestyle-job"); 105 | assertNews("created=folder created=folder/freestyle-job"); 106 | assertSame(r.jenkins.getItemByFullName("folder/freestyle-job"), project); 107 | reset(mockSender); 108 | 109 | project.delete(); 110 | assertNews("deleted=folder/freestyle-job"); 111 | verify(mockSender).send(any(Event.class)); 112 | assertNull(r.jenkins.getItemByFullName("folder/freestyle-job")); 113 | reset(mockSender); 114 | 115 | folder.delete(); 116 | assertNews("deleted=folder"); 117 | verify(mockSender, times(1)).send(any(Event.class)); 118 | assertNull(r.jenkins.getItemByFullName("folder")); 119 | } 120 | 121 | private void assertNews(String expected) { 122 | ItemListenerLogger extensionList = r.jenkins.getExtensionList(ItemListener.class).get(ItemListenerLogger.class); 123 | assertEquals(expected, extensionList.b.toString().trim()); 124 | extensionList.b.delete(0, extensionList.b.length()); 125 | } 126 | 127 | @TestExtension public static class ItemListenerLogger extends ItemListener { 128 | final StringBuilder b = new StringBuilder(); 129 | @Override public void onCreated(Item item) { 130 | b.append(" created=").append(item.getFullName()); 131 | } 132 | 133 | @Override public void onUpdated(Item item) { 134 | b.append(" updated=").append(item.getFullName()); 135 | } 136 | @Override public void onDeleted(Item item) { 137 | b.append(" deleted=").append(item.getFullName()); 138 | } 139 | @Override public void onRenamed(Item item, String oldName, String newName) { 140 | assertEquals(item.getName(), newName); 141 | b.append(" renamed=").append(item.getFullName()).append(";from=").append(oldName); 142 | } 143 | @Override public void onLocationChanged(Item item, String oldFullName, String newFullName) { 144 | assertEquals(item.getFullName(), newFullName); 145 | b.append(" moved=").append(newFullName).append(";from=").append(oldFullName); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/test/java/io/jenkins/plugins/generic/event/listener/RunListenerTest.java: -------------------------------------------------------------------------------- 1 | package io.jenkins.plugins.generic.event.listener; 2 | 3 | import com.cloudbees.hudson.plugins.folder.computed.FolderComputation; 4 | import hudson.ExtensionList; 5 | import hudson.model.*; 6 | import io.jenkins.plugins.generic.event.Event; 7 | import io.jenkins.plugins.generic.event.EventGlobalConfiguration; 8 | import io.jenkins.plugins.generic.event.EventSender; 9 | import jenkins.branch.BranchSource; 10 | import jenkins.model.JenkinsLocationConfiguration; 11 | import jenkins.plugins.git.GitBranchSCMHead; 12 | import jenkins.plugins.git.GitSCMSource; 13 | import jenkins.plugins.git.GitSampleRepoRule; 14 | import jenkins.scm.api.SCMHead; 15 | import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; 16 | import org.jenkinsci.plugins.workflow.job.WorkflowJob; 17 | import org.jenkinsci.plugins.workflow.job.WorkflowRun; 18 | import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; 19 | import org.junit.Before; 20 | import org.junit.ClassRule; 21 | import org.junit.Rule; 22 | import org.junit.Test; 23 | import org.jvnet.hudson.test.BuildWatcher; 24 | import org.jvnet.hudson.test.JenkinsRule; 25 | import org.jvnet.hudson.test.MockBuilder; 26 | import org.jvnet.hudson.test.MockFolder; 27 | import org.mockito.Mock; 28 | import org.mockito.MockitoAnnotations; 29 | 30 | import java.io.IOException; 31 | import java.util.Objects; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | import static org.junit.Assert.assertEquals; 35 | import static org.junit.Assert.fail; 36 | import static org.mockito.ArgumentMatchers.any; 37 | import static org.mockito.Mockito.*; 38 | 39 | public class RunListenerTest { 40 | 41 | private static final String JENKINSFILE = m( 42 | "pipeline {", 43 | " agent none", 44 | " stages {", 45 | " stage('Example') {", 46 | " steps {", 47 | " echo 'Hello World!'", 48 | " }", 49 | " }", 50 | " }", 51 | "}"); 52 | 53 | @ClassRule 54 | public static final BuildWatcher buildWatcher = new BuildWatcher(); 55 | 56 | @Rule 57 | public final JenkinsRule r = new JenkinsRule(); 58 | 59 | @Rule 60 | public final GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); 61 | 62 | @Mock 63 | EventSender mockSender; 64 | 65 | @Before 66 | public void setUp() { 67 | EventGlobalConfiguration config = EventGlobalConfiguration.get(); 68 | config.setReceiver("http://localhost:8000"); 69 | // simulate outside HTTP request 70 | JenkinsLocationConfiguration.get().setUrl(null); 71 | 72 | MockitoAnnotations.openMocks(this); 73 | ExtensionList listeners = ExtensionList.lookup(GenericEventRunListener.class); 74 | listeners.forEach((listener) -> listener.setEventSender(mockSender)); 75 | } 76 | 77 | @Test 78 | public void runSimplePipeline() throws Exception { 79 | doNothing().when(mockSender).send(any()); 80 | 81 | final WorkflowRun run = runPipeline(JENKINSFILE); 82 | 83 | r.assertBuildStatusSuccess(run); 84 | r.assertLogContains("Hello World!", run); 85 | // initialize, started, completed and finalized 86 | verify(mockSender, times(4)).send(any(Event.class)); 87 | } 88 | 89 | @Test 90 | public void runFreestyleProject() throws IOException, ExecutionException, InterruptedException { 91 | doNothing().when(mockSender).send(any()); 92 | 93 | FreeStyleProject project = r.createFreeStyleProject("my-freestyle-project"); 94 | project.getBuildersList().add(new MockBuilder(Result.SUCCESS)); 95 | FreeStyleBuild build = project.scheduleBuild2(0).waitForStart(); 96 | r.waitForCompletion(build); 97 | 98 | verify(mockSender, times(4)).send(any(Event.class)); 99 | } 100 | 101 | @Test 102 | public void runMultiBranchPipeline() throws Exception { 103 | doNothing().when(mockSender).send(any()); 104 | 105 | sampleRepo.init(); 106 | sampleRepo.write("Jenkinsfile", 107 | "echo \"branch=${env.BRANCH_NAME}\"; node {checkout scm; echo readFile('file')}"); 108 | sampleRepo.write("file", "initial content"); 109 | sampleRepo.git("add", "Jenkinsfile"); 110 | sampleRepo.git("commit", "--all", "--message=flow"); 111 | sampleRepo.git("checkout", "-b", "dev"); 112 | 113 | MockFolder folderProject = r.createFolder("my-devops-project"); 114 | WorkflowMultiBranchProject project = folderProject.createProject(WorkflowMultiBranchProject.class, "my-multi-branch-pipeline"); 115 | project.getSourcesList() 116 | .add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false))); 117 | project.getSCMSources().forEach(source -> assertEquals(project, source.getOwner())); 118 | 119 | Objects.requireNonNull(project.scheduleBuild2(0)).getFuture().get(); 120 | WorkflowJob branchProject = findBranchProject(project, "dev"); 121 | assertEquals(new GitBranchSCMHead("dev"), SCMHead.HeadByItem.findHead(branchProject)); 122 | assertEquals(2, project.getItems().size()); 123 | r.waitUntilNoActivity(); 124 | 125 | WorkflowRun lastRun = branchProject.getLastBuild(); 126 | r.assertLogContains("initial content", lastRun); 127 | r.assertLogContains("branch=dev", lastRun); 128 | 129 | verify(mockSender, times(8)).send(any(Event.class)); 130 | } 131 | 132 | private WorkflowJob findBranchProject(WorkflowMultiBranchProject project, String name) 133 | throws IOException, InterruptedException { 134 | WorkflowJob job = project.getItem(name); 135 | showIndexing(project); 136 | if (job == null) { 137 | fail(name + " project not found in " + project.getName()); 138 | } 139 | return job; 140 | } 141 | 142 | private void showIndexing(WorkflowMultiBranchProject project) throws IOException, InterruptedException { 143 | FolderComputation indexing = project.getIndexing(); 144 | System.out.println("---%<---" + indexing.getUrl()); 145 | indexing.writeWholeLogTo(System.out); 146 | System.out.println("---%>---"); 147 | } 148 | 149 | private WorkflowRun runPipeline(String definition) throws Exception { 150 | MockFolder folderProject = r.createFolder("my-devops-project"); 151 | WorkflowJob project = folderProject.createProject(WorkflowJob.class, "example-pipeline"); 152 | project.setDefinition(new CpsFlowDefinition(definition, true)); 153 | 154 | BooleanParameterDefinition skipDefinition = new BooleanParameterDefinition("skip", false, "Should we skip this step"); 155 | ParametersDefinitionProperty paramsDefProperty = new ParametersDefinitionProperty(skipDefinition); 156 | project.addProperty(paramsDefProperty); 157 | 158 | WorkflowRun run = Objects.requireNonNull(project.scheduleBuild2(0)).waitForStart(); 159 | r.waitForCompletion(run); 160 | return run; 161 | } 162 | 163 | private static String m(String... lines) { 164 | return String.join("\n", lines); 165 | } 166 | 167 | } 168 | --------------------------------------------------------------------------------