├── .gitignore ├── CHANGES.md ├── LICENSE ├── NOTICE.md ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── therapi-runtime-javadoc-scribe ├── build.gradle ├── gradle.properties └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── therapi │ │ │ └── runtimejavadoc │ │ │ └── scribe │ │ │ ├── JavadocAnnotationProcessor.java │ │ │ ├── JsonJavadocBuilder.java │ │ │ └── PackageFilter.java │ └── resources │ │ └── META-INF │ │ ├── license │ │ └── JavaPoet-LICENSE.txt │ │ └── services │ │ └── javax.annotation.processing.Processor │ └── test │ ├── java │ └── com │ │ └── github │ │ └── therapi │ │ └── runtimejavadoc │ │ ├── CompilationClassLoader.java │ │ └── JavadocAnnotationProcessorTest.java │ └── resources │ ├── DefaultPackageResident.java │ └── javasource │ ├── bar │ ├── AnotherDocumentedClass.java │ ├── BlankDocumentation.java │ ├── OnlyMethodDocumented.java │ ├── OverridingClassInAnotherPackage.java │ ├── UndocumentedClass.java │ └── YetAnotherDocumentedClass.java │ └── foo │ ├── ComplexEnum.java │ ├── ComplexImplementation.java │ ├── DocumentedClass.java │ ├── DocumentedEnum.java │ ├── DocumentedImplementation.java │ ├── DocumentedInterface.java │ ├── DocumentedRecord.java │ ├── OtherInterface.java │ ├── OverridingClass.java │ ├── OverridingClass2Degrees.java │ └── VeryComplexImplementation.java └── therapi-runtime-javadoc ├── build.gradle ├── gradle.properties └── src ├── main ├── java │ └── com │ │ └── github │ │ └── therapi │ │ └── runtimejavadoc │ │ ├── BaseJavadoc.java │ │ ├── ClassJavadoc.java │ │ ├── Comment.java │ │ ├── CommentElement.java │ │ ├── CommentFormatter.java │ │ ├── CommentText.java │ │ ├── CommentVisitor.java │ │ ├── FieldJavadoc.java │ │ ├── InlineLink.java │ │ ├── InlineTag.java │ │ ├── InlineValue.java │ │ ├── Link.java │ │ ├── MethodJavadoc.java │ │ ├── OtherJavadoc.java │ │ ├── ParamJavadoc.java │ │ ├── RetainJavadoc.java │ │ ├── RuntimeJavadoc.java │ │ ├── SeeAlsoJavadoc.java │ │ ├── ThrowsJavadoc.java │ │ ├── ToHtmlStringCommentVisitor.java │ │ ├── ToTextListCommentVisitor.java │ │ ├── Value.java │ │ └── internal │ │ ├── JsonJavadocReader.java │ │ ├── MethodSignature.java │ │ ├── RuntimeJavadocHelper.java │ │ └── parser │ │ ├── BlockTag.java │ │ ├── CommentParser.java │ │ ├── JavadocParser.java │ │ ├── LinkParser.java │ │ ├── ParsedJavadoc.java │ │ ├── SeeAlsoParser.java │ │ └── ThrowsTagParser.java └── resources │ └── META-INF │ └── license │ └── minimal-json-LICENSE.txt └── test └── java └── com └── github └── therapi └── runtimejavadoc ├── CommentFormatterTest.java ├── Example.java ├── ToTextListCommentVisitorTest.java └── internal └── parser ├── CommentParserTest.java └── ThrowsTagParserTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | # IntelliJ IDEA project files 15 | *.ipr 16 | *.iml 17 | .idea 18 | out 19 | /therapi-runtime-javadoc-scribe/build 20 | /therapi-runtime-javadoc/build 21 | 22 | .gradle 23 | 24 | # macOS filesystem metadata 25 | .DS_Store 26 | 27 | .project 28 | .classpath 29 | .settings/ 30 | target/ 31 | bin/ 32 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Change history 2 | 3 | ## 0.15.0 - July 23, 2022 4 | 5 | :bug: [#69](https://github.com/dnault/therapi-runtime-javadoc/issues/69) 6 | Fixed a regression in 0.14.0 where attempting to get Javadoc for a nested class would throw IllegalArgumentException. 7 | Thank you to yanxiyue for investigating the issue. 8 | 9 | :bug: [#70](https://github.com/dnault/therapi-runtime-javadoc/issues/70) 10 | Fixed a problem where classes with absolutely no Javadoc would not inherit 11 | method documentation. 12 | 13 | ## 0.14.0 - July 15, 2022 14 | 15 | :sparkles: [#61](https://github.com/dnault/therapi-runtime-javadoc/issues/61) 16 | Thanks to Sheikah45, methods without documentation now inherit documentation from superclass or implemented interface. 17 | 18 | ## 0.13.0 - January 1, 2022 19 | 20 | :sparkles: [#52](https://github.com/dnault/therapi-runtime-javadoc/issues/52) 21 | Added support for Java 16's record classes. 22 | Use the new `ClassJavadoc.getRecordComponents()` method to get `@param` tags 23 | from the class documentation / canonical constructor. 24 | 25 | :bug: [#50](https://github.com/dnault/therapi-runtime-javadoc/issues/50) 26 | `RuntimeJavadoc.getJavadoc(Method)` no longer fails when parameters have 27 | certain annotations. Also, the annotation names no longer leak into 28 | `MethodJavadoc.getParameterTypes()`. 29 | 30 | :bug: [#58](https://github.com/dnault/therapi-runtime-javadoc/issues/58) 31 | When constructor documentation is not found, the returned empty 32 | MethodJavadoc now has the correct method name of `` instead of 33 | the fully-qualified class name. 34 | 35 | :bug: [#59](https://github.com/dnault/therapi-runtime-javadoc/issues/59) 36 | `@see` tags in class documentation are now returned by 37 | `ClassJavadoc.getSeeAlso()` instead of `ClassJavadoc.getOther()`. 38 | 39 | :fire: [#57](https://github.com/dnault/therapi-runtime-javadoc/issues/57) 40 | Removed the duplicate repackaged version of minimal-json from the 41 | annotation processor JAR. Environments that complain about duplicate classes 42 | should be happier now. 43 | 44 | 45 | ### Breaking changes 46 | 47 | :arrow_up: [#56](https://github.com/dnault/therapi-runtime-javadoc/issues/56) Java 1.8 is now the minimum required version. 48 | 49 | :truck: Moved JavadocAnnotationProcessor to avoid split package between 50 | annotation processor and runtime library. The new fully-qualified name 51 | is `com.github.therapi.runtimejavadoc.scribe.JavadocAnnotationProcessor`. 52 | 53 | ## 0.12.0 - October 17, 2020 54 | 55 | Thanks to Chris Kirk (kirkch) for the improvements and fixes in this version. 56 | 57 | Issues resolved: 58 | 59 | :sparkles: [#48](https://github.com/dnault/therapi-runtime-javadoc/issues/48) Use visitor pattern for formatting comments 60 | 61 | :bug: [#21](https://github.com/dnault/therapi-runtime-javadoc/issues/21) @throws never parsed as ThrowsJavadoc 62 | 63 | :bug: [#41](https://github.com/dnault/therapi-runtime-javadoc/issues/41) Constructor javadoc is missing when there is no class level java doc 64 | 65 | :bug: [#43](https://github.com/dnault/therapi-runtime-javadoc/issues/43) @see on fields appears under other 66 | 67 | 68 | ## 0.11.0 - August 16, 2020 69 | 70 | Issues resolved: 71 | 72 | :sparkles: #37 Support reading constructor Javadoc 73 | 74 | :bug: [#36](https://github.com/dnault/therapi-runtime-javadoc/issues/36) Reader throws AssertionError when parsing malformed "see" tag 75 | 76 | :bug: [#38](https://github.com/dnault/therapi-runtime-javadoc/issues/38) Fix @code tag parsing 77 | 78 | ## 0.10.0 - July 19, 2020 79 | 80 | It's now possible to get the Javadoc of nested classes in the default package. 81 | 82 | Issues resolved: 83 | 84 | :bug: [#35](https://github.com/dnault/therapi-runtime-javadoc/issues/35) Can't get Javadoc for nested class in default package 85 | 86 | ## 0.9.0 - November 22, 2018 87 | 88 | Thanks to Benny Bottema, first class support for `@value` tags, and fixes for `@see` tags. 89 | 90 | ## 0.8.0 - October 3, 2018 91 | 92 | Thanks to Benny Bottema, method signatures in link tags are now parsed correctly. 93 | 94 | ### Deprecations 95 | 96 | The `isPresent()` method on Javadoc objects is deprecated in favor of 97 | `!isEmpty()`. 98 | 99 | 100 | ## 0.7.0 - September 1, 2018 101 | 102 | Thanks to Benny Bottema, now compatible with Java 7. 103 | 104 | ### BREAKING API CHANGE 105 | Public API methods that previously returned `Optional` now return `X`, 106 | always non-null. 107 | 108 | If the Javadoc is not available, the returned object will be a placeholder 109 | following the **Null Object Pattern**. A placeholder acts just a like a "real" 110 | `Class/Method/FieldDoc` object, but its methods return values that model 111 | absent Javadoc. 112 | 113 | If you need to distinguish a placeholder from a "real" 114 | documentation object, you can call the `isPresent()` method which always 115 | returns `false` for placeholders. 116 | 117 | Issues resolved: 118 | 119 | :sparkles: [#22](https://github.com/dnault/therapi-runtime-javadoc/issues/22) Make this available in Java 7 (Benny Bottema) 120 | 121 | 122 | ## 0.6.0 - May 3, 2018 123 | 124 | Thanks to Joffrey Bion, inline tags and links in comments are now parsed 125 | and presented as `InlineTag` and `InlineLink` comment elements. 126 | 127 | Issues resolved: 128 | 129 | :sparkles: [#17](https://github.com/dnault/therapi-runtime-javadoc/issues/17) Add links and tags elements to Comment (joffrey-bion) 130 | 131 | 132 | ## 0.5.0 - April 28, 2018 133 | 134 | Thanks to contributions from Joffrey Bion and Simon Kissane, 135 | it's now possible to read the Javadoc of fields and enum constants. 136 | 137 | Issues resolved: 138 | 139 | :sparkles: [#15](https://github.com/dnault/therapi-runtime-javadoc/issues/15) Add field and enum constants support (joffrey-bion, skissane) 140 | 141 | :bug: [#12](https://github.com/dnault/therapi-runtime-javadoc/issues/12) NullPointerException in RuntimeJavadoc due to null ClassLoader 142 | 143 | 144 | ## 0.4.0 - March 12, 2018 145 | 146 | Javadoc is now stored as class path resources instead of Java classes, 147 | yielding smaller JAR sizes. 148 | 149 | Issues resolved: 150 | 151 | :sparkles: [#10](https://github.com/dnault/therapi-runtime-javadoc/issues/10) Write Javadoc to class path resources instead of Java classes 152 | 153 | :sparkles: [#8](https://github.com/dnault/therapi-runtime-javadoc/issues/8) Don't generate companion class if there is no Javadoc 154 | 155 | 156 | ## 0.3.0 - March 11, 2018 157 | 158 | Javadoc for all classes is now retained by default. The `@RetainJavadoc` 159 | annotation is no longer required. 160 | 161 | Breaking changes: 162 | 163 | :truck: The annotation processor is now a separate artifact, 164 | `com.github.therapi:therapi-runtime-javadoc-scribe`. 165 | 166 | Issues resolved: 167 | 168 | :sparkles: [#7](https://github.com/dnault/therapi-runtime-javadoc/issues/7) Separate the annotation processor from the runtime library 169 | 170 | :sparkles: [#5](https://github.com/dnault/therapi-runtime-javadoc/issues/5) Provide RuntimeJavadoc.getJavadoc(Method) (Thanks @joffrey-bion!) 171 | 172 | :sparkles: [#4](https://github.com/dnault/therapi-runtime-javadoc/issues/4) Allow the use of a package whitelist instead of annotating on each class 173 | 174 | 175 | ## 0.2.1 - August 26, 2017 176 | 177 | :bug: [#3](https://github.com/dnault/therapi-runtime-javadoc/issues/3) ClassJavadoc.getName() should return the class name 178 | 179 | 180 | ## 0.2.0 - December 4, 2016 181 | 182 | :tada: Complete overhaul to use an annotation processor instead of a Gradle plugin. 183 | The new approach is compatible with Maven projects, and works when code is run 184 | directly from an IDE. 185 | 186 | 187 | ## 0.1.2 - March 13, 2016 188 | 189 | :bug: Fix reading Javadoc for inner classes. 190 | 191 | 192 | ## 0.1.1 - October 11, 2015 193 | 194 | :sparkles: Adds CommentFormatter to help convert comments to strings. 195 | 196 | 197 | ## 0.1.0 - October 10, 2015 198 | 199 | :tada: Initial release 200 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /NOTICE.md: -------------------------------------------------------------------------------- 1 | This software includes the following libraries, 2 | repackaged to avoid potential dependency conflicts: 3 | 4 | * [minimal-json](https://github.com/ralfstx/minimal-json) 5 | (MIT License) Copyright (c) 2013, 2014 EclipseSource 6 | 7 | * [JavaPoet](https://github.com/square/javapoet) 8 | (Apache 2.0 License) Copyright (c) 2015 Square, Inc. 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # therapi-runtime-javadoc 2 | 3 | ![Java 1.8+](https://img.shields.io/badge/java-1.8+-lightgray.svg) 4 | 5 | 6 | ## Bake Javadoc comments into your code 7 | 8 | 1. Add an annotation processor to your class path at compile time. 9 | 2. Read Javadoc comments at run time. 10 | 11 | The annotation processor copies Javadoc from your source code 12 | into class path resources. 13 | 14 | The runtime library reads the class path resources, serving up your 15 | Javadoc on demand. 16 | 17 | 18 | ## Coordinates 19 | 20 | ### Gradle 21 | 22 | ```groovy 23 | dependencies { 24 | annotationProcessor 'com.github.therapi:therapi-runtime-javadoc-scribe:0.13.0' 25 | 26 | // Runtime library 27 | implementation 'com.github.therapi:therapi-runtime-javadoc:0.13.0' 28 | } 29 | ``` 30 | 31 | ### Maven 32 | 33 | ```xml 34 | 35 | 36 | com.github.therapi 37 | therapi-runtime-javadoc-scribe 38 | 0.13.0 39 | provided 40 | 41 | 42 | 43 | 44 | com.github.therapi 45 | therapi-runtime-javadoc 46 | 0.13.0 47 | 48 | ``` 49 | 50 | 51 | ## Usage 52 | 53 | ### Building a JAR with embedded Javadoc 54 | 55 | Include the annotation processor JAR in your class path when compiling 56 | the code whose Javadoc you want to read later at runtime. 57 | 58 | When building in an IDE you may have to explicitly enable annotation processing. 59 | In IntelliJ this is done by going to 60 | `Preferences > Build, Execution, Deployment > Compiler > Annotation Processors` 61 | and checking the box labeled "Enable annotation processing". 62 | 63 | 64 | #### Selective Retention 65 | 66 | If you only want to retain the Javadoc from certain packages, use the 67 | `-A` javac argument to pass the `javadoc.packages` option to the annotation 68 | processor. The value is a comma-delimited list of packages whose Javadoc 69 | you want to keep. (Subpackages are included, recursively.) 70 | 71 | For Gradle that might look like this: 72 | 73 | ```groovy 74 | tasks.withType(JavaCompile) { 75 | options.compilerArgs << "-Ajavadoc.packages=com.example,org.example" 76 | } 77 | ``` 78 | 79 | If you don't specify any packages, the default behavior is to retain Javadoc 80 | from all packages. 81 | 82 | 83 | ### Reading Javadoc comments at runtime 84 | 85 | Add the runtime library as a dependency of your project. 86 | 87 | Read the Javadoc by calling `RuntimeJavadoc.getJavadoc` and passing a 88 | class literal, a fully-qualified class name, or a `java.lang.reflect.Method`. 89 | Because Javadoc comments may contain inline tags, you'll want to use a 90 | `CommentFormatter` to convert comments to strings. 91 | 92 | Here's an example that prints all available documentation for a class: 93 | 94 | ```java 95 | import com.github.therapi.runtimejavadoc.*; 96 | import java.io.IOException; 97 | 98 | public class Example { 99 | // formatters are reusable and thread-safe 100 | private static final CommentFormatter formatter = new CommentFormatter(); 101 | 102 | public static void printJavadoc(String fullyQualifiedClassName) throws IOException { 103 | ClassJavadoc classDoc = RuntimeJavadoc.getJavadoc(fullyQualifiedClassName); 104 | if (classDoc.isEmpty()) { // optionally skip absent documentation 105 | System.out.println("no documentation for " + fullyQualifiedClassName); 106 | return; 107 | } 108 | 109 | System.out.println(classDoc.getName()); 110 | System.out.println(format(classDoc.getComment())); 111 | System.out.println(); 112 | 113 | // @see tags 114 | for (SeeAlsoJavadoc see : classDoc.getSeeAlso()) { 115 | System.out.println("See also: " + see.getLink()); 116 | } 117 | // miscellaneous and custom javadoc tags (@author, etc.) 118 | for (OtherJavadoc other : classDoc.getOther()) { 119 | System.out.println(other.getName() + ": " + format(other.getComment())); 120 | } 121 | 122 | System.out.println(); 123 | System.out.println("CONSTRUCTORS"); 124 | for (MethodJavadoc methodDoc : classDoc.getConstructors()) { 125 | printMethodJavadoc(methodDoc); 126 | } 127 | 128 | System.out.println(); 129 | System.out.println("METHODS"); 130 | for (MethodJavadoc methodDoc : classDoc.getMethods()) { 131 | printMethodJavadoc(methodDoc); 132 | } 133 | } 134 | 135 | private static void printMethodJavadoc(MethodJavadoc methodDoc) { 136 | System.out.println(methodDoc.getName() + methodDoc.getParamTypes()); 137 | System.out.println(format(methodDoc.getComment())); 138 | 139 | if (!methodDoc.isConstructor()) { 140 | System.out.println(" returns " + format(methodDoc.getReturns())); 141 | } 142 | 143 | for (SeeAlsoJavadoc see : methodDoc.getSeeAlso()) { 144 | System.out.println(" See also: " + see.getLink()); 145 | } 146 | for (OtherJavadoc other : methodDoc.getOther()) { 147 | System.out.println(" " + other.getName() + ": " 148 | + format(other.getComment())); 149 | } 150 | for (ParamJavadoc paramDoc : methodDoc.getParams()) { 151 | System.out.println(" param " + paramDoc.getName() + " " 152 | + format(paramDoc.getComment())); 153 | } 154 | for (ThrowsJavadoc throwsDoc : methodDoc.getThrows()) { 155 | System.out.println(" throws " + throwsDoc.getName() + " " 156 | + format(throwsDoc.getComment())); 157 | } 158 | System.out.println(); 159 | } 160 | 161 | private static String format(Comment c) { 162 | return formatter.format(c); 163 | } 164 | } 165 | ``` 166 | 167 | ## License 168 | 169 | ``` 170 | Copyright 2015 David Nault and contributors 171 | 172 | Licensed under the Apache License, Version 2.0 (the "License"); 173 | you may not use this file except in compliance with the License. 174 | You may obtain a copy of the License at 175 | 176 | http://www.apache.org/licenses/LICENSE-2.0 177 | 178 | Unless required by applicable law or agreed to in writing, software 179 | distributed under the License is distributed on an "AS IS" BASIS, 180 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 181 | See the License for the specific language governing permissions and 182 | limitations under the License. 183 | ``` 184 | 185 | ## Notice 186 | 187 | This software includes the following libraries, 188 | repackaged to avoid potential dependency conflicts: 189 | 190 | * [minimal-json](https://github.com/ralfstx/minimal-json) 191 | (MIT License) Copyright (c) 2013, 2014 EclipseSource 192 | 193 | * [JavaPoet](https://github.com/square/javapoet) 194 | (Apache 2.0 License) Copyright (c) 2015 Square, Inc. 195 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.github.johnrengelman.shadow' version '7.1.2' 3 | } 4 | 5 | def compileJavaVersion = "8" 6 | def testJavaVersion = project.findProperty("testJavaVersion") ?: "17" 7 | def jvmVendor = null 8 | logger.lifecycle("Compiling for Java ${compileJavaVersion} and later, testing against Java ${testJavaVersion}") 9 | 10 | subprojects { 11 | apply plugin: 'java' 12 | apply plugin: 'maven-publish' 13 | apply plugin: 'signing' 14 | apply plugin: 'com.github.johnrengelman.shadow' 15 | 16 | group = "com.github.therapi" 17 | version = "0.16.0-SNAPSHOT" 18 | 19 | repositories { 20 | mavenCentral() 21 | } 22 | 23 | dependencies { 24 | testImplementation 'junit:junit:4.13.2' 25 | } 26 | 27 | java { 28 | withJavadocJar() 29 | withSourcesJar() 30 | 31 | toolchain { 32 | languageVersion = JavaLanguageVersion.of(compileJavaVersion) 33 | vendor = jvmVendor 34 | } 35 | } 36 | 37 | tasks.withType(Test) { 38 | testLogging.showStandardStreams = true 39 | javaLauncher = javaToolchains.launcherFor { 40 | languageVersion = JavaLanguageVersion.of(testJavaVersion) 41 | vendor = jvmVendor 42 | } 43 | } 44 | 45 | jar.enabled = false // interferes with shadow tasks 46 | 47 | shadowJar { 48 | archiveClassifier.set('') 49 | mergeServiceFiles() 50 | relocate 'com.eclipsesource.json', 'com.github.therapi.runtimejavadoc.repack.com.eclipsesource.json' 51 | } 52 | 53 | publishing { 54 | publications { 55 | mavenJava(MavenPublication) { publication -> 56 | project.shadow.component(publication) 57 | 58 | artifacts = [shadowJar, javadocJar, sourcesJar] 59 | 60 | pom { 61 | def githubProjectName = "therapi-runtime-javadoc" 62 | 63 | name = "${group}:${project.name}" 64 | description = project.description // defined in gradle.properties 65 | url = "https://github.com/dnault/${githubProjectName}" 66 | licenses { 67 | license { 68 | name = 'The Apache License, Version 2.0' 69 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 70 | } 71 | } 72 | developers { 73 | developer { 74 | id = 'dnault' 75 | name = 'David Nault' 76 | email = 'dnault@mac.com' 77 | organization = 'dnault' 78 | organizationUrl = 'https://github.com/dnault' 79 | } 80 | } 81 | scm { 82 | def gitUrl = "git@github.com:dnault/${githubProjectName}.git" 83 | 84 | connection = "scm:git:${gitUrl}" 85 | developerConnection = "scm:git:${gitUrl}" 86 | url = "${gitUrl}" 87 | } 88 | } 89 | } 90 | } 91 | 92 | repositories { 93 | maven { 94 | def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 95 | def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" 96 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 97 | 98 | credentials { 99 | // defined externally in gradle.properties 100 | username = project.properties["ossrhUsername"] 101 | password = project.properties["ossrhPassword"] 102 | } 103 | } 104 | } 105 | } 106 | 107 | signing { 108 | // Use GPG agent 109 | // https://docs.gradle.org/current/userguide/signing_plugin.html#sec:using_gpg_agent 110 | // Requires "signing.gnupg.keyName" property defined externally in gradle.properties 111 | useGpgCmd() 112 | 113 | sign publishing.publications.mavenJava 114 | } 115 | 116 | task install { 117 | dependsOn(publishToMavenLocal) 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dnault/therapi-runtime-javadoc/629fa89f4b264b61f046fee80357e3145d810a1d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'therapi-runtime-javadoc' 2 | 3 | include 'therapi-runtime-javadoc' 4 | include 'therapi-runtime-javadoc-scribe' 5 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | compileOnly files(System.properties['java.home'] + "/../lib/tools.jar") 3 | 4 | // relocated version is provided by the therapi-runtime-javadoc runtime library 5 | compileOnly 'com.eclipsesource.minimal-json:minimal-json:0.9.5' 6 | 7 | implementation 'com.squareup:javapoet:1.13.0' 8 | 9 | shadow project(':therapi-runtime-javadoc') 10 | 11 | testImplementation project(':therapi-runtime-javadoc') 12 | testImplementation 'com.google.testing.compile:compile-testing:0.19' 13 | } 14 | 15 | shadowJar { 16 | relocate 'com.squareup.javapoet', 'com.github.therapi.runtimejavadoc.scribe.repack.com.squareup.javapoet' 17 | } 18 | 19 | tasks.withType(JavaCompile) { 20 | // disable annotation processing 21 | options.compilerArgs << "-proc:none" 22 | } 23 | 24 | compileJava.dependsOn(":therapi-runtime-javadoc:shadowJar") 25 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/gradle.properties: -------------------------------------------------------------------------------- 1 | description = Annotation processor that bakes Javadoc comments into your code so they can be accessed at runtime. 2 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/main/java/com/github/therapi/runtimejavadoc/scribe/JavadocAnnotationProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.scribe; 18 | 19 | import com.eclipsesource.json.JsonObject; 20 | import com.github.therapi.runtimejavadoc.RetainJavadoc; 21 | 22 | import javax.annotation.processing.AbstractProcessor; 23 | import javax.annotation.processing.RoundEnvironment; 24 | import javax.lang.model.SourceVersion; 25 | import javax.lang.model.element.Element; 26 | import javax.lang.model.element.ElementKind; 27 | import javax.lang.model.element.PackageElement; 28 | import javax.lang.model.element.TypeElement; 29 | import javax.tools.Diagnostic; 30 | import javax.tools.FileObject; 31 | import javax.tools.StandardLocation; 32 | import java.io.IOException; 33 | import java.io.OutputStream; 34 | import java.util.Collections; 35 | import java.util.EnumSet; 36 | import java.util.HashSet; 37 | import java.util.Map; 38 | import java.util.Optional; 39 | import java.util.Set; 40 | 41 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.javadocResourceSuffix; 42 | import static java.nio.charset.StandardCharsets.UTF_8; 43 | 44 | public class JavadocAnnotationProcessor extends AbstractProcessor { 45 | 46 | private static final String PACKAGES_OPTION = "javadoc.packages"; 47 | 48 | private JsonJavadocBuilder jsonJavadocBuilder; 49 | 50 | @Override 51 | public boolean process(Set annotations, RoundEnvironment roundEnvironment) { 52 | this.jsonJavadocBuilder = new JsonJavadocBuilder(processingEnv); 53 | 54 | final Map options = processingEnv.getOptions(); 55 | final String packagesOption = options.get(PACKAGES_OPTION); 56 | 57 | // Retain Javadoc for classes that match this predicate 58 | final PackageFilter packageFilter = 59 | packagesOption == null ? new PackageFilter() : new PackageFilter(packagesOption); 60 | 61 | // Make sure each element only gets processed once. 62 | final Set alreadyProcessed = new HashSet<>(); 63 | 64 | // If retaining Javadoc for all packages, the @RetainJavadoc annotation is redundant. 65 | // Otherwise, make sure annotated classes have their Javadoc retained regardless of package. 66 | if (!packageFilter.allowAllPackages()) { 67 | for (TypeElement annotation : annotations) { 68 | if (isRetainJavadocAnnotation(annotation)) { 69 | for (Element e : roundEnvironment.getElementsAnnotatedWith(annotation)) { 70 | generateJavadoc(e, alreadyProcessed); 71 | } 72 | } 73 | } 74 | } 75 | 76 | for (Element e : roundEnvironment.getRootElements()) { 77 | if (packageFilter.test(e)) { 78 | generateJavadoc(e, alreadyProcessed); 79 | } 80 | } 81 | 82 | return false; 83 | } 84 | 85 | private static boolean isRetainJavadocAnnotation(TypeElement annotation) { 86 | return annotation.getQualifiedName().toString().equals(RetainJavadoc.class.getName()) 87 | || annotation.getAnnotation(RetainJavadoc.class) != null; 88 | } 89 | 90 | private static > Optional findValueOf(Class enumClass, String valueName) { 91 | try { 92 | return Optional.of(Enum.valueOf(enumClass, valueName)); 93 | } catch (IllegalArgumentException e) { 94 | return Optional.empty(); 95 | } 96 | } 97 | 98 | // ElementKind.RECORD was added in Java 16. We want to process records, but also 99 | // remain compatible with earlier Java versions. 100 | @SuppressWarnings("OptionalUsedAsFieldOrParameterType") 101 | static final Optional RECORD = findValueOf(ElementKind.class, "RECORD"); 102 | 103 | private static final EnumSet elementKindsToInspect = EnumSet.of( 104 | ElementKind.CLASS, 105 | ElementKind.INTERFACE, 106 | ElementKind.ENUM 107 | // and RECORD, but only if the Java version supports it 108 | ); 109 | 110 | static { 111 | RECORD.ifPresent(elementKindsToInspect::add); 112 | } 113 | 114 | private void generateJavadoc(Element element, Set alreadyProcessed) { 115 | ElementKind kind = element.getKind(); 116 | if (elementKindsToInspect.contains(kind)) { 117 | try { 118 | generateJavadocForClass(element, alreadyProcessed); 119 | } catch (Exception ex) { 120 | processingEnv.getMessager() 121 | .printMessage(Diagnostic.Kind.ERROR, "Javadoc retention failed; " + ex, element); 122 | throw new RuntimeException("Javadoc retention failed for " + element, ex); 123 | } 124 | } 125 | 126 | for (Element enclosed : element.getEnclosedElements()) { 127 | generateJavadoc(enclosed, alreadyProcessed); 128 | } 129 | } 130 | 131 | private void generateJavadocForClass(Element element, Set alreadyProcessed) throws IOException { 132 | if (!alreadyProcessed.add(element)) { 133 | return; 134 | } 135 | TypeElement classElement = (TypeElement) element; 136 | JsonObject maybeClassJsonDoc = jsonJavadocBuilder.getClassJavadocAsJsonOrNull(classElement); 137 | if (maybeClassJsonDoc != null) { 138 | outputJsonDoc(classElement, maybeClassJsonDoc); 139 | } 140 | } 141 | 142 | private void outputJsonDoc(TypeElement classElement, JsonObject classJsonDoc) throws IOException { 143 | String jsonString = classJsonDoc.toString(); 144 | FileObject resource = createJavadocResourceFile(classElement); 145 | try (OutputStream os = resource.openOutputStream()) { 146 | os.write(jsonString.getBytes(UTF_8)); 147 | } 148 | } 149 | 150 | private FileObject createJavadocResourceFile(TypeElement classElement) throws IOException { 151 | PackageElement packageElement = getPackageElement(classElement); 152 | String packageName = packageElement.getQualifiedName().toString(); 153 | String relativeName = getClassName(classElement) + javadocResourceSuffix(); 154 | return processingEnv.getFiler() 155 | .createResource(StandardLocation.CLASS_OUTPUT, packageName, relativeName, classElement); 156 | } 157 | 158 | private static PackageElement getPackageElement(Element element) { 159 | if (element instanceof PackageElement) { 160 | return (PackageElement) element; 161 | } 162 | return getPackageElement(element.getEnclosingElement()); 163 | } 164 | 165 | private static String getClassName(TypeElement typeElement) { 166 | // we can't take the simple name if we want to return names like EnclosingClass$NestedClass 167 | String typeName = typeElement.getQualifiedName().toString(); 168 | String packageName = getPackageElement(typeElement).getQualifiedName().toString(); 169 | 170 | if (!packageName.isEmpty()) { 171 | typeName = typeName.substring(packageName.length() + 1); 172 | } 173 | 174 | // for nested classes 175 | typeName = typeName.replace(".", "$"); 176 | 177 | return typeName; 178 | } 179 | 180 | @Override 181 | public SourceVersion getSupportedSourceVersion() { 182 | return SourceVersion.latestSupported(); 183 | } 184 | 185 | @Override 186 | public Set getSupportedAnnotationTypes() { 187 | return Collections.singleton("*"); 188 | } 189 | 190 | @Override 191 | public Set getSupportedOptions() { 192 | return Collections.singleton(PACKAGES_OPTION); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/main/java/com/github/therapi/runtimejavadoc/scribe/JsonJavadocBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.scribe; 18 | 19 | import com.eclipsesource.json.Json; 20 | import com.eclipsesource.json.JsonArray; 21 | import com.eclipsesource.json.JsonObject; 22 | import com.squareup.javapoet.TypeName; 23 | 24 | import javax.annotation.processing.ProcessingEnvironment; 25 | import javax.lang.model.element.Element; 26 | import javax.lang.model.element.ElementKind; 27 | import javax.lang.model.element.ExecutableElement; 28 | import javax.lang.model.element.TypeElement; 29 | import javax.lang.model.element.VariableElement; 30 | import javax.lang.model.type.TypeMirror; 31 | import javax.lang.model.util.Types; 32 | import java.util.ArrayList; 33 | import java.util.Collections; 34 | import java.util.HashMap; 35 | import java.util.List; 36 | import java.util.Map; 37 | 38 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.constructorsFieldName; 39 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.elementDocFieldName; 40 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.elementNameFieldName; 41 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.enumConstantsFieldName; 42 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.fieldsFieldName; 43 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.isBlank; 44 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.methodsFieldName; 45 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.paramTypesFieldName; 46 | import static javax.lang.model.element.ElementKind.CONSTRUCTOR; 47 | import static javax.lang.model.element.ElementKind.ENUM_CONSTANT; 48 | import static javax.lang.model.element.ElementKind.FIELD; 49 | import static javax.lang.model.element.ElementKind.METHOD; 50 | 51 | class JsonJavadocBuilder { 52 | 53 | private final ProcessingEnvironment processingEnv; 54 | 55 | JsonJavadocBuilder(ProcessingEnvironment processingEnv) { 56 | this.processingEnv = processingEnv; 57 | } 58 | 59 | JsonObject getClassJavadocAsJsonOrNull(TypeElement classElement) { 60 | String classDoc = processingEnv.getElementUtils().getDocComment(classElement); 61 | 62 | if (isBlank(classDoc)) { 63 | classDoc = ""; 64 | } 65 | 66 | Map> children = new HashMap<>(); 67 | for (Element enclosedElement : classElement.getEnclosedElements()) { 68 | children.computeIfAbsent(enclosedElement.getKind(), k -> new ArrayList<>()) 69 | .add(enclosedElement); 70 | } 71 | 72 | final List emptyList = Collections.emptyList(); 73 | List enclosedFields = defaultIfNull(children.get(FIELD), emptyList); 74 | List enclosedEnumConstants = defaultIfNull(children.get(ENUM_CONSTANT), emptyList); 75 | List enclosedMethods = defaultIfNull(children.get(METHOD), emptyList); 76 | List enclosedConstructors = defaultIfNull(children.get(CONSTRUCTOR), emptyList); 77 | 78 | JsonArray fieldDocs = getJavadocsAsJson(enclosedFields, new FieldJavadocAsJson()); 79 | JsonArray enumConstantDocs = getJavadocsAsJson(enclosedEnumConstants, new FieldJavadocAsJson()); 80 | JsonArray methodDocs = getJavadocsAsJson(enclosedMethods, new MethodJavadocAsJson()); 81 | JsonArray constructorDocs = getJavadocsAsJson(enclosedConstructors, new MethodJavadocAsJson()); 82 | 83 | if (isBlank(classDoc) && fieldDocs.isEmpty() && enumConstantDocs.isEmpty() && methodDocs.isEmpty() && constructorDocs.isEmpty()) { 84 | return null; 85 | } 86 | 87 | JsonObject json = new JsonObject(); 88 | json.add(elementDocFieldName(), classDoc); 89 | json.add(fieldsFieldName(), fieldDocs); 90 | json.add(enumConstantsFieldName(), enumConstantDocs); 91 | json.add(methodsFieldName(), methodDocs); 92 | json.add(constructorsFieldName(), constructorDocs); 93 | return json; 94 | } 95 | 96 | private static JsonArray getJavadocsAsJson(List elements, ElementToJsonFunction createDoc) { 97 | JsonArray jsonArray = new JsonArray(); 98 | for (Element e : elements) { 99 | JsonObject eMapped = createDoc.apply(e); 100 | if (eMapped != null) { 101 | jsonArray.add(eMapped); 102 | } 103 | } 104 | return jsonArray; 105 | } 106 | 107 | private interface ElementToJsonFunction { 108 | // nullable 109 | JsonObject apply(Element e); 110 | } 111 | 112 | private class FieldJavadocAsJson implements ElementToJsonFunction { 113 | @Override 114 | public JsonObject apply(Element field) { 115 | String javadoc = processingEnv.getElementUtils().getDocComment(field); 116 | if (isBlank(javadoc)) { 117 | return null; 118 | } 119 | 120 | JsonObject jsonDoc = new JsonObject(); 121 | jsonDoc.add(elementNameFieldName(), field.getSimpleName().toString()); 122 | jsonDoc.add(elementDocFieldName(), javadoc); 123 | return jsonDoc; 124 | } 125 | } 126 | 127 | private class MethodJavadocAsJson implements ElementToJsonFunction { 128 | @Override 129 | public JsonObject apply(Element method) { 130 | assert method instanceof ExecutableElement; 131 | 132 | String methodJavadoc = processingEnv.getElementUtils().getDocComment(method); 133 | if (isBlank(methodJavadoc)) { 134 | return null; 135 | } 136 | 137 | JsonObject jsonDoc = new JsonObject(); 138 | jsonDoc.add(elementNameFieldName(), method.getSimpleName().toString()); 139 | jsonDoc.add(paramTypesFieldName(), getParamErasures((ExecutableElement) method)); 140 | jsonDoc.add(elementDocFieldName(), methodJavadoc); 141 | return jsonDoc; 142 | } 143 | } 144 | 145 | private JsonArray getParamErasures(ExecutableElement executableElement) { 146 | Types typeUtils = processingEnv.getTypeUtils(); 147 | 148 | final JsonArray jsonValues = new JsonArray(); 149 | for (VariableElement parameter : executableElement.getParameters()) { 150 | TypeMirror erasure = typeUtils.erasure(parameter.asType()); 151 | String typeName = TypeName.get(erasure).withoutAnnotations().toString(); 152 | jsonValues.add(Json.value(typeName)); 153 | } 154 | return jsonValues; 155 | } 156 | 157 | private static T defaultIfNull(T actualValue, T defaultValue) { 158 | return actualValue != null ? actualValue : defaultValue; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/main/java/com/github/therapi/runtimejavadoc/scribe/PackageFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.scribe; 18 | 19 | import javax.lang.model.element.Element; 20 | import javax.lang.model.element.ElementKind; 21 | import javax.lang.model.element.QualifiedNameable; 22 | import java.util.HashSet; 23 | import java.util.Set; 24 | 25 | class PackageFilter { 26 | 27 | private final Set rootPackages = new HashSet<>(); 28 | private final Set packages = new HashSet<>(); 29 | private final Set negatives = new HashSet<>(); 30 | 31 | PackageFilter() { 32 | // leaves the package white-list empty, which implies it can be ignore 33 | } 34 | 35 | PackageFilter(String commaDelimitedPackages) { 36 | for (String pkg : commaDelimitedPackages.split(",")) { 37 | pkg = pkg.trim(); 38 | if (!pkg.isEmpty()) { 39 | rootPackages.add(pkg); 40 | } 41 | } 42 | packages.addAll(rootPackages); 43 | } 44 | 45 | public boolean test(Element element) { 46 | final String elementPackage = getPackage(element); 47 | 48 | if (negatives.contains(elementPackage)) { 49 | return false; 50 | } 51 | 52 | if (packages.isEmpty() || packages.contains(elementPackage)) { 53 | return true; 54 | } 55 | 56 | for (String p : rootPackages) { 57 | if (elementPackage.startsWith(p + ".")) { 58 | // Element's package is a subpackage of an included package. 59 | packages.add(elementPackage); 60 | return true; 61 | } 62 | } 63 | 64 | negatives.add(elementPackage); 65 | return false; 66 | } 67 | 68 | private static String getPackage(Element e) { 69 | while (e.getKind() != ElementKind.PACKAGE) { 70 | e = e.getEnclosingElement(); 71 | if (e == null) { 72 | return ""; 73 | } 74 | } 75 | return ((QualifiedNameable) e).getQualifiedName().toString(); 76 | } 77 | 78 | boolean allowAllPackages() { 79 | return packages.isEmpty(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/main/resources/META-INF/license/JavaPoet-LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2015 Square, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/main/resources/META-INF/services/javax.annotation.processing.Processor: -------------------------------------------------------------------------------- 1 | com.github.therapi.runtimejavadoc.scribe.JavadocAnnotationProcessor -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/java/com/github/therapi/runtimejavadoc/CompilationClassLoader.java: -------------------------------------------------------------------------------- 1 | package com.github.therapi.runtimejavadoc; 2 | 3 | import static javax.tools.StandardLocation.CLASS_OUTPUT; 4 | 5 | import javax.tools.JavaFileObject; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.net.MalformedURLException; 9 | import java.net.URI; 10 | import java.net.URL; 11 | import java.net.URLClassLoader; 12 | import java.net.URLConnection; 13 | import java.net.URLStreamHandler; 14 | 15 | import com.google.common.io.ByteStreams; 16 | import com.google.testing.compile.Compilation; 17 | 18 | public class CompilationClassLoader extends URLClassLoader { 19 | private final Compilation compilation; 20 | 21 | public CompilationClassLoader(Compilation compilation) { 22 | super(new URL[]{}); 23 | this.compilation = compilation; 24 | } 25 | 26 | @Override 27 | protected Class findClass(final String name) throws ClassNotFoundException { 28 | String path = name.replace(".", "/") + ".class"; 29 | JavaFileObject generatedClass = compilation.generatedFile(CLASS_OUTPUT, path).orElse(null); 30 | if (generatedClass == null) { 31 | return super.findClass(name); 32 | } 33 | 34 | try (InputStream is = generatedClass.openInputStream()) { 35 | byte[] classBytes = ByteStreams.toByteArray(is); 36 | return defineClass(name, classBytes, 0, classBytes.length); 37 | } catch (IOException e) { 38 | throw new RuntimeException(e); 39 | } 40 | } 41 | 42 | @Override 43 | public URL findResource(String name) { 44 | final JavaFileObject generatedResource = compilation.generatedFile(CLASS_OUTPUT, name).orElse(null); 45 | if (generatedResource == null) { 46 | return super.findResource(name); 47 | } 48 | try { 49 | URI uri = generatedResource.toUri(); 50 | return new URL("compilation", "", -1, uri.getPath(), new URLStreamHandler() { 51 | @Override 52 | protected URLConnection openConnection(URL u) throws IOException { 53 | return new URLConnection(u) { 54 | @Override 55 | public void connect() throws IOException { 56 | connected = true; 57 | } 58 | 59 | @Override 60 | public InputStream getInputStream() throws IOException { 61 | return generatedResource.openInputStream(); 62 | } 63 | }; 64 | } 65 | }); 66 | } catch (MalformedURLException e) { 67 | // Should never happen, since no validation is performed when stream handler is provided. 68 | throw new RuntimeException(e); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/DefaultPackageResident.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Hi, I live in the default package 3 | */ 4 | public class DefaultPackageResident { 5 | /** 6 | * Hi, I'm an inner class of a class in the default package. 7 | */ 8 | public class Nested { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/AnotherDocumentedClass.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | /** 4 | * Hi, I'm another documented class. 5 | */ 6 | public class AnotherDocumentedClass { 7 | } 8 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/BlankDocumentation.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | /** 4 | * 5 | */ 6 | public class BlankDocumentation { 7 | /** 8 | * 9 | */ 10 | public void foo() { 11 | } 12 | 13 | public static class NestedBlankBlankSubclass extends BlankDocumentation { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/OnlyMethodDocumented.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | // I don't have any class doc... 4 | public class OnlyMethodDocumented { 5 | /** 6 | * But I have a documented method! 7 | */ 8 | public void foo() { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/OverridingClassInAnotherPackage.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | import java.util.List; 4 | import javasource.foo.DocumentedClass; 5 | 6 | 7 | // I override methods of DocumentedClass with and without their own javadoc 8 | public class OverridingClassInAnotherPackage extends DocumentedClass { 9 | 10 | /** 11 | * Quick frobulate {@code a} by {@code b} using thin frobulation 12 | */ 13 | public int frobulate(String a, int b) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | // I have no javadoc of my own 18 | public int frobulate(String a, List b) { 19 | throw new UnsupportedOperationException(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/UndocumentedClass.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | // I don't have any Javadoc. Woe is me! 4 | public class UndocumentedClass { 5 | public void foo() { 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/bar/YetAnotherDocumentedClass.java: -------------------------------------------------------------------------------- 1 | package javasource.bar; 2 | 3 | import com.github.therapi.runtimejavadoc.RetainJavadoc; 4 | 5 | /** 6 | * I'm special because I'm annotated with {@link RetainJavadoc}. 7 | */ 8 | @RetainJavadoc 9 | public class YetAnotherDocumentedClass { 10 | } 11 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/ComplexEnum.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | /** 4 | * Hi, I'm a complex enum with fields. 5 | */ 6 | public enum ComplexEnum { 7 | 8 | /** 9 | * This is the FOO11 value documentation 10 | */ 11 | FOO11("test1"), 12 | /** 13 | * This is the BAR22 value documentation 14 | */ 15 | BAR22("test2"), 16 | /** 17 | * This is the BAZ33 value documentation 18 | */ 19 | BAZ33("test3"); 20 | 21 | /** 22 | * Content field description. 23 | */ 24 | private final String content; 25 | 26 | private ComplexEnum(String content) { 27 | this.content = content; 28 | } 29 | 30 | public String getContent() { 31 | return content; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/ComplexImplementation.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import javasource.foo.OtherInterface; 4 | import javasource.foo.DocumentedInterface; 5 | 6 | public class ComplexImplementation implements DocumentedInterface, OtherInterface { 7 | // I have no javadoc of my own 8 | public boolean hoodwink(String i) { 9 | throw new UnsupportedOperationException(); 10 | } 11 | 12 | // I have no javadoc of my own 13 | public boolean snaggle(String i) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | public boolean fling(Integer v) { 18 | throw new UnsupportedOperationException(); 19 | } 20 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/DocumentedClass.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * The {@code Javadoc} from this class is used for testing 7 | * 8 | * @author nobody@example.com 9 | * @custom.tag What does {@custom.inline this} mean? 10 | */ 11 | 12 | public class DocumentedClass { 13 | 14 | /** 15 | * I'm a useful field, maybe. 16 | * 17 | * @see #frobulate(String, int) interesting method, but nothing to do with this field 18 | */ 19 | private int myField; 20 | 21 | /** 22 | * I'm a field my children can see. 23 | */ 24 | protected int ourField; 25 | 26 | /** 27 | * I'm a constructor! 28 | */ 29 | public DocumentedClass() { 30 | } 31 | 32 | /** 33 | * I'm another constructor! 34 | * 35 | * @param ignore I'm a parameter! 36 | */ 37 | public DocumentedClass(String ignore) { 38 | } 39 | 40 | // I am undocumented! 41 | public DocumentedClass(Integer ignore) { 42 | } 43 | 44 | /** 45 | * Frobulate {@code a} by {@code b} 46 | * 47 | * @param a blurtification factor 48 | * @param b oopsifizzle constant 49 | * @return {@code a} frobulated by {@code b} 50 | * @throws UnsupportedOperationException if frobulation cannot be performed 51 | * @see com.github.therapi.runtimejavadoc.DocumentedClass Hey, that's this class! 52 | * @see #someOtherMethod() 53 | * @see "Moomoo boy went straight to Moomoo land. Land of the moomoo's" 54 | * @see Moomoo land 55 | */ 56 | public int frobulate(String a, int b) { 57 | throw new UnsupportedOperationException(); 58 | } 59 | 60 | /** 61 | * Frobulate {@code a} by multiple oopsifizzle constants 62 | * 63 | * @param a blurtification factor 64 | * @param b oopsifizzle constants 65 | * @return {@code a} frobulated by {@code b} 66 | * @throws UnsupportedOperationException if frobulation cannot be performed 67 | * @see com.github.therapi.runtimejavadoc.DocumentedClass Hey, that's this class! 68 | * @see #someOtherMethod() 69 | * @see "Moomoo boy went straight to Moomoo land. Land of the moomoo's" 70 | * @see Moomoo land 71 | */ 72 | public int frobulate(String a, List b) { 73 | throw new UnsupportedOperationException(); 74 | } 75 | 76 | public void someOtherMethod() { 77 | 78 | } 79 | 80 | /** 81 | * I am a simple method 82 | * 83 | * @throws UnsupportedOperationException if cannot skip 84 | */ 85 | public void skipMethod() throws UnsupportedOperationException { 86 | throw new UnsupportedOperationException(); 87 | } 88 | 89 | /** 90 | * Foo {@link Foo#bar(String).}{@value Foo#bar(String).} 91 | * 92 | * @see Foo#bar(String). 93 | */ 94 | public void malformedLinks() { 95 | } 96 | 97 | /** 98 | * Generic method to do generic things 99 | */ 100 | public T genericMethod(T generic) { 101 | return generic; 102 | } 103 | 104 | /** 105 | * Generic method to do run things 106 | */ 107 | public T skipGenericMethod(T generic) { 108 | return generic; 109 | } 110 | 111 | /** 112 | * Generic method to do other things 113 | */ 114 | public > T separateGeneric(U otherGeneric) { 115 | throw new UnsupportedOperationException(); 116 | } 117 | 118 | public T blankGenericMethod() { 119 | throw new UnsupportedOperationException(); 120 | } 121 | 122 | public boolean equals(Object o) { 123 | return super.equals(o); 124 | } 125 | 126 | /** 127 | * I'm a nested class! 128 | */ 129 | public static class Nested { 130 | } 131 | 132 | public static class NestedWithoutJavadoc { 133 | } 134 | 135 | public static class NestedSubclassWithoutJavadoc extends DocumentedClass { 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/DocumentedEnum.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | /** 4 | * Hi, I'm a documented enum. 5 | */ 6 | public enum DocumentedEnum { 7 | 8 | /** 9 | * This is the FOO11 value documentation 10 | */ 11 | FOO11, 12 | /** 13 | * This is the BAR22 value documentation 14 | */ 15 | BAR22, 16 | /** 17 | * This is the BAZ33 value documentation 18 | */ 19 | BAZ33; 20 | } 21 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/DocumentedImplementation.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import javasource.foo.DocumentedInterface; 4 | 5 | public class DocumentedImplementation implements DocumentedInterface { 6 | /** 7 | * hoodwink a stranger 8 | */ 9 | public boolean hoodwink(String i) { 10 | throw new UnsupportedOperationException(); 11 | } 12 | 13 | // I have no javadoc of my own 14 | public boolean snaggle(String i) { 15 | throw new UnsupportedOperationException(); 16 | } 17 | 18 | /** 19 | * @param v the tea weight 20 | */ 21 | public boolean fling(Integer v) throws UnsupportedOperationException { 22 | throw new UnsupportedOperationException(); 23 | } 24 | 25 | public boolean fling(Object v) { 26 | throw new UnsupportedOperationException(); 27 | } 28 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/DocumentedInterface.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | /** 4 | * The {@code Javadoc} from this interface is used for testing 5 | * 6 | */ 7 | public interface DocumentedInterface { 8 | /** 9 | * Hoodwink a kerfluffin 10 | * 11 | * @param i innocent 12 | * @return true if innocent hoodwinked 13 | * @throws UnsupportedOperationException if hoodwinking cannot be performed 14 | */ 15 | public boolean hoodwink(String i) throws UnsupportedOperationException; 16 | 17 | /** 18 | * Snaggle a kerfluffin 19 | * 20 | * @param i innocent 21 | * @return true if innocent hoodwinked 22 | */ 23 | public boolean snaggle(String i); 24 | 25 | /** 26 | * Fling the tea 27 | * @param v 28 | * @return true if flung 29 | * @exception UnsupportedOperationException if hoodwinking cannot be performed 30 | */ 31 | public boolean fling(T v) throws UnsupportedOperationException; 32 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/DocumentedRecord.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | /** 4 | * I am a documented record. 5 | * 6 | * @param count lucky number 7 | * @param color favorite color 8 | */ 9 | public record DocumentedRecord(int count, String color) { 10 | 11 | /** 12 | * Secondary constructor, assumes favorite color is red. 13 | * 14 | * @param count yes, the count 15 | */ 16 | public DocumentedRecord(int count) { 17 | this(count, "red"); 18 | } 19 | 20 | /** 21 | * I am a custom method in a record 22 | * 23 | * @param frobulate yes or no 24 | * @return some string 25 | */ 26 | public String someMethod(boolean frobulate) { 27 | return color + frobulate + count; 28 | } 29 | 30 | /** 31 | * I am nested in a record 32 | */ 33 | public static class Nested { 34 | } 35 | 36 | public static class NestedWithoutJavadoc { 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/OtherInterface.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | /** 4 | * The {@code Javadoc} from this interface is used for masking 5 | * 6 | */ 7 | public interface OtherInterface { 8 | /** 9 | * Hoodwink a schmadragon 10 | */ 11 | public boolean hoodwink(String g); 12 | 13 | /** 14 | * Fling the vorrdin 15 | * @param v 16 | * @return 17 | */ 18 | public boolean fling(T v); 19 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/OverridingClass.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import java.util.List; 4 | import javasource.foo.DocumentedClass; 5 | 6 | 7 | // I override methods of DocumentedClass with and without their own javadoc 8 | public class OverridingClass extends DocumentedClass { 9 | 10 | /** 11 | * Super frobulate {@code a} by {@code b} using extended frobulation 12 | * 13 | * @see com.github.therapi.runtimejavadoc.DocumentedClass Hey, that's this class! 14 | * @see javasource.foo.DocumentedClass#someOtherMethod() 15 | * @see "Moomoo boy went straight to Moomoo land. Land of the moomoo's" 16 | * @see Moomoo land 17 | */ 18 | public int frobulate(String a, int b) { 19 | throw new UnsupportedOperationException(); 20 | } 21 | 22 | // I have no javadoc of my own 23 | public int frobulate(String a, List b) { 24 | throw new UnsupportedOperationException(); 25 | } 26 | 27 | /** 28 | * My very own method 29 | * 30 | */ 31 | public void myOwnMethod() { 32 | throw new UnsupportedOperationException(); 33 | } 34 | 35 | // I have no javadoc 36 | public String genericMethod(String generic) { 37 | return generic; 38 | } 39 | 40 | // Even though I may no look like it I override nothing but do partially hide a method 41 | public String separateGeneric(Integer otherGeneric) { 42 | throw new UnsupportedOperationException(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/OverridingClass2Degrees.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import java.util.List; 4 | import javasource.foo.OverridingClass; 5 | 6 | 7 | // I override methods of DocumentedClass with and without their own javadoc 8 | public class OverridingClass2Degrees extends OverridingClass { 9 | 10 | /** 11 | * I am also a simple method 12 | */ 13 | public void skipMethod() { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | public String skipGenericMethod(String generic) { 18 | return generic; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc-scribe/src/test/resources/javasource/foo/VeryComplexImplementation.java: -------------------------------------------------------------------------------- 1 | package javasource.foo; 2 | 3 | import javasource.foo.OtherInterface; 4 | import javasource.foo.DocumentedInterface; 5 | 6 | public class VeryComplexImplementation extends DocumentedImplementation implements OtherInterface { 7 | // I have no javadoc of my own 8 | public boolean hoodwink(String i) { 9 | throw new UnsupportedOperationException(); 10 | } 11 | 12 | public boolean fling(Integer v) { 13 | throw new UnsupportedOperationException(); 14 | } 15 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'com.eclipsesource.minimal-json:minimal-json:0.9.5' 3 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc/gradle.properties: -------------------------------------------------------------------------------- 1 | description = Reads Javadoc comments baked into your code by the runtime Javadoc scribe. 2 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/BaseJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.List; 20 | 21 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.requireNonNull; 22 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; 23 | 24 | public abstract class BaseJavadoc { 25 | 26 | private final String name; 27 | private final Comment comment; 28 | private final List seeAlso; 29 | private final List other; 30 | 31 | BaseJavadoc(String name, Comment comment, List seeAlso, List other) { 32 | this.name = requireNonNull(name); 33 | this.comment = Comment.nullToEmpty(comment); 34 | this.other = unmodifiableDefensiveCopy(other); 35 | this.seeAlso = unmodifiableDefensiveCopy(seeAlso); 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | public Comment getComment() { 43 | return comment; 44 | } 45 | 46 | public List getSeeAlso() { 47 | return seeAlso; 48 | } 49 | 50 | public List getOther() { 51 | return other; 52 | } 53 | 54 | /** 55 | * @return false if this object has content, or true if it represents absent Javadoc. 56 | */ 57 | public boolean isEmpty() { 58 | return false; 59 | } 60 | 61 | /** 62 | * @return true if this object has content, or false if it represents absent Javadoc. 63 | * @deprecated use !{@link #isEmpty()} instead 64 | */ 65 | @Deprecated 66 | public boolean isPresent() { 67 | return !isEmpty(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/ClassJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import com.github.therapi.runtimejavadoc.internal.MethodSignature; 20 | 21 | import java.lang.reflect.Constructor; 22 | import java.lang.reflect.Field; 23 | import java.lang.reflect.Method; 24 | import java.util.ArrayList; 25 | import java.util.Arrays; 26 | import java.util.Collections; 27 | import java.util.HashMap; 28 | import java.util.LinkedHashMap; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.getAllTypeAncestors; 33 | 34 | public class ClassJavadoc extends BaseJavadoc { 35 | private final Map fields; 36 | private final Map enumConstants; 37 | private final Map methods; 38 | private final Map constructors; 39 | private final Map recordComponents; 40 | 41 | public ClassJavadoc(String name, Comment comment, List fields, List enumConstants, 42 | List methods, List constructors, List other, 43 | List seeAlso, List recordComponents) { 44 | super(name, comment, seeAlso, other); 45 | 46 | Map fieldMap = new LinkedHashMap<>(); 47 | if (fields != null) { 48 | fields.forEach(fieldJavadoc -> fieldMap.put(fieldJavadoc.getName(), fieldJavadoc)); 49 | } 50 | this.fields = Collections.unmodifiableMap(fieldMap); 51 | 52 | Map enumMap = new LinkedHashMap<>(); 53 | if (enumConstants != null) { 54 | enumConstants.forEach(fieldJavadoc -> enumMap.put(fieldJavadoc.getName(), fieldJavadoc)); 55 | } 56 | this.enumConstants = Collections.unmodifiableMap(enumMap); 57 | 58 | Map methodsMap = new LinkedHashMap<>(); 59 | if (methods != null) { 60 | methods.forEach(methodJavadoc -> methodsMap.put(MethodSignature.from(methodJavadoc), methodJavadoc)); 61 | } 62 | this.methods = Collections.unmodifiableMap(methodsMap); 63 | 64 | Map constructorsMap = new LinkedHashMap<>(); 65 | if (constructors != null) { 66 | constructors.forEach( 67 | methodJavadoc -> constructorsMap.put(MethodSignature.from(methodJavadoc), methodJavadoc)); 68 | } 69 | this.constructors = Collections.unmodifiableMap(constructorsMap); 70 | 71 | Map recordsMap = new LinkedHashMap<>(); 72 | if (recordComponents != null) { 73 | recordComponents.forEach(paramJavadoc -> recordsMap.put(paramJavadoc.getName(), paramJavadoc)); 74 | } 75 | this.recordComponents = Collections.unmodifiableMap(recordsMap); 76 | } 77 | 78 | private ClassJavadoc(String name, Comment comment, Map fields, 79 | Map enumConstants, Map methods, 80 | Map constructors, List other, 81 | List seeAlso, Map recordComponents) { 82 | super(name, comment, seeAlso, other); 83 | this.fields = Collections.unmodifiableMap(fields); 84 | this.enumConstants = Collections.unmodifiableMap(enumConstants); 85 | this.methods = Collections.unmodifiableMap(methods); 86 | this.constructors = Collections.unmodifiableMap(constructors); 87 | this.recordComponents = Collections.unmodifiableMap(recordComponents); 88 | } 89 | 90 | public static ClassJavadoc createEmpty(String qualifiedClassName) { 91 | return new ClassJavadoc(qualifiedClassName, null, (List) null, null, null, null, null, null, null) { 92 | @Override 93 | public boolean isEmpty() { 94 | return true; 95 | } 96 | }; 97 | } 98 | 99 | ClassJavadoc createEnhancedClassJavadoc(Class clazz) { 100 | assert getName().replace("$", ".").equals(clazz.getCanonicalName()) 101 | : "Class `" + clazz.getName() + "` does not match class doc for `" + getName() + "`"; 102 | 103 | Map classJavadocCache = new HashMap<>(); 104 | 105 | classJavadocCache.put(clazz.getCanonicalName(), this); 106 | getAllTypeAncestors(clazz).forEach(cls -> classJavadocCache.put(cls.getCanonicalName(), RuntimeJavadoc.getSkinnyClassJavadoc(cls))); 107 | 108 | Map methodJavadocs = new LinkedHashMap<>(); 109 | Arrays.stream(clazz.getMethods()) 110 | .forEach(method -> { 111 | MethodJavadoc methodJavadoc = RuntimeJavadoc.getJavadoc(method, classJavadocCache); 112 | if (!methodJavadoc.isEmpty()) { 113 | methodJavadocs.put(MethodSignature.from(method), methodJavadoc); 114 | } 115 | }); 116 | 117 | if (methodJavadocs.isEmpty()) { 118 | return this; // didn't inherit anything. 119 | } 120 | 121 | return new ClassJavadoc(getName(), getComment(), fields, enumConstants, methodJavadocs, constructors, 122 | getOther(), getSeeAlso(), recordComponents); 123 | } 124 | 125 | public List getFields() { 126 | return Collections.unmodifiableList(new ArrayList<>(fields.values())); 127 | } 128 | 129 | public List getEnumConstants() { 130 | return Collections.unmodifiableList(new ArrayList<>(enumConstants.values())); 131 | } 132 | 133 | public List getMethods() { 134 | return Collections.unmodifiableList(new ArrayList<>(methods.values())); 135 | } 136 | 137 | public List getConstructors() { 138 | return Collections.unmodifiableList(new ArrayList<>(constructors.values())); 139 | } 140 | 141 | /** 142 | * If this class is a record, returns the "@param" tags from the canonical constructor. 143 | * Otherwise, returns an empty list. 144 | * 145 | * @return a non-null (but possibly empty) list of param tags describing the record components, 146 | * in the order the tags appear in the Javadoc. 147 | */ 148 | public List getRecordComponents() { 149 | return Collections.unmodifiableList(new ArrayList<>(recordComponents.values())); 150 | } 151 | 152 | FieldJavadoc findMatchingField(Field field) { 153 | return fields.getOrDefault(field.getName(), FieldJavadoc.createEmpty(field.getName())); 154 | } 155 | 156 | FieldJavadoc findMatchingEnumConstant(Enum enumConstant) { 157 | return enumConstants.getOrDefault(enumConstant.name(), FieldJavadoc.createEmpty(enumConstant.name())); 158 | } 159 | 160 | MethodJavadoc findMatchingMethod(Method method) { 161 | MethodSignature methodSignature = MethodSignature.from(method); 162 | return methods.getOrDefault(methodSignature, MethodJavadoc.createEmpty(method)); 163 | } 164 | 165 | MethodJavadoc findMatchingConstructor(Constructor constructor) { 166 | MethodSignature methodSignature = MethodSignature.from(constructor); 167 | return constructors.getOrDefault(methodSignature, MethodJavadoc.createEmpty(constructor)); 168 | } 169 | 170 | ParamJavadoc findRecordComponent(String recordComponent) { 171 | return recordComponents.getOrDefault(recordComponent, new ParamJavadoc(recordComponent, Comment.createEmpty())); 172 | } 173 | 174 | @Override 175 | public String toString() { 176 | return "ClassJavadoc{" 177 | + "name='" + getName() + '\'' 178 | + ", comment=" + getComment() 179 | + ", fields=" + fields 180 | + ", methods=" + methods 181 | + ", constructors=" + constructors 182 | + ", recordComponents=" + recordComponents 183 | + ", seeAlso=" + getSeeAlso() 184 | + ", other=" + getOther() + '}'; 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/Comment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Collections; 20 | import java.util.Iterator; 21 | import java.util.List; 22 | 23 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; 24 | 25 | /** 26 | * Comment text that may contain inline tags. 27 | */ 28 | public class Comment implements Iterable { 29 | private static final Comment EMPTY = new Comment(Collections.emptyList()); 30 | 31 | public static Comment createEmpty() { 32 | return EMPTY; 33 | } 34 | 35 | public static Comment nullToEmpty(Comment c) { 36 | return c == null ? EMPTY : c; 37 | } 38 | 39 | private final List elements; 40 | 41 | public Comment(List elements) { 42 | this.elements = unmodifiableDefensiveCopy(elements); 43 | } 44 | 45 | /** 46 | * Returns the elements this comment consists of. 47 | * 48 | * @return the elements this comment consists of. 49 | */ 50 | public List getElements() { 51 | return elements; 52 | } 53 | 54 | @Override 55 | public Iterator iterator() { 56 | return elements.iterator(); 57 | } 58 | 59 | public void visit(CommentVisitor visitor) { 60 | for (CommentElement e : elements) { 61 | e.visit(visitor); 62 | } 63 | } 64 | 65 | @Override 66 | public String toString() { 67 | return new CommentFormatter().format(this); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/CommentElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | 20 | public abstract class CommentElement { 21 | public abstract void visit(CommentVisitor visitor); 22 | } 23 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/CommentFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | /** 20 | * Performs basic conversion of a Comment into a String. 21 | *

