Polishing

- Make inner classes static where possible
 - Declare classes as final where appropriate
 - Use try-with-resources
 - Improve readability by breaking up some large methods
 - Do not throw Throwable where possible
This commit is contained in:
Andy Wilkinson
2015-06-24 14:25:31 +01:00
parent 8a0b07576d
commit f705656595
11 changed files with 78 additions and 52 deletions

View File

@@ -16,6 +16,7 @@
package org.springframework.restdocs;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
@@ -36,7 +37,7 @@ import org.springframework.util.ReflectionUtils;
* @see RestDocumentation#modifyResponseTo(ResponsePostProcessor...)
* @author Andy Wilkinson
*/
public class ResponseModifier {
public final class ResponseModifier {
private final List<ResponsePostProcessor> postProcessors;
@@ -98,7 +99,8 @@ public class ResponseModifier {
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
MethodProxy methodProxy) throws IllegalAccessException,
InvocationTargetException {
if (this.getResponseMethod.equals(method)) {
return this.response;
}

View File

@@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*
* @author Andy Wilkinson
*/
public class RestDocumentationContext {
public final class RestDocumentationContext {
private static final ThreadLocal<RestDocumentationContext> CONTEXTS = new InheritableThreadLocal<RestDocumentationContext>();

View File

@@ -83,13 +83,37 @@ public abstract class CurlDocumentation {
public void perform() throws IOException {
DocumentableHttpServletRequest request = new DocumentableHttpServletRequest(
this.result.getRequest());
this.writer.print(String.format("curl '%s://%s", request.getScheme(),
this.writer.print("curl '");
writeAuthority(request);
writePathAndQueryString(request);
this.writer.print("'");
writeOptionToIncludeHeadersInOutput();
writeHttpMethodIfNecessary(request);
writeHeaders(request);
writeContent(request);
this.writer.println();
}
private void writeAuthority(DocumentableHttpServletRequest request) {
this.writer.print(String.format("%s://%s", request.getScheme(),
request.getHost()));
if (isNonStandardPort(request)) {
this.writer.print(String.format(":%d", request.getPort()));
}
}
private boolean isNonStandardPort(DocumentableHttpServletRequest request) {
return (SCHEME_HTTP.equals(request.getScheme()) && request.getPort() != STANDARD_PORT_HTTP)
|| (SCHEME_HTTPS.equals(request.getScheme()) && request.getPort() != STANDARD_PORT_HTTPS);
}
private void writePathAndQueryString(DocumentableHttpServletRequest request) {
if (StringUtils.hasText(request.getContextPath())) {
this.writer.print(String.format(
request.getContextPath().startsWith("/") ? "%s" : "/%s",
@@ -97,20 +121,29 @@ public abstract class CurlDocumentation {
}
this.writer.print(request.getRequestUriWithQueryString());
}
this.writer.print("' -i");
private void writeOptionToIncludeHeadersInOutput() {
this.writer.print(" -i");
}
private void writeHttpMethodIfNecessary(DocumentableHttpServletRequest request) {
if (!request.isGetRequest()) {
this.writer.print(String.format(" -X %s", request.getMethod()));
}
}
private void writeHeaders(DocumentableHttpServletRequest request) {
for (Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
for (String header : entry.getValue()) {
this.writer.print(String.format(" -H '%s: %s'", entry.getKey(),
header));
}
}
}
private void writeContent(DocumentableHttpServletRequest request)
throws IOException {
if (request.getContentLength() > 0) {
this.writer
.print(String.format(" -d '%s'", request.getContentAsString()));
@@ -121,13 +154,6 @@ public abstract class CurlDocumentation {
this.writer.print(String.format(" -d '%s'", queryString));
}
}
this.writer.println();
}
private boolean isNonStandardPort(DocumentableHttpServletRequest request) {
return (SCHEME_HTTP.equals(request.getScheme()) && request.getPort() != STANDARD_PORT_HTTP)
|| (SCHEME_HTTPS.equals(request.getScheme()) && request.getPort() != STANDARD_PORT_HTTPS);
}
}

View File

@@ -63,25 +63,29 @@ public class LinkSnippetResultHandler extends SnippetWritingResultHandler {
@Override
protected void handle(MvcResult result, DocumentationWriter writer)
throws IOException {
Map<String, List<Link>> links;
validate(extractLinks(result));
writeDocumentationSnippet(writer);
}
private Map<String, List<Link>> extractLinks(MvcResult result) throws IOException {
if (this.extractor != null) {
links = this.extractor.extractLinks(result.getResponse());
return this.extractor.extractLinks(result.getResponse());
}
else {
String contentType = result.getResponse().getContentType();
LinkExtractor extractorForContentType = LinkExtractors
.extractorForContentType(contentType);
if (extractorForContentType != null) {
links = extractorForContentType.extractLinks(result.getResponse());
}
else {
throw new IllegalStateException(
"No LinkExtractor has been provided and one is not available for the content type "
+ contentType);
return extractorForContentType.extractLinks(result.getResponse());
}
throw new IllegalStateException(
"No LinkExtractor has been provided and one is not available for the content type "
+ contentType);
}
}
private void validate(Map<String, List<Link>> links) {
Set<String> actualRels = links.keySet();
Set<String> undocumentedRels = new HashSet<String>(actualRels);
@@ -105,7 +109,9 @@ public class LinkSnippetResultHandler extends SnippetWritingResultHandler {
}
throw new SnippetGenerationException(message);
}
}
private void writeDocumentationSnippet(DocumentationWriter writer) throws IOException {
writer.table(new TableAction() {
@Override
@@ -118,7 +124,6 @@ public class LinkSnippetResultHandler extends SnippetWritingResultHandler {
}
});
}
}

View File

@@ -27,7 +27,7 @@ import java.util.regex.Pattern;
* @author Andy Wilkinson
*
*/
class FieldPath {
final class FieldPath {
private static final Pattern ARRAY_INDEX_PATTERN = Pattern
.compile("\\[([0-9]+|\\*){0,1}\\]");

View File

@@ -29,7 +29,7 @@ import java.util.concurrent.atomic.AtomicReference;
* @author Andy Wilkinson
*
*/
class FieldProcessor {
final class FieldProcessor {
boolean hasField(FieldPath fieldPath, Object payload) {
final AtomicReference<Boolean> hasField = new AtomicReference<Boolean>(false);
@@ -122,7 +122,7 @@ class FieldProcessor {
}
}
private final class MapMatch implements Match {
private static final class MapMatch implements Match {
private final Object item;
@@ -154,7 +154,7 @@ class FieldProcessor {
}
private final class ListMatch implements Match {
private static final class ListMatch implements Match {
private final Iterator<?> items;
@@ -199,7 +199,7 @@ class FieldProcessor {
void remove();
}
private static class ProcessingContext {
private static final class ProcessingContext {
private final Object payload;

View File

@@ -16,6 +16,7 @@
package org.springframework.restdocs.response;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
@@ -74,7 +75,8 @@ public abstract class ContentModifyingReponsePostProcessor implements
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
MethodProxy methodProxy) throws IllegalAccessException,
InvocationTargetException {
if (this.getContentAsStringMethod.equals(method)) {
return this.modifiedContent;
}

View File

@@ -16,6 +16,7 @@
package org.springframework.restdocs.response;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@@ -78,7 +79,8 @@ class HeaderRemovingResponsePostProcessor implements ResponsePostProcessor {
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
MethodProxy methodProxy) throws IllegalAccessException,
InvocationTargetException {
if (this.getHeaderNamesMethod.equals(method)) {
List<String> headerNames = new ArrayList<>();
for (String candidate : this.response.getHeaderNames()) {

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.xml.transform.OutputKeys;
@@ -35,13 +36,14 @@ import com.fasterxml.jackson.databind.SerializationFeature;
class PrettyPrintingResponsePostProcessor extends ContentModifyingReponsePostProcessor {
private static final List<PrettyPrinter> prettyPrinters = Arrays.asList(
new JsonPrettyPrinter(), new XmlPrettyPrinter());
private static final List<PrettyPrinter> PRETTY_PRINTERS = Collections
.unmodifiableList(Arrays.asList(new JsonPrettyPrinter(),
new XmlPrettyPrinter()));
@Override
protected String modifyContent(String originalContent) {
if (StringUtils.hasText(originalContent)) {
for (PrettyPrinter prettyPrinter : prettyPrinters) {
for (PrettyPrinter prettyPrinter : PRETTY_PRINTERS) {
try {
return prettyPrinter.prettyPrint(originalContent);
}

View File

@@ -28,25 +28,16 @@ class DocumentationProperties {
private final Properties properties = new Properties();
DocumentationProperties() {
InputStream stream = getClass().getClassLoader().getResourceAsStream(
"documentation.properties");
if (stream != null) {
try {
try (InputStream stream = getClass().getClassLoader().getResourceAsStream(
"documentation.properties")) {
if (stream != null) {
this.properties.load(stream);
}
catch (IOException ex) {
throw new IllegalStateException(
"Failed to read documentation.properties", ex);
}
finally {
try {
stream.close();
}
catch (IOException e) {
// Continue
}
}
}
catch (IOException ex) {
throw new IllegalStateException("Failed to read documentation.properties", ex);
}
this.properties.putAll(System.getProperties());
}

View File

@@ -48,13 +48,9 @@ public abstract class SnippetWritingResultHandler implements ResultHandler {
@Override
public void handle(MvcResult result) throws IOException {
Writer writer = createWriter();
try {
try (Writer writer = createWriter()) {
handle(result, new AsciidoctorWriter(writer));
}
finally {
writer.close();
}
}
private Writer createWriter() throws IOException {