-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
SpringRestDocsOperationBuilderPlugin.java
175 lines (158 loc) · 6.07 KB
/
SpringRestDocsOperationBuilderPlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package springfox.documentation.spring.web.plugins;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import rawhttp.core.RawHttp;
import rawhttp.core.RawHttpResponse;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.Example;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Header;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.Collections.*;
import static java.util.stream.Collectors.*;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public class SpringRestDocsOperationBuilderPlugin implements OperationBuilderPlugin {
private Logger LOG = LoggerFactory.getLogger(SpringRestDocsOperationBuilderPlugin.class);
@Override
public void apply(OperationContext context) {
context.operationBuilder()
.responseMessages(read(context));
}
@Override
public boolean supports(DocumentationType documentationType) {
return DocumentationType.SWAGGER_12.equals(documentationType)
|| DocumentationType.SWAGGER_2.equals(documentationType);
}
/**
* Provides response messages with examples for given single operation context.
*
* @param context representing an operation
* @return response messages.
*/
protected Set<ResponseMessage> read(OperationContext context) {
Set<ResponseMessage> ret;
try {
PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourceResolver.getResources(
"classpath*:"
+ context.getName()
+ "*/http-response.springfox");
// TODO: restdocs in safe package name, not directly under restdocs
ret = Arrays.stream(resources)
.map(toRawHttpResponse())
.filter(Objects::nonNull)
.collect(Collectors.collectingAndThen(
toMap(
RawHttpResponse::getStatusCode,
mappingResponseToResponseMessageBuilder(),
mergingExamples()
),
responseMessagesMap -> responseMessagesMap.values()
.stream()
.map(ResponseMessageBuilder::build)
.collect(Collectors.toSet())));
} catch (
Exception e) {
LOG.warn("Failed to read restdocs example for {} " + context.getName() + " caused by: " + e.toString());
ret = Collections.emptySet();
}
return ret;
}
private Function<Resource, RawHttpResponse<Void>> toRawHttpResponse() {
return resource -> {
try (InputStream resourceAsStream = new FileInputStream(resource.getFile())) {
RawHttp rawHttp = new RawHttp();
// must extract the body before the stream is closed
return (RawHttpResponse<Void>) rawHttp.parseResponse(resourceAsStream).eagerly();
} catch (IOException e) {
LOG.warn("Failed to read restdocs example for {} "
+ resource.getFilename() + " caused by: " + e.toString());
return null;
}
};
}
private BinaryOperator<ResponseMessageBuilder> mergingExamples() {
return (leftWithSameStatusCode, rightWithSameStatusCode) ->
leftWithSameStatusCode.examples(rightWithSameStatusCode.build()
.getExamples());
}
private Function<RawHttpResponse<Void>, ResponseMessageBuilder> mappingResponseToResponseMessageBuilder() {
return parsedResponse -> new ResponseMessageBuilder()
.code(parsedResponse.getStatusCode())
.examples(toExamples(parsedResponse))
.headersWithDescription(toHeaders(parsedResponse));
}
private Map<String, Header> toHeaders(RawHttpResponse<Void> parsedResponse) {
return parsedResponse.getHeaders()
.asMap()
.entrySet()
.stream()
.collect(toMap(
Map.Entry::getKey,
o -> new Header(o.getKey(), "", new ModelRef("string"))));
}
private List<Example> toExamples(RawHttpResponse<Void> parsedResponse) {
return singletonList(new Example(getContentType(parsedResponse),
getBody(parsedResponse)));
}
private String getBody(RawHttpResponse<Void> parsedResponse) {
return parsedResponse.getBody()
.map(bodyReader -> {
String ret = null;
try {
ret = bodyReader.asRawString(Charset.forName("utf-8"));
} catch (IOException e) {
LOG.error("failed to read response body", e);
}
return ret;
})
.orElse(null);
}
private String getContentType(RawHttpResponse<Void> parsedResponse) {
return parsedResponse.getHeaders()
.get("Content-Type")
.stream()
.findFirst()
.orElse(null);
}
}