22 | * Reusable and thread-safe. 23 | */ 24 | public class CommentFormatter { 25 | /** 26 | * Render the comment as an HTML String. 27 | * 28 | * @param comment the comment to render (may be {@code null} in which case an empty string is returned) 29 | * @return the HTML String representation of the comment 30 | */ 31 | public String format(Comment comment) { 32 | if (comment == null) { 33 | return ""; 34 | } 35 | 36 | ToHtmlStringCommentVisitor visitor = new ToHtmlStringCommentVisitor(); 37 | comment.visit(visitor); 38 | 39 | return visitor.build(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/CommentText.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Objects; 20 | 21 | public class CommentText extends CommentElement { 22 | private final String value; 23 | 24 | public CommentText(String value) { 25 | this.value = value; 26 | } 27 | 28 | public String getValue() { 29 | return value; 30 | } 31 | 32 | public void visit(CommentVisitor visitor) { 33 | visitor.commentText(value); 34 | } 35 | 36 | @Override 37 | public boolean equals(Object o) { 38 | if (this == o) { 39 | return true; 40 | } 41 | if (o == null || getClass() != o.getClass()) { 42 | return false; 43 | } 44 | CommentText that = (CommentText) o; 45 | return Objects.equals(value, that.value); 46 | } 47 | 48 | @Override 49 | public int hashCode() { 50 | return Objects.hash(value); 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "CommentText{" + "value='" + value + '\'' + '}'; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/CommentVisitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | 20 | public interface CommentVisitor { 21 | void commentText(String value); 22 | 23 | void inlineLink(Link link); 24 | 25 | void inlineTag(String name, String value); 26 | 27 | void inlineValue(Value value); 28 | } 29 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/FieldJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.List; 20 | 21 | public class FieldJavadoc extends BaseJavadoc { 22 | 23 | public FieldJavadoc(String name, Comment comment, List other, List seeAlso) { 24 | super(name, comment, seeAlso, other); 25 | } 26 | 27 | public static FieldJavadoc createEmpty(String fieldName) { 28 | return new FieldJavadoc(fieldName, null, null, null) { 29 | @Override 30 | public boolean isEmpty() { 31 | return true; 32 | } 33 | }; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return "FieldJavadoc{" 39 | + "name='" + getName() + '\'' 40 | + ", comment=" + getComment() 41 | + ", other=" + getOther() 42 | + ", seeAlso=" + getSeeAlso() 43 | + '}'; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/InlineLink.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Objects; 20 | 21 | public class InlineLink extends CommentElement { 22 | private final Link link; 23 | 24 | public InlineLink(Link link) { 25 | this.link = link; 26 | } 27 | 28 | public Link getLink() { 29 | return link; 30 | } 31 | 32 | public void visit(CommentVisitor visitor) { 33 | visitor.inlineLink(link); 34 | } 35 | 36 | @Override 37 | public boolean equals(Object o) { 38 | if (this == o) { 39 | return true; 40 | } 41 | if (o == null || getClass() != o.getClass()) { 42 | return false; 43 | } 44 | InlineLink that = (InlineLink) o; 45 | return Objects.equals(link, that.link); 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "link=" + link; 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | return Objects.hash(link); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/InlineTag.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Objects; 20 | 21 | public class InlineTag extends CommentElement { 22 | private final String name; 23 | private final String value; 24 | 25 | public InlineTag(String name, String value) { 26 | this.name = name; 27 | this.value = value; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public String getValue() { 35 | return value; 36 | } 37 | 38 | public void visit(CommentVisitor visitor) { 39 | visitor.inlineTag(name, value); 40 | } 41 | 42 | @Override 43 | public boolean equals(Object o) { 44 | if (this == o) { 45 | return true; 46 | } 47 | if (o == null || getClass() != o.getClass()) { 48 | return false; 49 | } 50 | InlineTag inlineTag = (InlineTag) o; 51 | return Objects.equals(name, inlineTag.name) && Objects.equals(value, inlineTag.value); 52 | } 53 | 54 | @Override 55 | public int hashCode() { 56 | return Objects.hash(name, value); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/InlineValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Objects; 20 | 21 | public class InlineValue extends CommentElement { 22 | private final Value value; 23 | 24 | public InlineValue(Value value) { 25 | this.value = value; 26 | } 27 | 28 | public Value getValue() { 29 | return value; 30 | } 31 | 32 | public void visit(CommentVisitor visitor) { 33 | visitor.inlineValue(value); 34 | } 35 | 36 | @Override 37 | public boolean equals(Object o) { 38 | if (this == o) { 39 | return true; 40 | } 41 | if (o == null || getClass() != o.getClass()) { 42 | return false; 43 | } 44 | InlineValue that = (InlineValue) o; 45 | return Objects.equals(value, that.value); 46 | } 47 | 48 | @Override 49 | public String toString() { 50 | return "value=" + value; 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | return Objects.hash(value); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/Link.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.List; 20 | import java.util.Objects; 21 | 22 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.join; 23 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; 24 | 25 | public class Link { 26 | private final String label; 27 | private final String referencedClassName; 28 | private final String referencedMemberName; 29 | private final List params; 30 | 31 | public Link(String label, String referencedClassName, String referencedMemberName, List params) { 32 | this.label = label; 33 | this.referencedClassName = referencedClassName; 34 | this.referencedMemberName = referencedMemberName; 35 | this.params = unmodifiableDefensiveCopy(params); 36 | } 37 | 38 | public String getLabel() { 39 | return label; 40 | } 41 | 42 | public String getReferencedClassName() { 43 | return referencedClassName; 44 | } 45 | 46 | public String getReferencedMemberName() { 47 | return referencedMemberName; 48 | } 49 | 50 | public List getParams() { 51 | return params; 52 | } 53 | 54 | @Override 55 | public boolean equals(Object o) { 56 | if (this == o) { 57 | return true; 58 | } 59 | if (o == null || getClass() != o.getClass()) { 60 | return false; 61 | } 62 | Link link = (Link) o; 63 | return Objects.equals(label, link.label) && 64 | Objects.equals(referencedClassName, link.referencedClassName) 65 | && Objects.equals(referencedMemberName, link.referencedMemberName) 66 | && Objects.equals(params, link.params); 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | return Objects.hash(label, referencedClassName, referencedMemberName, params); 72 | } 73 | 74 | public String toString() { 75 | StringBuilder sb = new StringBuilder(); 76 | 77 | if (referencedClassName != null) { 78 | sb.append(referencedClassName); 79 | } 80 | 81 | if (referencedMemberName != null) { 82 | sb.append('#').append(referencedMemberName); 83 | 84 | if (!params.isEmpty()) { 85 | sb.append('(').append(join(", ", params)).append(")"); 86 | } 87 | } 88 | 89 | if (label != null) { 90 | sb.append(' ').append(label); 91 | } 92 | 93 | return sb.toString(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/MethodJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import com.github.therapi.runtimejavadoc.internal.MethodSignature; 20 | import com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper; 21 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; 22 | import java.lang.reflect.Constructor; 23 | import java.lang.reflect.Executable; 24 | import java.lang.reflect.Method; 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.Collections; 28 | import java.util.LinkedHashMap; 29 | import java.util.List; 30 | import java.util.Map; 31 | import java.util.stream.Collectors; 32 | 33 | public class MethodJavadoc extends BaseJavadoc { 34 | private final List paramTypes; 35 | private final Map params; 36 | private final Map exceptions; 37 | private final Comment returns; 38 | 39 | public MethodJavadoc(String name, 40 | List paramTypes, 41 | Comment comment, 42 | List params, 43 | List exceptions, 44 | List other, 45 | Comment returns, 46 | List seeAlso) { 47 | super(name, comment, seeAlso, other); 48 | 49 | this.paramTypes = unmodifiableDefensiveCopy(paramTypes); 50 | this.returns = Comment.nullToEmpty(returns); 51 | 52 | Map paramJavadocMap = new LinkedHashMap<>(); 53 | 54 | if (params != null) { 55 | params.forEach(paramJavadoc -> paramJavadocMap.put(paramJavadoc.getName(), paramJavadoc)); 56 | } 57 | 58 | this.params = Collections.unmodifiableMap(paramJavadocMap); 59 | 60 | Map throwsJavadocMap = new LinkedHashMap<>(); 61 | 62 | if (params != null) { 63 | exceptions.forEach(throwsJavadoc -> throwsJavadocMap.put(throwsJavadoc.getName(), throwsJavadoc)); 64 | } 65 | 66 | this.exceptions = Collections.unmodifiableMap(throwsJavadocMap); 67 | } 68 | 69 | private MethodJavadoc(String name, 70 | List paramTypes, 71 | Comment comment, 72 | Map params, 73 | Map exceptions, 74 | List other, 75 | Comment returns, 76 | List seeAlso) { 77 | super(name, comment, seeAlso, other); 78 | this.paramTypes = Collections.unmodifiableList(paramTypes); 79 | this.params = Collections.unmodifiableMap(params); 80 | this.exceptions = Collections.unmodifiableMap(exceptions); 81 | this.returns = returns; 82 | } 83 | 84 | public static MethodJavadoc createEmpty(Executable executable) { 85 | String name = executable instanceof Constructor ? RuntimeJavadocHelper.INIT : executable.getName(); 86 | List paramTypes = Arrays.stream(executable.getParameterTypes()) 87 | .map(Class::getCanonicalName) 88 | .collect(Collectors.toList()); 89 | 90 | return new MethodJavadoc(name, paramTypes, null, (List) null, null, null, null, null) { 91 | @Override 92 | public boolean isEmpty() { 93 | return true; 94 | } 95 | }; 96 | } 97 | 98 | MethodJavadoc enhanceWithOverriddenJavadoc(Method method, Map classJavadocCache) { 99 | MethodJavadoc enhancedJavadoc = this; 100 | List> superTypes = RuntimeJavadocHelper.getAllTypeAncestors(method.getDeclaringClass()); 101 | 102 | for (Class superType : superTypes) { 103 | ClassJavadoc classJavadoc = classJavadocCache.get(superType.getCanonicalName()); 104 | if (classJavadoc == null) { 105 | classJavadoc = RuntimeJavadoc.getSkinnyClassJavadoc(superType); 106 | } 107 | MethodJavadoc overriddenJavadoc = classJavadoc.findMatchingMethod(method); 108 | enhancedJavadoc = enhancedJavadoc.copyWithInheritance(overriddenJavadoc); 109 | if (enhancedJavadoc.fullyDescribes(method)) { 110 | break; 111 | } 112 | } 113 | 114 | return enhancedJavadoc; 115 | } 116 | 117 | private MethodJavadoc copyWithInheritance(MethodJavadoc superMethodJavadoc) { 118 | if (superMethodJavadoc.isEmpty()) { 119 | return this; 120 | } 121 | 122 | List paramTypes = new ArrayList<>(this.paramTypes); 123 | if (paramTypes.isEmpty()) { 124 | paramTypes = superMethodJavadoc.paramTypes; 125 | } 126 | 127 | Comment comment = getComment(); 128 | if (comment.getElements().isEmpty()) { 129 | comment = superMethodJavadoc.getComment(); 130 | } 131 | 132 | Map params = new LinkedHashMap<>(this.params); 133 | superMethodJavadoc.params.forEach(params::putIfAbsent); 134 | 135 | Map exceptions = new LinkedHashMap<>(this.exceptions); 136 | superMethodJavadoc.exceptions.forEach(exceptions::putIfAbsent); 137 | 138 | Comment returns = this.returns; 139 | if (returns.getElements().isEmpty()) { 140 | returns = superMethodJavadoc.returns; 141 | } 142 | 143 | return new MethodJavadoc(getName(), paramTypes, comment, params, exceptions, getOther(), returns, getSeeAlso()); 144 | } 145 | 146 | public boolean isConstructor() { 147 | return RuntimeJavadocHelper.INIT.equals(getName()); 148 | } 149 | 150 | boolean fullyDescribes(Method method) { 151 | if (!method.getName().equals(getName()) || method.getParameterCount() != paramTypes.size()) { 152 | throw new IllegalArgumentException("Method `" + method.getName() + "` does not match javadoc `" + getName() + "`"); 153 | } 154 | 155 | return !getComment().getElements().isEmpty() 156 | && !returns.getElements().isEmpty() 157 | && method.getParameterCount() == params.size() 158 | && Arrays.stream(method.getExceptionTypes()) 159 | .allMatch(exception -> exceptions.containsKey(exception.getSimpleName())); 160 | } 161 | 162 | public boolean matches(Executable executable) { 163 | if (executable instanceof Method) { 164 | return matches((Method) executable); 165 | } else if (executable instanceof Constructor) { 166 | return matches((Constructor) executable); 167 | } else { 168 | throw new UnsupportedOperationException("Unknown executable type"); 169 | } 170 | } 171 | 172 | public boolean matches(Method method) { 173 | return method.getName().equals(getName()) 174 | && paramsMatch(method.getParameterTypes()); 175 | } 176 | 177 | public boolean matches(Constructor method) { 178 | return isConstructor() 179 | && paramsMatch(method.getParameterTypes()); 180 | } 181 | 182 | private boolean paramsMatch(Class[] paramTypes) { 183 | return getCanonicalNames(paramTypes).equals(this.paramTypes); 184 | } 185 | 186 | private static List getCanonicalNames(Class[] paramTypes) { 187 | List methodParamsTypes = new ArrayList<>(); 188 | for (Class aClass : paramTypes) { 189 | methodParamsTypes.add(aClass.getCanonicalName()); 190 | } 191 | return methodParamsTypes; 192 | } 193 | 194 | public List getParamTypes() { 195 | return paramTypes; 196 | } 197 | 198 | public List getParams() { 199 | return Collections.unmodifiableList(new ArrayList<>(params.values())); 200 | } 201 | 202 | public List getThrows() { 203 | return Collections.unmodifiableList(new ArrayList<>(exceptions.values())); 204 | } 205 | 206 | public Comment getReturns() { 207 | return returns; 208 | } 209 | 210 | @Override 211 | public String toString() { 212 | return "MethodJavadoc{" + 213 | "name='" + getName() + '\'' + 214 | ", paramTypes='" + paramTypes + '\'' + 215 | ", comment=" + getComment() + 216 | ", params=" + params + 217 | ", exceptions=" + exceptions + 218 | ", other=" + getOther() + 219 | ", returns=" + returns + 220 | ", seeAlso=" + getSeeAlso() + 221 | '}'; 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/OtherJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | /** 20 | * Unstructured tag with a name and comment. May be a standard tag like "@author" 21 | * or a user-defined custom tag. 22 | */ 23 | public class OtherJavadoc { 24 | private final String name; 25 | private final Comment comment; 26 | 27 | public OtherJavadoc(String name, Comment comment) { 28 | this.name = name; 29 | this.comment = comment; 30 | } 31 | 32 | /** 33 | * Returns the name of the tag (including the "@") 34 | * 35 | * @return the name of the tag (including the "@") 36 | */ 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public Comment getComment() { 42 | return comment; 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "@" + name + " " + comment; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/ParamJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | 20 | public class ParamJavadoc { 21 | private final String name; 22 | private final Comment comment; 23 | 24 | public ParamJavadoc(String name, Comment comment) { 25 | this.name = name; 26 | this.comment = comment; 27 | } 28 | 29 | /** 30 | * Returns the name of parameter 31 | * 32 | * @return the name of parameter 33 | */ 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public Comment getComment() { 39 | return comment; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return name + " " + comment; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/RetainJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | /** 25 | * Indicates the annotated element should have its Javadoc made available at runtime, 26 | * even if it's not in one of the packages specified by the {@code javadoc.packages} 27 | * annotation processor option. 28 | *

29 | * Note that if a {@code javadoc.packages} is not specified, this annotation is 30 | * redundant since the default behavior is to retain Javadoc for all classes. 31 | * 32 | * @see RuntimeJavadoc#getJavadoc 33 | */ 34 | @Retention(RetentionPolicy.RUNTIME) 35 | @Target({ElementType.TYPE, ElementType.PACKAGE}) 36 | public @interface RetainJavadoc { 37 | } 38 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/RuntimeJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import com.eclipsesource.json.Json; 20 | import com.eclipsesource.json.JsonObject; 21 | import com.github.therapi.runtimejavadoc.internal.JsonJavadocReader; 22 | import com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper; 23 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.javadocResourceSuffix; 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.InputStreamReader; 27 | import java.lang.reflect.Constructor; 28 | import java.lang.reflect.Field; 29 | import java.lang.reflect.Method; 30 | import static java.nio.charset.StandardCharsets.UTF_8; 31 | import java.util.Collections; 32 | import java.util.List; 33 | import java.util.Map; 34 | 35 | /** 36 | * Allows access to Javadoc elements at runtime for code that was compiled using the 37 | * {@code therapi-runtime-javadoc-scribe} annotation processor. 38 | */ 39 | public class RuntimeJavadoc { 40 | 41 | private RuntimeJavadoc() { 42 | throw new AssertionError("not instantiable"); 43 | } 44 | 45 | /** 46 | * Gets the Javadoc of the given class. 47 | *

48 | * The return value is always non-null. If no Javadoc is available, the returned object's 49 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 50 | * 51 | * @param clazz the class whose Javadoc you want to retrieve 52 | * @return the Javadoc of the given class 53 | */ 54 | public static ClassJavadoc getJavadoc(Class clazz) { 55 | return getSkinnyClassJavadoc(clazz.getName(), clazz).createEnhancedClassJavadoc(clazz); 56 | } 57 | 58 | /** 59 | * Gets the Javadoc of the given class. 60 | *

61 | * The return value is always non-null. If no Javadoc is available, the returned object's 62 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 63 | * 64 | * @param qualifiedClassName the fully qualified name of the class whose Javadoc you want to retrieve 65 | * @return the Javadoc of the given class 66 | */ 67 | public static ClassJavadoc getJavadoc(String qualifiedClassName) { 68 | return getJavadoc(qualifiedClassName, RuntimeJavadoc.class); 69 | } 70 | 71 | /** 72 | * Gets the Javadoc of the given class, using the given {@link ClassLoader} to find the Javadoc resource. 73 | *

74 | * The return value is always non-null. If no Javadoc is available, the returned object's 75 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 76 | * 77 | * @param qualifiedClassName the fully qualified name of the class whose Javadoc you want to retrieve 78 | * @param loader the class loader to use to find the Javadoc resource file 79 | * @return the Javadoc of the given class 80 | */ 81 | public static ClassJavadoc getJavadoc(String qualifiedClassName, ClassLoader loader) { 82 | try { 83 | return getSkinnyClassJavadoc(qualifiedClassName, loader) 84 | .createEnhancedClassJavadoc(loader.loadClass(qualifiedClassName)); 85 | } catch (ClassNotFoundException e) { 86 | throw new RuntimeException(e); 87 | } 88 | } 89 | 90 | /** 91 | * Gets the Javadoc of the given class, using the given {@link Class} object to load the Javadoc resource. 92 | *

93 | * The return value is always non-null. If no Javadoc is available, the returned object's 94 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 95 | * 96 | * @param qualifiedClassName the fully qualified name of the class whose Javadoc you want to retrieve 97 | * @param loader the class object to use to find the Javadoc resource file 98 | * @return the Javadoc of the given class 99 | */ 100 | public static ClassJavadoc getJavadoc(String qualifiedClassName, Class loader) { 101 | try { 102 | return getSkinnyClassJavadoc(qualifiedClassName, loader) 103 | .createEnhancedClassJavadoc(loader.getClassLoader().loadClass(qualifiedClassName)); 104 | } catch (ClassNotFoundException e) { 105 | throw new RuntimeException(e); 106 | } 107 | } 108 | 109 | static ClassJavadoc getSkinnyClassJavadoc(Class clazz) { 110 | return getSkinnyClassJavadoc(clazz.getName(), clazz); 111 | } 112 | 113 | private static ClassJavadoc getSkinnyClassJavadoc(String qualifiedClassName, ClassLoader loader) { 114 | final String resourceName = getResourceName(qualifiedClassName); 115 | try (InputStream is = loader.getResourceAsStream("/" + resourceName)) { 116 | return parseJavadocResource(qualifiedClassName, is); 117 | } catch (IOException e) { 118 | throw new RuntimeException(e); 119 | } 120 | } 121 | 122 | private static ClassJavadoc getSkinnyClassJavadoc(String qualifiedClassName, Class loader) { 123 | final String resourceName = getResourceName(qualifiedClassName); 124 | try (InputStream is = loader.getResourceAsStream("/" + resourceName)) { 125 | return parseJavadocResource(qualifiedClassName, is); 126 | } catch (IOException e) { 127 | throw new RuntimeException(e); 128 | } 129 | } 130 | 131 | private static String getResourceName(String qualifiedClassName) { 132 | return qualifiedClassName.replace(".", "/") + javadocResourceSuffix(); 133 | } 134 | 135 | private static ClassJavadoc parseJavadocResource(String qualifiedClassName, InputStream is) throws IOException { 136 | if (is == null) { 137 | return ClassJavadoc.createEmpty(qualifiedClassName); 138 | } 139 | 140 | try (InputStreamReader r = new InputStreamReader(is, UTF_8)) { 141 | JsonObject json = Json.parse(r).asObject(); 142 | return JsonJavadocReader.readClassJavadoc(qualifiedClassName, json); 143 | } 144 | } 145 | 146 | /** 147 | * Gets the Javadoc of the given method. 148 | *

149 | * The return value is always non-null. If no Javadoc is available, the returned object's 150 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 151 | *

152 | * Implementation note: this method first retrieves the Javadoc of the class, and then matches the method signature 153 | * with the correct documentation. If the client code's purpose is to loop through all methods doc, prefer using 154 | * {@link #getJavadoc(Class)} (or one of its overloads), and calling {@link ClassJavadoc#getMethods()} on the 155 | * returned class doc to retrieve method docs. 156 | * 157 | * @param method the method whose Javadoc you want to retrieve 158 | * @return the given method's Javadoc 159 | */ 160 | public static MethodJavadoc getJavadoc(Method method) { 161 | return getJavadoc(method, Collections.emptyMap()); 162 | } 163 | 164 | static MethodJavadoc getJavadoc(Method method, Map classJavadocCache) { 165 | Class declaringClass = method.getDeclaringClass(); 166 | ClassJavadoc classJavadoc = classJavadocCache.get(declaringClass.getCanonicalName()); 167 | if (classJavadoc == null) { 168 | classJavadoc = getSkinnyClassJavadoc(declaringClass); 169 | } 170 | 171 | MethodJavadoc methodJavadoc = classJavadoc.findMatchingMethod(method); 172 | if (methodJavadoc.fullyDescribes(method)) { 173 | return methodJavadoc; 174 | } 175 | 176 | methodJavadoc = methodJavadoc.enhanceWithOverriddenJavadoc(method, classJavadocCache); 177 | if (methodJavadoc.fullyDescribes(method)) { 178 | return methodJavadoc; 179 | } 180 | 181 | Method bridgeMethod = RuntimeJavadocHelper.findBridgeMethod(method); 182 | if (bridgeMethod != null && method != bridgeMethod) { 183 | methodJavadoc = methodJavadoc.enhanceWithOverriddenJavadoc(bridgeMethod, classJavadocCache); 184 | } 185 | 186 | return methodJavadoc; 187 | } 188 | 189 | /** 190 | * Gets the Javadoc of the given constructor. 191 | *

192 | * The return value is always non-null. If no Javadoc is available, the returned object's 193 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 194 | *

195 | * Implementation note: this method first retrieves the Javadoc of the class, and then matches the method signature 196 | * with the correct documentation. If the client code's purpose is to loop through all methods doc, prefer using 197 | * {@link #getJavadoc(Class)} (or one of its overloads), and calling {@link ClassJavadoc#getMethods()} on the 198 | * returned class doc to retrieve method docs. 199 | * 200 | * @param method the constructor whose Javadoc you want to retrieve 201 | * @return the given constructor's Javadoc 202 | */ 203 | public static MethodJavadoc getJavadoc(Constructor method) { 204 | return getSkinnyClassJavadoc(method.getDeclaringClass()).findMatchingConstructor(method); 205 | } 206 | 207 | /** 208 | * Gets the Javadoc of the given field. 209 | *

210 | * The return value is always non-null. If no Javadoc is available, the returned object's 211 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 212 | *

213 | * Implementation note: this method first retrieves the Javadoc of the class, and then matches the field name 214 | * with the correct documentation. If the client code's purpose is to loop through all fields doc, prefer using 215 | * {@link #getJavadoc(Class)} (or one of its overloads), and calling {@link ClassJavadoc#getFields()} on the 216 | * returned class doc to retrieve field docs. 217 | * 218 | * @param field the field whose Javadoc you want to retrieve 219 | * @return the given field's Javadoc 220 | */ 221 | public static FieldJavadoc getJavadoc(Field field) { 222 | return getSkinnyClassJavadoc(field.getDeclaringClass()).findMatchingField(field); 223 | } 224 | 225 | /** 226 | * Gets the Javadoc of the given enum constant. 227 | *

228 | * The return value is always non-null. If no Javadoc is available, the returned object's 229 | * {@link BaseJavadoc#isEmpty isEmpty()} method will return {@code true}. 230 | *

231 | * Implementation note: this method first retrieves the Javadoc of the class, and then matches the enum constant's 232 | * name with the correct documentation. If the client code's purpose is to loop through all enum constants docs, 233 | * prefer using {@link #getJavadoc(Class)} (or one of its overloads), and calling 234 | * {@link ClassJavadoc#getEnumConstants()} on the returned class doc to retrieve enum constant docs. 235 | * 236 | * @param enumValue the enum constant whose Javadoc you want to retrieve 237 | * @return the given enum constant's Javadoc 238 | */ 239 | public static FieldJavadoc getJavadoc(Enum enumValue) { 240 | return getSkinnyClassJavadoc(enumValue.getDeclaringClass()).findMatchingEnumConstant(enumValue); 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/SeeAlsoJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | /** 20 | * Represents a {@code @see} tag on a class or method. 21 | */ 22 | public class SeeAlsoJavadoc { 23 | 24 | public enum SeeAlsoType { 25 | STRING_LITERAL, HTML_LINK, JAVADOC_LINK 26 | } 27 | 28 | private final SeeAlsoType seeAlsoType; 29 | private final String stringLiteral; 30 | private final HtmlLink htmlLink; 31 | private final Link link; 32 | 33 | public SeeAlsoJavadoc(String stringLiteral) { 34 | this(SeeAlsoType.STRING_LITERAL, stringLiteral, null, null); 35 | } 36 | 37 | public SeeAlsoJavadoc(HtmlLink htmlLink) { 38 | this(SeeAlsoType.HTML_LINK, null, htmlLink, null); 39 | } 40 | 41 | public SeeAlsoJavadoc(Link link) { 42 | this(SeeAlsoType.JAVADOC_LINK, null, null, link); 43 | } 44 | 45 | private SeeAlsoJavadoc(SeeAlsoType seeAlsoType, String stringLiteral, HtmlLink htmlLink, Link link) { 46 | this.seeAlsoType = seeAlsoType; 47 | this.stringLiteral = stringLiteral; 48 | this.htmlLink = htmlLink; 49 | this.link = link; 50 | } 51 | 52 | public SeeAlsoType getSeeAlsoType() { 53 | return seeAlsoType; 54 | } 55 | 56 | public String getStringLiteral() { 57 | return stringLiteral; 58 | } 59 | 60 | public HtmlLink getHtmlLink() { 61 | return htmlLink; 62 | } 63 | 64 | public Link getLink() { 65 | return link; 66 | } 67 | 68 | public static class HtmlLink { 69 | private final String text; 70 | private final String link; 71 | 72 | public HtmlLink(String text, String link) { 73 | this.text = text; 74 | this.link = link; 75 | } 76 | 77 | public String getText() { 78 | return text; 79 | } 80 | 81 | public String getLink() { 82 | return link; 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/ThrowsJavadoc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | public class ThrowsJavadoc { 20 | private final String name; 21 | private final Comment comment; 22 | 23 | public ThrowsJavadoc(String name, Comment comment) { 24 | this.name = name; 25 | this.comment = comment; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public Comment getComment() { 33 | return comment; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/ToHtmlStringCommentVisitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | 20 | public class ToHtmlStringCommentVisitor implements CommentVisitor { 21 | protected StringBuilder buf = new StringBuilder(); 22 | 23 | public void commentText(String value) { 24 | buf.append(value); 25 | } 26 | 27 | public void inlineLink(Link link) { 28 | buf.append("{@link "); 29 | buf.append(link); 30 | buf.append("}"); 31 | } 32 | 33 | public void inlineTag(String name, String value) { 34 | if ("code".equals(name)) { 35 | buf.append(""); 36 | buf.append(escapeHtml(value)); 37 | buf.append(""); 38 | } else if ("literal".equals(name)) { 39 | buf.append(escapeHtml(value)); 40 | } else { 41 | buf.append("{@"); 42 | buf.append(name); 43 | buf.append(" "); 44 | buf.append(value); 45 | buf.append("}"); 46 | } 47 | } 48 | 49 | public void inlineValue(Value value) { 50 | if (value.getReferencedMemberName() == null) { 51 | buf.append("{@value}"); 52 | } else { 53 | buf.append("{@value "); 54 | buf.append(value); 55 | buf.append("}"); 56 | } 57 | } 58 | 59 | public String build() { 60 | return buf.toString(); 61 | } 62 | 63 | /** 64 | * Escapes the HTML special characters: {@code " & < >} 65 | * 66 | * @param value The value to escape 67 | * @return the input value with any instances of HTML special characters converted to character entities. 68 | */ 69 | protected static String escapeHtml(String value) { 70 | StringBuilder escaped = new StringBuilder(); 71 | 72 | for (int i = 0, len = value.length(); i < len; i++) { 73 | final char c = value.charAt(i); 74 | 75 | if (c == '"') { 76 | escaped.append("""); 77 | } else if (c == '&') { 78 | escaped.append("&"); 79 | } else if (c == '<') { 80 | escaped.append("<"); 81 | } else if (c == '>') { 82 | escaped.append(">"); 83 | } else { 84 | escaped.append(c); 85 | } 86 | } 87 | 88 | return escaped.toString(); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/ToTextListCommentVisitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Arrays; 21 | import java.util.List; 22 | 23 | 24 | public class ToTextListCommentVisitor implements CommentVisitor { 25 | protected List lines = new ArrayList<>(); 26 | 27 | public void commentText(String value) { 28 | String[] splits = value.split("\r\n|\n"); 29 | 30 | lines.addAll(Arrays.asList(splits)); 31 | } 32 | 33 | public void inlineLink(Link link) { 34 | appendInlineText(link.toString()); 35 | } 36 | 37 | public void inlineTag(String name, String value) { 38 | appendInlineText(value); 39 | } 40 | 41 | public void inlineValue(Value value) { 42 | appendInlineText(value.toString()); 43 | } 44 | 45 | public List build() { 46 | return lines; 47 | } 48 | 49 | private void appendInlineText(String txt) { 50 | if (txt == null) { 51 | } else if (lines.isEmpty()) { 52 | lines.add(txt); 53 | } else { 54 | int index = lines.size() - 1; 55 | String newLine = lines.get(index) + txt; 56 | 57 | lines.set(index, newLine); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/Value.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc; 18 | 19 | import java.util.Objects; 20 | 21 | public class Value { 22 | private final String referencedClassName; 23 | private final String referencedMemberName; 24 | 25 | public Value(String referencedClassName, String referencedMemberName) { 26 | this.referencedClassName = referencedClassName; 27 | this.referencedMemberName = referencedMemberName; 28 | } 29 | 30 | public String getReferencedClassName() { 31 | return referencedClassName; 32 | } 33 | 34 | public String getReferencedMemberName() { 35 | return referencedMemberName; 36 | } 37 | 38 | @Override 39 | public boolean equals(Object o) { 40 | if (this == o) { 41 | return true; 42 | } 43 | if (o == null || getClass() != o.getClass()) { 44 | return false; 45 | } 46 | Value link = (Value) o; 47 | return Objects.equals(referencedClassName, link.referencedClassName) 48 | && Objects.equals(referencedMemberName, link.referencedMemberName); 49 | } 50 | 51 | @Override 52 | public int hashCode() { 53 | return Objects.hash(referencedClassName, referencedMemberName); 54 | } 55 | 56 | public String toString() { 57 | StringBuilder sb = new StringBuilder(); 58 | if (referencedClassName != null) { 59 | sb.append(referencedClassName); 60 | } 61 | if (referencedMemberName != null) { 62 | sb.append('#').append(referencedMemberName); 63 | } 64 | return sb.toString(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/JsonJavadocReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal; 18 | 19 | import com.eclipsesource.json.JsonArray; 20 | import com.eclipsesource.json.JsonObject; 21 | import com.eclipsesource.json.JsonValue; 22 | import com.github.therapi.runtimejavadoc.ClassJavadoc; 23 | import com.github.therapi.runtimejavadoc.FieldJavadoc; 24 | import com.github.therapi.runtimejavadoc.MethodJavadoc; 25 | import com.github.therapi.runtimejavadoc.internal.parser.JavadocParser; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Collections; 29 | import java.util.List; 30 | 31 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.constructorsFieldName; 32 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.elementDocFieldName; 33 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.elementNameFieldName; 34 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.enumConstantsFieldName; 35 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.fieldsFieldName; 36 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.methodsFieldName; 37 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.paramTypesFieldName; 38 | 39 | public class JsonJavadocReader { 40 | 41 | public static ClassJavadoc readClassJavadoc(String qualifiedClassName, JsonObject json) { 42 | String className = qualifiedClassName.replace("$", "."); 43 | List fields = readFieldDocs(qualifiedClassName, json.get(fieldsFieldName())); 44 | List enumConstants = readFieldDocs(qualifiedClassName, json.get(enumConstantsFieldName())); 45 | List methods = readMethodDocs(qualifiedClassName, json.get(methodsFieldName())); 46 | List constructors = readMethodDocs(qualifiedClassName, json.get(constructorsFieldName())); 47 | String classJavadocString = json.getString(elementDocFieldName(), null); 48 | return JavadocParser.parseClassJavadoc(className, classJavadocString, fields, enumConstants, methods, constructors); 49 | } 50 | 51 | private static List readFieldDocs(String owningClass, JsonValue fieldsValue) { 52 | if (fieldsValue == null) { 53 | // old versions might not have this JSON field 54 | return Collections.emptyList(); 55 | } 56 | JsonArray fieldsArray = fieldsValue.asArray(); 57 | List fields = new ArrayList<>(fieldsArray.size()); 58 | for (JsonValue fieldValue : fieldsArray) { 59 | fields.add(readFieldDoc(owningClass, fieldValue)); 60 | } 61 | return fields; 62 | } 63 | 64 | private static FieldJavadoc readFieldDoc(String owningClass, JsonValue fieldValue) { 65 | JsonObject field = fieldValue.asObject(); 66 | String fieldName = field.getString(elementNameFieldName(), null); 67 | String fieldDoc = field.getString(elementDocFieldName(), null); 68 | return JavadocParser.parseFieldJavadoc(owningClass, fieldName, fieldDoc); 69 | } 70 | 71 | private static List readMethodDocs(String owningClass, JsonValue methodsValue) { 72 | JsonArray methodArray = methodsValue.asArray(); 73 | List methods = new ArrayList<>(methodArray.size()); 74 | for (JsonValue methodValue : methodArray) { 75 | methods.add(readMethodDoc(owningClass, methodValue)); 76 | } 77 | return methods; 78 | } 79 | 80 | private static MethodJavadoc readMethodDoc(String owningClass, JsonValue methodValue) { 81 | JsonObject method = methodValue.asObject(); 82 | String methodName = method.getString(elementNameFieldName(), null); 83 | List paramTypes = readParamTypes(method.get(paramTypesFieldName())); 84 | String methodDoc = method.getString(elementDocFieldName(), null); 85 | return JavadocParser.parseMethodJavadoc(owningClass, methodName, paramTypes, methodDoc); 86 | } 87 | 88 | private static List readParamTypes(JsonValue paramTypesValue) { 89 | JsonArray paramTypesArray = paramTypesValue.asArray(); 90 | List paramTypes = new ArrayList<>(paramTypesArray.size()); 91 | for (JsonValue v : paramTypesArray) { 92 | paramTypes.add(v.asString()); 93 | } 94 | return paramTypes; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/MethodSignature.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal; 18 | 19 | import com.github.therapi.runtimejavadoc.MethodJavadoc; 20 | 21 | import java.lang.reflect.Constructor; 22 | import java.lang.reflect.Executable; 23 | import java.lang.reflect.Method; 24 | import java.util.Arrays; 25 | import java.util.List; 26 | import java.util.Objects; 27 | import java.util.stream.Collectors; 28 | 29 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.INIT; 30 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.unmodifiableDefensiveCopy; 31 | import static java.util.Objects.requireNonNull; 32 | 33 | public class MethodSignature { 34 | private final String name; 35 | private final List paramTypes; 36 | 37 | private MethodSignature(String methodName, List paramTypes) { 38 | this.name = requireNonNull(methodName); 39 | this.paramTypes = unmodifiableDefensiveCopy(paramTypes); 40 | } 41 | 42 | public static MethodSignature from(MethodJavadoc methodJavadoc) { 43 | return new MethodSignature(methodJavadoc.getName(), methodJavadoc.getParamTypes()); 44 | } 45 | 46 | public static MethodSignature from(Executable executable) { 47 | List paramTypes = Arrays.stream(executable.getParameterTypes()) 48 | .map(Class::getCanonicalName) 49 | .collect(Collectors.toList()); 50 | String name; 51 | if (executable instanceof Method) { 52 | name = executable.getName(); 53 | } else if (executable instanceof Constructor) { 54 | name = INIT; 55 | } else { 56 | throw new IllegalArgumentException("Unexpected executable type: " + executable.getClass()); 57 | } 58 | 59 | return new MethodSignature(name, paramTypes); 60 | } 61 | 62 | @Override 63 | public boolean equals(Object o) { 64 | if (this == o) { 65 | return true; 66 | } 67 | if (o == null || getClass() != o.getClass()) { 68 | return false; 69 | } 70 | MethodSignature that = (MethodSignature) o; 71 | return Objects.equals(name, that.name) && Objects.equals(paramTypes, that.paramTypes); 72 | } 73 | 74 | @Override 75 | public int hashCode() { 76 | return Objects.hash(name, paramTypes); 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return name + "(" + String.join(",", paramTypes) + ")"; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/RuntimeJavadocHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal; 18 | 19 | import java.lang.reflect.Constructor; 20 | import java.lang.reflect.Executable; 21 | import java.lang.reflect.Method; 22 | import java.util.ArrayList; 23 | import java.util.Arrays; 24 | import java.util.Collections; 25 | import static java.util.Collections.unmodifiableList; 26 | import java.util.Iterator; 27 | import java.util.LinkedHashMap; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.stream.Collectors; 31 | 32 | public class RuntimeJavadocHelper { 33 | public static final String INIT = ""; 34 | 35 | private RuntimeJavadocHelper() { 36 | throw new AssertionError("not instantiable"); 37 | } 38 | 39 | public static List unmodifiableDefensiveCopy(List list) { 40 | return list == null ? Collections.emptyList() : unmodifiableList(new ArrayList<>(list)); 41 | } 42 | 43 | public static T requireNonNull(T object) { 44 | if (object == null) { 45 | throw new NullPointerException(); 46 | } 47 | return object; 48 | } 49 | 50 | public static String join(CharSequence delimiter, Iterable items) { 51 | requireNonNull(delimiter); 52 | StringBuilder result = new StringBuilder(); 53 | for (Iterator i = items.iterator(); i.hasNext(); ) { 54 | result.append(i.next()); 55 | if (i.hasNext()) { 56 | result.append(delimiter); 57 | } 58 | } 59 | return result.toString(); 60 | } 61 | 62 | public static List> getAllTypeAncestors(Class clazz) { 63 | if (clazz == null) { 64 | return Collections.emptyList(); 65 | } 66 | 67 | Map> typeAncestors = new LinkedHashMap<>(); 68 | Class superclass = clazz.getSuperclass(); 69 | if (superclass != null) { 70 | typeAncestors.put(superclass.getCanonicalName(), superclass); 71 | getAllTypeAncestors(superclass).forEach(cls -> typeAncestors.put(cls.getCanonicalName(), cls)); 72 | } 73 | 74 | Class[] interfaces = clazz.getInterfaces(); 75 | for (Class superType : interfaces) { 76 | typeAncestors.put(superType.getCanonicalName(), superType); 77 | getAllTypeAncestors(superType).forEach(cls -> typeAncestors.put(cls.getCanonicalName(), cls)); 78 | } 79 | 80 | return Collections.unmodifiableList(new ArrayList<>(typeAncestors.values())); 81 | } 82 | 83 | public static boolean isBlank(String s) { 84 | return s == null || s.trim().isEmpty(); 85 | } 86 | 87 | public static String javadocResourceSuffix() { 88 | return "__Javadoc.json"; 89 | } 90 | 91 | public static String paramTypesFieldName() { 92 | return "paramTypes"; 93 | } 94 | 95 | public static String fieldsFieldName() { 96 | return "fields"; 97 | } 98 | 99 | public static String enumConstantsFieldName() { 100 | return "enumConstants"; 101 | } 102 | 103 | public static String methodsFieldName() { 104 | return "methods"; 105 | } 106 | 107 | public static String constructorsFieldName() { 108 | return "constructors"; 109 | } 110 | 111 | public static String elementNameFieldName() { 112 | return "name"; 113 | } 114 | 115 | public static String elementDocFieldName() { 116 | return "doc"; 117 | } 118 | 119 | public static Method findBridgeMethod(Method method) { 120 | if (method.isBridge()) { 121 | return method; 122 | } 123 | 124 | Class declaringClass = method.getDeclaringClass(); 125 | for (Method bridgeMethod : declaringClass.getDeclaredMethods()) { 126 | if (bridgeMethod.isBridge() 127 | && method.getName().equals(bridgeMethod.getName()) 128 | && parametersMatchWithErasure(method.getParameterTypes(), bridgeMethod.getParameterTypes())) { 129 | return bridgeMethod; 130 | } 131 | } 132 | 133 | return null; 134 | } 135 | 136 | private static boolean parametersMatchWithErasure(Class[] parameterTypes, Class[] erasureTypes) { 137 | if (parameterTypes.length != erasureTypes.length) { 138 | return false; 139 | } 140 | 141 | for (int i = 0; i < parameterTypes.length; i++) { 142 | if (!erasureTypes[i].isAssignableFrom(parameterTypes[i])) { 143 | return false; 144 | } 145 | } 146 | 147 | return true; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/parser/BlockTag.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal.parser; 18 | 19 | public class BlockTag { 20 | 21 | final String name; 22 | 23 | final String value; 24 | 25 | public BlockTag(String name, String value) { 26 | this.name = name; 27 | this.value = value; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "@" + name + " : " + value; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/parser/CommentParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal.parser; 18 | 19 | import com.github.therapi.runtimejavadoc.Comment; 20 | import com.github.therapi.runtimejavadoc.CommentElement; 21 | import com.github.therapi.runtimejavadoc.CommentText; 22 | import com.github.therapi.runtimejavadoc.InlineLink; 23 | import com.github.therapi.runtimejavadoc.InlineTag; 24 | import com.github.therapi.runtimejavadoc.InlineValue; 25 | import com.github.therapi.runtimejavadoc.Link; 26 | import com.github.therapi.runtimejavadoc.Value; 27 | 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | import java.util.regex.Matcher; 31 | import java.util.regex.Pattern; 32 | 33 | import static com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper.isBlank; 34 | import static java.util.regex.Pattern.compile; 35 | 36 | class CommentParser { 37 | 38 | private static final Pattern inlineTag = compile("\\{@([^\\s}]+)[ \\t]*([^}]+)?}"); 39 | 40 | // https://regex101.com/r/KhEo62/4 41 | private static final Pattern valuePattern = compile("^(?:(?[\\w.]+)#)?#?(?\\w+)$"); 42 | 43 | static Comment parse(String owningClass, String commentText) { 44 | return isBlank(commentText) ? Comment.createEmpty() : new Comment(parseElements(owningClass, commentText.trim())); 45 | } 46 | 47 | private static List parseElements(String owningClass, String commentText) { 48 | Matcher matcher = inlineTag.matcher(commentText); 49 | List elements = new ArrayList<>(); 50 | int pos = 0; 51 | while (matcher.find()) { 52 | int start = matcher.start(); 53 | if (start > pos) { 54 | elements.add(new CommentText(commentText.substring(pos, start))); 55 | } 56 | CommentElement elt = createTagElement(owningClass, matcher.group(1), matcher.group(2)); 57 | if (elt != null) { 58 | elements.add(elt); 59 | } 60 | pos = matcher.end(); 61 | } 62 | 63 | if (pos < commentText.length()) { 64 | elements.add(new CommentText(commentText.substring(pos))); 65 | } 66 | return elements; 67 | } 68 | 69 | /** 70 | * @return null if tag is malformed 71 | */ 72 | private static CommentElement createTagElement(String owningClass, String name, String value) { 73 | if (value == null) { 74 | return null; 75 | } 76 | if ("link".equals(name)) { 77 | return createLinkElement(owningClass, value); 78 | } else if ("value".equals(name)) { 79 | return createValueElement(owningClass, value); 80 | } else { 81 | return new InlineTag(name, value); 82 | } 83 | } 84 | 85 | /** 86 | * @return null if tag is malformed 87 | */ 88 | private static InlineValue createValueElement(String owningClass, String value) { 89 | if (value == null || value.trim().isEmpty()) { 90 | return new InlineValue(new Value(null, null)); 91 | } 92 | 93 | Matcher linkMatcher = valuePattern.matcher(value); 94 | if (!linkMatcher.matches()) { 95 | // malformed reference 96 | return null; 97 | } 98 | String classRef = linkMatcher.group("classname"); 99 | String memberRef = linkMatcher.group("member"); 100 | 101 | String effectiveClassName = classRef == null ? owningClass : classRef; 102 | return new InlineValue(new Value(effectiveClassName, memberRef)); 103 | } 104 | 105 | private static InlineLink createLinkElement(String owningClass, String value) { 106 | Link javadocLink = LinkParser.createLinkElement(owningClass, value); 107 | if (javadocLink == null) { 108 | // malformed link 109 | return null; 110 | } 111 | return new InlineLink(javadocLink); 112 | } 113 | } -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/parser/JavadocParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal.parser; 18 | 19 | import com.github.therapi.runtimejavadoc.ClassJavadoc; 20 | import com.github.therapi.runtimejavadoc.Comment; 21 | import com.github.therapi.runtimejavadoc.FieldJavadoc; 22 | import com.github.therapi.runtimejavadoc.MethodJavadoc; 23 | import com.github.therapi.runtimejavadoc.OtherJavadoc; 24 | import com.github.therapi.runtimejavadoc.ParamJavadoc; 25 | import com.github.therapi.runtimejavadoc.SeeAlsoJavadoc; 26 | import com.github.therapi.runtimejavadoc.ThrowsJavadoc; 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | import java.util.regex.Pattern; 30 | 31 | public class JavadocParser { 32 | 33 | private static final Pattern blockSeparator = Pattern.compile("^\\s*@(?=\\S)", Pattern.MULTILINE); 34 | 35 | private static final Pattern whitespace = Pattern.compile("\\s"); 36 | 37 | private static ParamJavadoc parseParam(BlockTag t, String owningClass) { 38 | String[] paramNameAndComment = whitespace.split(t.value, 2); 39 | String paramName = paramNameAndComment[0]; 40 | String paramComment = paramNameAndComment.length == 1 ? "" : paramNameAndComment[1]; 41 | 42 | return new ParamJavadoc(paramName, CommentParser.parse(owningClass, paramComment)); 43 | } 44 | 45 | public static ClassJavadoc parseClassJavadoc(String className, String javadoc, List fields, 46 | List enumConstants, List methods, List constructors) { 47 | ParsedJavadoc parsed = parse(javadoc, className); 48 | return new ClassJavadoc(className, parsed.getDescription(), fields, enumConstants, methods, 49 | constructors, parsed.getOtherDocs(), parsed.getSeeAlsoDocs(), parsed.getParamDocs()); 50 | } 51 | 52 | public static FieldJavadoc parseFieldJavadoc(String owningClass, String fieldName, String javadoc) { 53 | ParsedJavadoc parsed = parse(javadoc, owningClass); 54 | return new FieldJavadoc(fieldName, parsed.getDescription(), parsed.getOtherDocs(), parsed.getSeeAlsoDocs()); 55 | } 56 | 57 | public static MethodJavadoc parseMethodJavadoc(String owningClass, String methodName, List paramTypes, String javadoc) { 58 | ParsedJavadoc parsed = parse(javadoc, owningClass); 59 | return new MethodJavadoc(methodName, paramTypes, parsed.getDescription(), parsed.getParamDocs(), 60 | parsed.getThrowsDocs(), parsed.getOtherDocs(), parsed.getReturns(), parsed.getSeeAlsoDocs()); 61 | } 62 | 63 | private static ParsedJavadoc parse(String javadoc, String owningClass) { 64 | String[] blocks = blockSeparator.split(javadoc); 65 | 66 | List paramDocs = new ArrayList<>(); 67 | List seeAlsoDocs = new ArrayList<>(); 68 | List throwsDocs = new ArrayList<>(); 69 | List otherDocs = new ArrayList<>(); 70 | Comment returns = null; 71 | 72 | for (int i = 1; i < blocks.length; i++) { 73 | BlockTag blockTag = parseBlockTag(blocks[i]); 74 | switch (blockTag.name) { 75 | case "param": 76 | paramDocs.add(parseParam(blockTag, owningClass)); 77 | break; 78 | case "return": 79 | returns = CommentParser.parse(owningClass, blockTag.value); 80 | break; 81 | case "see": 82 | SeeAlsoJavadoc seeAlso = SeeAlsoParser.parseSeeAlso(owningClass, blockTag.value); 83 | if (seeAlso != null) { 84 | seeAlsoDocs.add(seeAlso); 85 | } 86 | break; 87 | case "throws": 88 | case "exception": 89 | ThrowsJavadoc throwsDoc = ThrowsTagParser.parseTag(owningClass, blockTag.value); 90 | if (throwsDoc != null) { 91 | throwsDocs.add(throwsDoc); 92 | } 93 | break; 94 | default: 95 | otherDocs.add(new OtherJavadoc(blockTag.name, CommentParser.parse(owningClass, blockTag.value))); 96 | break; 97 | } 98 | } 99 | Comment description = CommentParser.parse(owningClass, blocks[0].trim()); 100 | return new ParsedJavadoc(description, otherDocs, seeAlsoDocs, paramDocs, throwsDocs, returns); 101 | } 102 | 103 | private static BlockTag parseBlockTag(String block) { 104 | String[] s = whitespace.split(block.trim(), 2); 105 | String name = s[0]; 106 | String value = s.length > 1 ? s[1] : ""; 107 | return new BlockTag(name, value); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/main/java/com/github/therapi/runtimejavadoc/internal/parser/LinkParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 David Nault and contributors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.github.therapi.runtimejavadoc.internal.parser; 18 | 19 | import com.github.therapi.runtimejavadoc.Link; 20 | 21 | import java.util.Collections; 22 | import java.util.List; 23 | import java.util.regex.Matcher; 24 | import java.util.regex.Pattern; 25 | 26 | import static java.util.Arrays.asList; 27 | import static java.util.regex.Pattern.compile; 28 | 29 | public class LinkParser { 30 | 31 | // https://regex101.com/r/3DoNfK/2 32 | private static final Pattern linkPattern = compile("^(?[\\w.]+)?(?:#(?\\w+))?(?:\\((?.*)\\))?(?:\\s(?

{@code\n    foo\n}
").getElements(); 262 | assertEquals(3, elements.size()); 263 | assertEquals(new CommentText("
"), elements.get(0));
264 |         assertEquals(new InlineTag("code", "\n    foo\n"), elements.get(1));
265 |         assertEquals(new CommentText("
"), elements.get(2)); 266 | } 267 | 268 | @Test 269 | public void parse_mix_praiseTheMightyThor() { 270 | String input = " text}bef{}ore {@link ClassName}{@} text{after}\nand {@empty}{@value #member}\n\n"; 271 | List elements = CommentParser.parse("TestClass", input).getElements(); 272 | assertEquals(5, elements.size()); 273 | assertEquals(new CommentText("text}bef{}ore "), elements.get(0)); 274 | assertEquals(new InlineLink(new Link("ClassName", "ClassName", null, null)), elements.get(1)); 275 | assertEquals(new CommentText("{@} text{after}\nand "), elements.get(2)); 276 | assertEquals(new InlineTag("empty", null), elements.get(3)); 277 | assertEquals(new InlineValue(new Value("TestClass", "member")), elements.get(4)); 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /therapi-runtime-javadoc/src/test/java/com/github/therapi/runtimejavadoc/internal/parser/ThrowsTagParserTest.java: -------------------------------------------------------------------------------- 1 | package com.github.therapi.runtimejavadoc.internal.parser; 2 | 3 | import com.github.therapi.runtimejavadoc.CommentText; 4 | import com.github.therapi.runtimejavadoc.ThrowsJavadoc; 5 | import org.junit.Test; 6 | 7 | import java.util.Arrays; 8 | import java.util.Collections; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | import static org.junit.Assert.assertNull; 12 | 13 | 14 | public class ThrowsTagParserTest { 15 | @Test 16 | public void givenNullText_expectNoDocs() { 17 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", null ); 18 | 19 | assertNull( doc ); 20 | } 21 | @Test 22 | public void givenNoExceptionOrDescription_expectNoDocs() { 23 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", "" ); 24 | 25 | assertNull( doc ); 26 | } 27 | 28 | @Test 29 | public void givenFullyQualifiedExceptionAndNoDescription_expectEmptyDescription() { 30 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", "com.github.voyage.OutOfFuelException" ); 31 | 32 | assertEquals( "com.github.voyage.OutOfFuelException", doc.getName() ); 33 | assertEquals( Collections.emptyList(), doc.getComment().getElements() ); 34 | } 35 | 36 | @Test 37 | public void givenWhitespaceAroundFullyQualifiedExceptionAndNoDescription_expectEmptyDescription() { 38 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", " com.github.voyage.OutOfFuelException " ); 39 | 40 | assertEquals( "com.github.voyage.OutOfFuelException", doc.getName() ); 41 | assertEquals( Collections.emptyList(), doc.getComment().getElements() ); 42 | } 43 | 44 | @Test 45 | public void givenRelativeExceptionAndNoDescription_expectExceptionToNotBeResolvedYet() { 46 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", "OutOfFuelException" ); 47 | 48 | assertEquals( "OutOfFuelException", doc.getName() ); 49 | assertEquals( Collections.emptyList(), doc.getComment().getElements() ); 50 | } 51 | 52 | @Test 53 | public void givenFullyQualifiedExceptionWithASingleLineDescription_expectDescription() { 54 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( "com.github.Mission", "com.github.voyage.OutOfFuelException Lorem ipsum dolor sit amet" ); 55 | 56 | assertEquals( "com.github.voyage.OutOfFuelException", doc.getName() ); 57 | assertEquals( Arrays.asList(new CommentText("Lorem ipsum dolor sit amet")), doc.getComment().getElements() ); 58 | } 59 | 60 | @Test 61 | public void givenFullyQualifiedExceptionWithMultiLineDescription_expectDescription() { 62 | ThrowsJavadoc doc = ThrowsTagParser.parseTag( 63 | "com.github.Mission", 64 | " com.github.voyage.OutOfFuelException Lorem ipsum dolor sit amet, consectetur \n" + 65 | " adipiscing elit, sed do eiusmod tempor incididunt. " ); 66 | 67 | assertEquals( "com.github.voyage.OutOfFuelException", doc.getName() ); 68 | assertEquals( Arrays.asList(new CommentText("Lorem ipsum dolor sit amet, consectetur \n" + 69 | " adipiscing elit, sed do eiusmod tempor incididunt.")), doc.getComment().getElements() ); 70 | } 71 | } 72 | --------------------------------------------------------------------------------