├── .gitignore
├── LICENSE
├── README.md
├── easy-restdocs-generator
├── build.gradle
└── src
│ └── main
│ └── java
│ └── io
│ └── github
│ └── hejow
│ └── restdocs
│ └── generator
│ ├── ApiTag.java
│ ├── ContentSupplier.java
│ ├── DocsGenerateUtil.java
│ ├── Document.java
│ └── JsonParser.java
├── easy-restdocs-gradle-plugin
├── build.gradle.kts
└── src
│ └── main
│ └── kotlin
│ └── io
│ └── github
│ └── hejow
│ └── restdocs
│ └── gradle
│ ├── EasyRestdocsPlugin.kt
│ └── EasyRestdocsTask.kt
├── gradle.properties
├── gradle
├── publish.gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── pom.xml
├── sample
├── build.gradle
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── simplerestdocs
│ │ ├── EasyRestdocsGeneratorApplication.java
│ │ └── user
│ │ ├── User.java
│ │ ├── UserController.java
│ │ ├── UserRepository.java
│ │ └── UserService.java
│ └── test
│ └── java
│ └── com
│ └── simplerestdocs
│ ├── RestDocsTest.java
│ └── user
│ ├── MyTag.java
│ └── UserControllerTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Custom ###
2 | .env
3 | *.gpg
4 |
5 | HELP.md
6 | .gradle
7 | build/
8 | !gradle/wrapper/gradle-wrapper.jar
9 | !**/src/main/**/build/
10 | !**/src/test/**/build/
11 |
12 | ### STS ###
13 | .apt_generated
14 | .classpath
15 | .factorypath
16 | .project
17 | .settings
18 | .springBeans
19 | .sts4-cache
20 | bin/
21 | !**/src/main/**/bin/
22 | !**/src/test/**/bin/
23 |
24 | ### IntelliJ IDEA ###
25 | .idea
26 | *.iws
27 | *.iml
28 | *.ipr
29 | out/
30 | !**/src/main/**/out/
31 | !**/src/test/**/out/
32 |
33 | ### NetBeans ###
34 | /nbproject/private/
35 | /nbbuild/
36 | /dist/
37 | /nbdist/
38 | /.nb-gradle/
39 |
40 | ### VS Code ###
41 | .vscode/
42 |
--------------------------------------------------------------------------------
/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 2024-present Hejow
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Easy Spring Rest-docs Generator
2 |
3 | [](https://central.sonatype.com/artifact/io.github.hejow/easy-restdocs-generator)
4 | [](https://github.com/Hejow/easy-restdocs-generator/blob/main/LICENSE)
5 |
6 | ### This is a generator that suggest easier way to use rest-docs.
7 |
8 | ## Install
9 |
10 | - `JDK 17` or higher is required
11 | - `Spring Boot 3.X` is required
12 |
13 | ### Gradle
14 |
15 | ```groovy
16 | testImplementation("io.github.hejow:easy-restdocs-generator:1.0.0")
17 | ```
18 |
19 | ### Maven
20 |
21 | ```xml
22 |
23 |
24 | io.github.hejow
25 | easy-restdocs-generator
26 | 1.0.4
27 | test
28 |
29 | ```
30 |
31 | ## How to use
32 |
33 | Only you have to do is **Customize tags** and **Use builder**.
34 |
35 | ### Customize tags
36 |
37 | To specify your api, easy-restdoc use `ApiTag` to generate documents.
38 |
39 | ```java
40 | // example
41 | public enum MyTag implements ApiTag {
42 | USER("user api");
43 |
44 | private final String content;
45 |
46 | // ... constructor
47 |
48 | @Override
49 | public String getName() {
50 | return this.content;
51 | }
52 | }
53 | ```
54 |
55 | ### Use builder
56 |
57 | After test with `mockMvc` just use builder to generate as like below.
58 |
59 | Planning to support `RestAssured`.
60 |
61 | > ### 💡 Tips
62 | >
63 | > To generate documents you MUST put `tag`, `result` on `Builder`.
64 | >
65 | > If you don’t put `identifier` on `Builder`, Method name of the test you wrote will be used as `identifier`
66 | >
67 | > Tests MUST run with rest-docs settings such as
68 | `@ExtendWith(RestDocumentationExtension.class)` ([see here](https://github.com/Hejow/easy-restdocs-generator/blob/f25657a5aa20f813d9814d00b661bf6e11d300dd/sample/src/test/java/com/simplerestdocs/user/UserControllerTest.java#L45))
69 |
70 | ```java
71 | // example
72 | @Test
73 | void myTest() throws Exception {
74 | // given
75 |
76 | // when
77 | var result = mockMvc.perform(...);
78 |
79 | // then
80 | result.andExpectAll(
81 | status().isOk(),
82 | ...
83 | );
84 |
85 | // docs
86 | result.andDo(
87 | Document.builder()
88 | .identifier("identifier of your API") // Can skip
89 | .tag(MyTag.USER) // Custom tags
90 | .summary("this will be name of API")
91 | .description("write description about your API")
92 | .result(result) // Test result
93 | .buildAndGenerate()
94 | );
95 | }
96 | ```
97 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java-library'
3 | id 'org.springframework.boot' version '3.2.3'
4 | id 'io.spring.dependency-management' version '1.1.4'
5 | id 'cl.franciscosolis.sonatype-central-upload' version '1.0.0'
6 | }
7 |
8 | apply from: "$rootDir/gradle/publish.gradle"
9 |
10 | group = "${projectGroup}"
11 | version = "${applicationVersion}"
12 | java.sourceCompatibility = JavaVersion.VERSION_17
13 |
14 | jar.archiveFileName = "${name}-${version}.jar"
15 | bootJar.enabled = false
16 |
17 | dependencies {
18 | api 'org.springframework.boot:spring-boot-starter-web'
19 | api 'org.springframework.boot:spring-boot-starter-json'
20 | api 'org.springframework.restdocs:spring-restdocs-mockmvc'
21 | api "com.epages:restdocs-api-spec-mockmvc:$restdocsApiSpecVersion"
22 | }
23 |
24 | repositories {
25 | mavenCentral()
26 | }
27 |
28 | test {
29 | useJUnitPlatform()
30 | }
31 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/src/main/java/io/github/hejow/restdocs/generator/ApiTag.java:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.generator;
2 |
3 | /**
4 | * This interface for indicate tag information to swagger.
5 | *
6 | *
7 | *
8 | *
9 | * public enum CustomTag implements ApiTag {
10 | * USER("user api"),
11 | * ...
12 | * ;
13 | *
14 | * private final String name;
15 | *
16 | * @Override
17 | * String getName() {
18 | * return this.name; // this.name() also possible
19 | * }
20 | * }
21 | *
22 | *
23 | * @see Document
24 | */
25 | public interface ApiTag {
26 | String getName();
27 | }
28 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/src/main/java/io/github/hejow/restdocs/generator/ContentSupplier.java:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.generator;
2 |
3 | import java.io.UnsupportedEncodingException;
4 |
5 | @FunctionalInterface
6 | interface ContentSupplier {
7 | String get() throws UnsupportedEncodingException;
8 | }
9 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/src/main/java/io/github/hejow/restdocs/generator/DocsGenerateUtil.java:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.generator;
2 |
3 | import com.epages.restdocs.apispec.ParameterDescriptorWithType;
4 | import com.fasterxml.jackson.databind.JsonNode;
5 | import org.springframework.mock.web.MockHttpServletRequest;
6 | import org.springframework.mock.web.MockHttpServletResponse;
7 | import org.springframework.restdocs.payload.FieldDescriptor;
8 |
9 | import java.util.Collections;
10 | import java.util.List;
11 | import java.util.Map;
12 | import java.util.Objects;
13 | import java.util.function.Function;
14 | import java.util.function.Predicate;
15 | import java.util.function.Supplier;
16 | import java.util.stream.Stream;
17 | import java.util.stream.StreamSupport;
18 |
19 | import static com.epages.restdocs.apispec.ResourceDocumentation.parameterWithName;
20 | import static java.util.Spliterator.ORDERED;
21 | import static java.util.Spliterators.spliteratorUnknownSize;
22 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
23 | import static org.springframework.web.servlet.HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
24 |
25 | final class DocsGenerateUtil {
26 | private static final Function, List> PARAMETER_NAME_PARSER = parameters -> parameters.stream()
27 | .map(ParameterDescriptorWithType::getName)
28 | .toList();
29 |
30 | private static final Function, List> PATH_PARSER = fields -> fields.stream()
31 | .map(FieldDescriptor::getPath)
32 | .toList();
33 |
34 | private static final Predicate IS_SUPPORT_TYPE = "application/json;charset=UTF-8"::contains;
35 |
36 | private static final String NULL_RESPONSE_BODY = "Response Body cannot be NULL unless HTTP status is 204.";
37 | private static final int NO_CONTENT = 204;
38 | private static final String BLANK = "";
39 |
40 | private DocsGenerateUtil() {
41 | throw new AssertionError("Can't be initialize!");
42 | }
43 |
44 | public static List requestFields(MockHttpServletRequest request, List customRequestFields) {
45 | var tree = JsonParser.readTree(request::getContentAsString);
46 |
47 | Stream requestFieldStream = tree != null ? toObjectDescriptors(tree, BLANK) : Stream.empty();
48 |
49 | return merge(() -> requestFieldStream, customRequestFields);
50 | }
51 |
52 | public static List responseFields(MockHttpServletResponse response, List customResponseFields) {
53 | if (isNotJsonOrNoContent(response)) {
54 | return Collections.emptyList();
55 | }
56 |
57 | var tree = Objects.requireNonNull(JsonParser.readTree(response::getContentAsString), NULL_RESPONSE_BODY);
58 |
59 | return merge(() -> toObjectDescriptors(tree, BLANK), customResponseFields);
60 | }
61 |
62 | private static List merge(Supplier> fields, List customFields) {
63 | var customPaths = PATH_PARSER.apply(customFields);
64 |
65 | return Stream.concat(
66 | customFields.stream(),
67 | fields.get().filter(it -> !customPaths.contains(it.getPath()))
68 | ).toList();
69 | }
70 |
71 | private static boolean isNotJsonOrNoContent(MockHttpServletResponse response) {
72 | var contentType = Objects.requireNonNullElse(response.getContentType(), BLANK);
73 |
74 | return response.getStatus() == NO_CONTENT || !IS_SUPPORT_TYPE.test(contentType);
75 | }
76 |
77 | public static List queryParameters(
78 | MockHttpServletRequest request,
79 | List customRequestParameters
80 | ) {
81 | var customs = PARAMETER_NAME_PARSER.apply(customRequestParameters);
82 |
83 | var queryParamterStream = request.getParameterMap().entrySet().stream()
84 | .filter(entry -> !customs.contains(entry.getKey()))
85 | .map(entry -> parameterWithName(entry.getKey()).description(String.join(BLANK, entry.getValue())));
86 |
87 | return Stream.concat(customRequestParameters.stream(), queryParamterStream).toList();
88 | }
89 |
90 | public static List pathVariables(
91 | MockHttpServletRequest request,
92 | List customPathVariables
93 | ) {
94 | var customs = PARAMETER_NAME_PARSER.apply(customPathVariables);
95 |
96 | var pathVariableStream = ((Map, ?>) request.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE)).entrySet().stream()
97 | .filter(entry -> !customs.contains(entry.getKey()))
98 | .map(entry -> parameterWithName(String.valueOf(entry.getKey())).description(entry.getValue()));
99 |
100 | return Stream.concat(customPathVariables.stream(), pathVariableStream).toList();
101 | }
102 |
103 | private static Stream toObjectDescriptors(JsonNode tree, String parentPath) {
104 | return StreamSupport.stream(spliteratorUnknownSize(tree.fields(), ORDERED), true)
105 | .flatMap(it -> dispatch(it.getValue(), nextObjectPath(it.getKey(), parentPath)));
106 | }
107 |
108 | private static Stream dispatch(JsonNode node, String path) {
109 | return switch (node.getNodeType()) {
110 | case OBJECT -> toObjectDescriptors(node, path);
111 | case ARRAY -> toArrayDescriptors(node, path);
112 | default -> toFieldDescriptor(node, path);
113 | };
114 | }
115 |
116 | private static Stream toArrayDescriptors(JsonNode node, String parentPath) {
117 | return node.isEmpty()
118 | ? toFieldDescriptor(node, parentPath)
119 | : StreamSupport.stream(spliteratorUnknownSize(node.elements(), ORDERED), true)
120 | .flatMap(it -> it.isObject() ? toObjectDescriptors(it, nextArrayPath(parentPath)) : toFieldDescriptor(node, parentPath));
121 | }
122 |
123 | private static Stream toFieldDescriptor(JsonNode node, String path) {
124 | var text = node.asText();
125 |
126 | var fieldDescriptor = fieldWithPath(path).description(text).type(node.getNodeType());
127 |
128 | return Stream.of(text.isBlank() ? fieldDescriptor.optional() : fieldDescriptor);
129 | }
130 |
131 | private static String nextArrayPath(String parentPath) {
132 | return "%s[]".formatted(parentPath);
133 | }
134 |
135 | private static String nextObjectPath(String currentField, String parentPath) {
136 | return parentPath.isBlank() ? currentField : "%s.%s".formatted(parentPath, currentField);
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/src/main/java/io/github/hejow/restdocs/generator/Document.java:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.generator;
2 |
3 | import com.epages.restdocs.apispec.ParameterDescriptorWithType;
4 | import com.epages.restdocs.apispec.ResourceSnippetParameters;
5 | import org.springframework.mock.web.MockHttpServletRequest;
6 | import org.springframework.mock.web.MockHttpServletResponse;
7 | import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
8 | import org.springframework.restdocs.payload.FieldDescriptor;
9 | import org.springframework.test.web.servlet.ResultActions;
10 |
11 | import java.util.Collections;
12 | import java.util.List;
13 |
14 | import static com.epages.restdocs.apispec.MockMvcRestDocumentationWrapper.document;
15 | import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
16 | import static java.util.Objects.requireNonNull;
17 | import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
18 |
19 | /**
20 | * Builders class to prevent human error such as typos.
21 | * If class safely created can call `generateDocs()` to create `RestDocumentationResultHandler`
22 | *
23 | * @see ApiTag
24 | */
25 | public class Document {
26 | private static final String DEFAULT_IDENTIFIER = "{method_name}";
27 |
28 | private final String identifier;
29 | private final String tag;
30 | private final String summary;
31 | private final String description;
32 | private final MockHttpServletRequest request;
33 | private final MockHttpServletResponse response;
34 | private final List customRequestFields;
35 | private final List customResponseFields;
36 | private final List customRequestParameters;
37 | private final List customPathVariables;
38 |
39 | public Document(
40 | String identifier,
41 | String tag,
42 | String summary,
43 | String description,
44 | MockHttpServletRequest request,
45 | MockHttpServletResponse response,
46 | List customRequestFields,
47 | List customResponseFields,
48 | List customRequestParameters,
49 | List customPathVariables
50 | ) {
51 | requireNonNull(tag, "Tag cannot be null");
52 | this.identifier = identifier;
53 | this.tag = tag;
54 | this.summary = summary;
55 | this.description = description;
56 | this.request = request;
57 | this.response = response;
58 | this.customRequestFields = customRequestFields == null ? Collections.emptyList() : customRequestFields;
59 | this.customResponseFields = customResponseFields == null ? Collections.emptyList() : customResponseFields;
60 | this.customRequestParameters = customRequestParameters == null ? Collections.emptyList() : customRequestParameters;
61 | this.customPathVariables = customPathVariables == null ? Collections.emptyList() : customPathVariables;
62 | }
63 |
64 | public static Builder builder() {
65 | return new Builder();
66 | }
67 |
68 | public RestDocumentationResultHandler generate() {
69 | return document(
70 | identifier == null ? DEFAULT_IDENTIFIER : identifier,
71 | preprocessRequest(prettyPrint()),
72 | preprocessResponse(prettyPrint()),
73 | resource(
74 | ResourceSnippetParameters.builder()
75 | .tag(tag)
76 | .summary(summary)
77 | .description(description)
78 | .requestFields(DocsGenerateUtil.requestFields(request, customRequestFields))
79 | .responseFields(DocsGenerateUtil.responseFields(response, customResponseFields))
80 | .queryParameters(DocsGenerateUtil.queryParameters(request, customRequestParameters))
81 | .pathParameters(DocsGenerateUtil.pathVariables(request, customPathVariables))
82 | .build()
83 | )
84 | );
85 | }
86 |
87 | public static class Builder {
88 | private String identifier;
89 | private ApiTag apiTag;
90 | private String summary;
91 | private String description;
92 | private ResultActions result;
93 | private MockHttpServletRequest request;
94 | private MockHttpServletResponse response;
95 | private List requestParameters;
96 | private List pathVariables;
97 | private List requestFields;
98 | private List responseFields;
99 |
100 | private Builder() {
101 | }
102 |
103 | public Builder identifier(String identifier) {
104 | this.identifier = identifier;
105 | return this;
106 | }
107 |
108 | public Builder tag(ApiTag tag) {
109 | this.apiTag = tag;
110 | return this;
111 | }
112 |
113 | public Builder summary(String summary) {
114 | this.summary = summary;
115 | return this;
116 | }
117 |
118 | public Builder description(String description) {
119 | this.description = description;
120 | return this;
121 | }
122 |
123 | public Builder result(ResultActions result) {
124 | this.result = result;
125 | return this;
126 | }
127 |
128 | public Builder request(MockHttpServletRequest request) {
129 | this.request = request;
130 | return this;
131 | }
132 |
133 | public Builder response(MockHttpServletResponse response) {
134 | this.response = response;
135 | return this;
136 | }
137 |
138 | public Builder requestParameters(List requestParameters) {
139 | this.requestParameters = requestParameters;
140 | return this;
141 | }
142 |
143 | public Builder pathVariables(List pathVariables) {
144 | this.pathVariables = pathVariables;
145 | return this;
146 | }
147 |
148 | public Builder requestFields(List requestFields) {
149 | this.requestFields = requestFields;
150 | return this;
151 | }
152 |
153 | public Builder responseFields(List responseFields) {
154 | this.responseFields = responseFields;
155 | return this;
156 | }
157 |
158 | public Document build() {
159 | if (result == null) {
160 | requireNonNull(request, "Request cannot be null");
161 | requireNonNull(response, "Response cannot be null");
162 |
163 | return new Document(
164 | identifier,
165 | apiTag.getName(),
166 | summary,
167 | description,
168 | request,
169 | response,
170 | requestFields,
171 | responseFields,
172 | requestParameters,
173 | pathVariables
174 | );
175 | }
176 |
177 | var mvcResult = result.andReturn();
178 |
179 | return new Document(
180 | identifier,
181 | apiTag.getName(),
182 | summary,
183 | description,
184 | mvcResult.getRequest(),
185 | mvcResult.getResponse(),
186 | requestFields,
187 | responseFields,
188 | requestParameters,
189 | pathVariables
190 | );
191 | }
192 |
193 | public RestDocumentationResultHandler buildAndGenerate() {
194 | return build().generate();
195 | }
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/easy-restdocs-generator/src/main/java/io/github/hejow/restdocs/generator/JsonParser.java:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.generator;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.JsonNode;
5 | import com.fasterxml.jackson.databind.ObjectMapper;
6 |
7 | import java.io.UnsupportedEncodingException;
8 |
9 | class JsonParser {
10 | private static final ObjectMapper mapper = new ObjectMapper();
11 |
12 | private JsonParser() {
13 | throw new AssertionError("can't be initialize!");
14 | }
15 |
16 | public static JsonNode readTree(ContentSupplier contentSupplier) {
17 | try {
18 | var content = contentSupplier.get();
19 |
20 | return content != null ? mapper.readTree(content) : null;
21 | } catch (UnsupportedEncodingException | JsonProcessingException exception) {
22 | throw new IllegalArgumentException("Read JsonNode Tree Failed", exception);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/easy-restdocs-gradle-plugin/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
2 |
3 | plugins {
4 | java
5 | `java-gradle-plugin`
6 | kotlin("jvm") version "1.9.22"
7 | id("com.gradle.plugin-publish") version "1.2.1"
8 | id("com.epages.restdocs-api-spec") version "0.18.2"
9 | id("org.hidetake.swagger.generator") version "2.18.2"
10 | }
11 |
12 | val projectGroup: String by project
13 | val applicationVersion: String by project
14 |
15 | group = projectGroup
16 | version = applicationVersion
17 | java.sourceCompatibility = JavaVersion.VERSION_17
18 |
19 | gradlePlugin {
20 | website = "https://github.com/Hejow/easy-restdocs-generator"
21 | vcsUrl = "https://github.com/Hejow/easy-restdocs-generator.git"
22 |
23 | plugins {
24 | create("easyRestdocsPlugin") {
25 | id = "io.github.hejow.easy-rest-docs"
26 | version = applicationVersion
27 | displayName = "easy-restdocs-generator gradle plugin"
28 | description = "Replacing the boilerplate codes with simple generator gives you an easier way to use rest-docs. And extends restdocs-api-spec to convert into SwaggerUI without any settings."
29 | tags = listOf("spring", "restdocs", "openapi3", "api", "specification")
30 | implementationClass = "io.github.hejow.restdocs.gradle.EasyRestdocsPlugin"
31 | }
32 | }
33 | }
34 |
35 | dependencies {
36 | swaggerUI("org.webjars:swagger-ui:4.1.3")
37 | }
38 |
39 | repositories {
40 | mavenCentral()
41 | }
42 |
43 | tasks.withType {
44 | kotlinOptions {
45 | freeCompilerArgs = listOf("-Xjsr305=strict", "-Xjvm-default=all")
46 | jvmTarget = "17"
47 | }
48 | }
49 |
50 | tasks.withType {
51 | useJUnitPlatform()
52 | }
53 |
--------------------------------------------------------------------------------
/easy-restdocs-gradle-plugin/src/main/kotlin/io/github/hejow/restdocs/gradle/EasyRestdocsPlugin.kt:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.gradle
2 |
3 | import org.gradle.api.Plugin
4 | import org.gradle.api.Project
5 |
6 | open class EasyRestdocsPlugin : Plugin {
7 | private fun T.applyConfiguration(): T {
8 | dependsOn("check")
9 | group = "documentation"
10 | description = "generate swaggerUI from rest-docs snippets"
11 | return this
12 | }
13 |
14 | override fun apply(project: Project) {
15 | with(project) {
16 | afterEvaluate {
17 | tasks.create("easyRestdocs", EasyRestdocsTask::class.java).applyConfiguration()
18 | }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/easy-restdocs-gradle-plugin/src/main/kotlin/io/github/hejow/restdocs/gradle/EasyRestdocsTask.kt:
--------------------------------------------------------------------------------
1 | package io.github.hejow.restdocs.gradle
2 |
3 | import org.gradle.api.DefaultTask
4 | import org.gradle.api.tasks.Input
5 | import org.gradle.api.tasks.Optional
6 | import org.gradle.api.tasks.TaskAction
7 |
8 | open class EasyRestdocsTask : DefaultTask() {
9 | @Input
10 | @Optional
11 | var servers: List = listOf()
12 |
13 | @Input
14 | @Optional
15 | var title: String? = null
16 |
17 | @Input
18 | @Optional
19 | var apiDescription: String? = null
20 |
21 | @Input
22 | @Optional
23 | var apiVersion: String? = null
24 |
25 | @Input
26 | @Optional
27 | var outputFileNamePrefix: String? = null
28 |
29 | @TaskAction
30 | fun generate() {
31 | print(this.toString())
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # application
2 | projectGroup=io.github.hejow
3 | applicationVersion=1.0.4
4 | # rest-docs
5 | restdocsApiSpecVersion=0.18.2
6 | swaggerGeneratorVersion=2.18.2
7 |
--------------------------------------------------------------------------------
/gradle/publish.gradle:
--------------------------------------------------------------------------------
1 | rootFile(".env").eachLine {line ->
2 | def (key, value) = line.tokenize('=')
3 | ext[key] = value
4 | }
5 |
6 | tasks.register('sourcesJar', Jar) {
7 | archiveClassifier.set("sources")
8 | }
9 |
10 | tasks.register('javadocJar', Jar) {
11 | archiveClassifier.set("javadoc")
12 | }
13 |
14 | artifacts {
15 | archives sourcesJar, javadocJar
16 | }
17 |
18 | sonatypeCentralUpload {
19 | username = SONATYPE_TOKEN
20 | password = SONATYPE_TOKEN_PASSWORD
21 |
22 | archives = files(
23 | "$buildDir/libs/${name}-${applicationVersion}.jar",
24 | "$buildDir/libs/${name}-${applicationVersion}-javadoc.jar",
25 | "$buildDir/libs/${name}-${applicationVersion}-sources.jar",
26 | )
27 | pom = rootFile("pom.xml")
28 |
29 | signingKey = signingKey()
30 | signingKeyPassphrase = SIGNING_PASSWORD
31 | }
32 |
33 | def signingKey() {
34 | def sb = new StringBuilder()
35 | def file = rootFile(SIGNING_KEY_FILE)
36 | file.eachLine {line -> sb.append(line).append('\n')}
37 | return sb.toString()
38 | }
39 |
40 | def rootFile(String fileName) {
41 | return file("$rootDir/$fileName")
42 | }
43 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hejow/easy-restdocs-generator/b703977b70fe1b64cb7f0139bcdb2416738433c5/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-8.5-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/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/HEAD/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 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | 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 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/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 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
5 | 4.0.0
6 |
7 | io.github.hejow
8 | easy-restdocs-generator
9 | 1.0.4
10 | jar
11 |
12 | easy-restdocs-generator
13 | Generate rest docs easy with OpenAPI spec
14 | https://github.com/Hejow/easy-restdocs-generator
15 |
16 |
17 |
18 | The Apache License, Version 2.0
19 | https://www.apache.org/licenses/LICENSE-2.0.txt
20 |
21 |
22 |
23 |
24 |
25 | Hejow
26 | Hejow Moon
27 | gmlwh124@naver.com
28 |
29 |
30 |
31 |
32 | https://github.com/Hejow/easy-restdocs-generator
33 |
34 |
35 |
36 |
37 | sonatype-nexus-staging
38 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java'
3 | id 'org.springframework.boot' version '3.2.3'
4 | id 'io.spring.dependency-management' version '1.1.4'
5 | }
6 |
7 | group = "${projectGroup}"
8 | version = "${applicationVersion}"
9 | java.sourceCompatibility = JavaVersion.VERSION_17
10 | jar.enabled = false
11 |
12 | dependencies {
13 | implementation project(':easy-restdocs-generator')
14 |
15 | implementation 'org.springframework.boot:spring-boot-starter-web'
16 | implementation 'org.springframework.boot:spring-boot-starter-json'
17 |
18 | testImplementation 'org.springframework.boot:spring-boot-starter-test'
19 | }
20 |
21 | repositories {
22 | mavenCentral()
23 | }
24 |
25 | test {
26 | useJUnitPlatform()
27 | }
28 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/simplerestdocs/EasyRestdocsGeneratorApplication.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class EasyRestdocsGeneratorApplication {
8 | public static void main(String[] args) {
9 | SpringApplication.run(EasyRestdocsGeneratorApplication.class, args);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/simplerestdocs/user/User.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | public class User {
4 | private static Long currentId = 0L;
5 |
6 | private Long id;
7 | private String name;
8 | private String email;
9 |
10 | public User(String name, String email) {
11 | this.id = ++currentId;
12 | this.name = name;
13 | this.email = email;
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public String getName() {
21 | return name;
22 | }
23 |
24 | public String getEmail() {
25 | return email;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/simplerestdocs/user/UserController.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | import org.springframework.http.ResponseEntity;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.PostMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | import java.net.URI;
9 |
10 | @RestController
11 | public class UserController {
12 | private final UserService userService;
13 |
14 | public UserController(UserService userService) {
15 | this.userService = userService;
16 | }
17 |
18 | @PostMapping("/users")
19 | public ResponseEntity> save(CreateDto request) {
20 | Long id = userService.save(request.name, request.email);
21 | return ResponseEntity.created(URI.create("/users/" + id)).build();
22 | }
23 |
24 | @GetMapping("/users")
25 | public ResponseEntity> findAll() {
26 | return ResponseEntity.ok(userService.loadAll());
27 | }
28 |
29 | public static class CreateDto {
30 | private final String name;
31 | private final String email;
32 |
33 | public CreateDto(String name, String email) {
34 | this.name = name;
35 | this.email = email;
36 | }
37 |
38 | public String getName() {
39 | return name;
40 | }
41 |
42 | public String getEmail() {
43 | return email;
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/simplerestdocs/user/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | import org.springframework.stereotype.Repository;
4 |
5 | import java.util.Collection;
6 | import java.util.List;
7 | import java.util.Map;
8 | import java.util.Optional;
9 | import java.util.concurrent.ConcurrentHashMap;
10 |
11 | @Repository
12 | public class UserRepository {
13 | private static final Map storage = new ConcurrentHashMap<>();
14 |
15 | public User save(User user) {
16 | storage.put(user.getId(), user);
17 | return user;
18 | }
19 |
20 | public void saveAll(Collection users) {
21 | for (User user : users) {
22 | storage.put(user.getId(), user);
23 | }
24 | }
25 |
26 | public Optional findById(Long id) {
27 | return Optional.ofNullable(storage.get(id));
28 | }
29 |
30 | public List findAll() {
31 | return storage.values().stream()
32 | .toList();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/simplerestdocs/user/UserService.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | import org.springframework.stereotype.Service;
4 |
5 | import java.util.List;
6 |
7 | @Service
8 | public class UserService {
9 | private final UserRepository userRepository;
10 |
11 | public UserService(UserRepository userRepository) {
12 | this.userRepository = userRepository;
13 | }
14 |
15 | public Long save(String name, String email) {
16 | User user = new User(name, email);
17 | return userRepository.save(user).getId();
18 | }
19 |
20 | public List loadAll() {
21 | return userRepository.findAll();
22 | }
23 |
24 | public User loadById(Long id) {
25 | return userRepository.findById(id)
26 | .orElseThrow(() -> new IllegalArgumentException("user not found"));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/simplerestdocs/RestDocsTest.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs;
2 |
3 | import com.fasterxml.jackson.databind.ObjectMapper;
4 | import io.github.hejow.restdocs.generator.Document;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.MethodOrderer;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.api.TestMethodOrder;
9 | import org.junit.jupiter.api.extension.ExtendWith;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
12 | import org.springframework.boot.test.context.SpringBootTest;
13 | import org.springframework.http.HttpStatus;
14 | import org.springframework.http.MediaType;
15 | import org.springframework.restdocs.RestDocumentationContextProvider;
16 | import org.springframework.restdocs.RestDocumentationExtension;
17 | import org.springframework.test.web.servlet.MockMvc;
18 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
19 | import org.springframework.web.bind.annotation.*;
20 | import org.springframework.web.filter.CharacterEncodingFilter;
21 |
22 | import java.util.List;
23 |
24 | import static java.nio.charset.StandardCharsets.UTF_8;
25 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
26 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
27 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
28 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
29 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
30 |
31 | @AutoConfigureRestDocs
32 | @ExtendWith(RestDocumentationExtension.class)
33 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
34 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
35 | class RestDocsTest {
36 | @Autowired
37 | private RestDocumentationContextProvider restDocumentation;
38 | @Autowired
39 | private ObjectMapper objectMapper;
40 |
41 | private MockMvc mockMvc;
42 |
43 | @BeforeEach
44 | void setup() {
45 | mockMvc = MockMvcBuilders
46 | .standaloneSetup(new TestController())
47 | .alwaysDo(print())
48 | .apply(documentationConfiguration(restDocumentation))
49 | .addFilter(new CharacterEncodingFilter(UTF_8.name(), true))
50 | .build();
51 | }
52 |
53 | @Test
54 | void sample1() throws Exception {
55 | // given
56 | var request = new TestDto(
57 | "first",
58 | "second",
59 | List.of(
60 | new TestDto2(
61 | "first",
62 | List.of(
63 | new TestDto3(
64 | "first",
65 | List.of(),
66 | List.of("third")
67 | )
68 | )
69 | )
70 | )
71 | );
72 |
73 | // when
74 | var result = mockMvc.perform(post("/samples")
75 | .contentType(MediaType.APPLICATION_JSON)
76 | .content(objectMapper.writeValueAsString(request)));
77 |
78 | // then
79 | result.andExpect(status().isOk());
80 |
81 | // docs
82 | result.andDo(
83 | Document.builder()
84 | .tag(() -> "Sample")
85 | .summary("Post Sample")
86 | .result(result)
87 | .buildAndGenerate()
88 | );
89 | }
90 |
91 | @Test
92 | void sample2() throws Exception {
93 | // given
94 |
95 | // when
96 | var result = mockMvc.perform(get("/samples2"));
97 |
98 | // then
99 | result.andExpect(status().isOk());
100 |
101 | // docs
102 | result.andDo(
103 | Document.builder()
104 | .tag(() -> "Sample")
105 | .summary("Get Sample")
106 | .result(result)
107 | .buildAndGenerate()
108 | );
109 | }
110 |
111 | public static class TestDto {
112 | private final String first;
113 | private final String second;
114 | private final List third;
115 |
116 | public TestDto(String first, String second, List third) {
117 | this.first = first;
118 | this.second = second;
119 | this.third = third;
120 | }
121 |
122 | public String getFirst() {
123 | return first;
124 | }
125 |
126 | public String getSecond() {
127 | return second;
128 | }
129 |
130 | public List getThird() {
131 | return third;
132 | }
133 | }
134 |
135 | public static class TestDto2 {
136 | private final String first;
137 | private final List second;
138 |
139 | public TestDto2(String first, List second) {
140 | this.first = first;
141 | this.second = second;
142 | }
143 |
144 | public String getFirst() {
145 | return first;
146 | }
147 |
148 | public List getSecond() {
149 | return second;
150 | }
151 | }
152 |
153 | public static class TestDto3 {
154 | private final String first;
155 | private final List second;
156 | private final List third;
157 |
158 | public TestDto3(String first, List second, List third) {
159 | this.first = first;
160 | this.second = second;
161 | this.third = third;
162 | }
163 |
164 | public String getFirst() {
165 | return first;
166 | }
167 |
168 | public List getSecond() {
169 | return second;
170 | }
171 |
172 | public List getThird() {
173 | return third;
174 | }
175 | }
176 |
177 | @RestController
178 | public static class TestController {
179 | @SuppressWarnings("unused")
180 | @PostMapping("/samples")
181 | @ResponseStatus(HttpStatus.OK)
182 | public void sample(@RequestBody TestDto request) {
183 | }
184 |
185 | @GetMapping("/samples2")
186 | @ResponseStatus(HttpStatus.OK)
187 | public Response> sample2() {
188 | var response = new TestDto(
189 | "first",
190 | "second",
191 | List.of(
192 | new TestDto2(
193 | "first",
194 | List.of(
195 | new TestDto3(
196 | "first",
197 | List.of(),
198 | List.of("third")
199 | )
200 | )
201 | )
202 | )
203 | );
204 |
205 | return new Response<>(response);
206 | }
207 | }
208 |
209 | public static class Response {
210 | private final T data;
211 |
212 | public Response(T data) {
213 | this.data = data;
214 | }
215 |
216 | public T getData() {
217 | return data;
218 | }
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/simplerestdocs/user/MyTag.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | import io.github.hejow.restdocs.generator.ApiTag;
4 |
5 | public enum MyTag implements ApiTag {
6 | USER("user api"),
7 | ;
8 |
9 | private final String content;
10 |
11 | MyTag(String content) {
12 | this.content = content;
13 | }
14 |
15 | @Override
16 | public String getName() {
17 | return this.content;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/simplerestdocs/user/UserControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.simplerestdocs.user;
2 |
3 | import com.fasterxml.jackson.databind.ObjectMapper;
4 | import io.github.hejow.restdocs.generator.Document;
5 | import org.junit.jupiter.api.*;
6 | import org.junit.jupiter.api.extension.ExtendWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.http.MediaType;
11 | import org.springframework.restdocs.RestDocumentationContextProvider;
12 | import org.springframework.restdocs.RestDocumentationExtension;
13 | import org.springframework.test.web.servlet.MockMvc;
14 | import org.springframework.test.web.servlet.ResultActions;
15 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
16 | import org.springframework.web.context.WebApplicationContext;
17 | import org.springframework.web.filter.CharacterEncodingFilter;
18 |
19 | import java.util.List;
20 |
21 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
22 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
23 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
24 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
25 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
26 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
27 |
28 | @AutoConfigureMockMvc
29 | @ExtendWith(RestDocumentationExtension.class)
30 | @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
31 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
32 | class UserControllerTest {
33 | @Autowired
34 | private MockMvc mockMvc;
35 | @Autowired
36 | private ObjectMapper objectMapper;
37 | @Autowired
38 | private UserRepository userRepository;
39 |
40 | @BeforeEach
41 | void setup(
42 | WebApplicationContext webApplicationContext,
43 | RestDocumentationContextProvider restDocumentation
44 | ) {
45 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
46 | .alwaysDo(print())
47 | .apply(documentationConfiguration(restDocumentation))
48 | .addFilter(new CharacterEncodingFilter("UTF-8", true))
49 | .build();
50 | }
51 |
52 | @Test
53 | @Order(2)
54 | void saveTest() throws Exception {
55 | // given
56 | UserController.CreateDto request = new UserController.CreateDto("john", "no-reply@gmail.com");
57 |
58 | // when
59 | ResultActions result = mockMvc.perform(post("/users")
60 | .contentType(MediaType.APPLICATION_JSON)
61 | .content(objectMapper.writeValueAsString(request)));
62 |
63 | // then
64 | result.andExpect(status().isCreated());
65 |
66 | // docs
67 | result.andDo(
68 | Document.builder()
69 | .identifier("user-create-success")
70 | .tag(MyTag.USER)
71 | .summary("user-create-api")
72 | .description("save new user")
73 | .result(result)
74 | .buildAndGenerate()
75 | );
76 | }
77 |
78 | @Test
79 | @Order(1)
80 | void loadAllTest() throws Exception {
81 | // given
82 | User john = new User("john", "no-reply@google.com");
83 | User mike = new User("mike", "no-reply@apple.com");
84 |
85 | userRepository.saveAll(List.of(john, mike));
86 |
87 | // when
88 | ResultActions result = mockMvc.perform(get("/users")
89 | .contentType(MediaType.APPLICATION_JSON));
90 |
91 | // then
92 | result.andExpectAll(
93 | status().isOk(),
94 | jsonPath("$[0].id").value(john.getId()),
95 | jsonPath("$[0].name").value(john.getName()),
96 | jsonPath("$[0].email").value(john.getEmail())
97 | );
98 |
99 | // docs
100 | result.andDo(
101 | Document.builder()
102 | .identifier("load-all-users-success")
103 | .tag(MyTag.USER)
104 | .summary("get-all-users-api")
105 | .description("load all saved users")
106 | .result(result)
107 | .buildAndGenerate()
108 | );
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'easy-restdocs'
2 |
3 | include 'easy-restdocs-generator'
4 | include 'easy-restdocs-gradle-plugin'
5 | include 'sample'
6 |
--------------------------------------------------------------------------------