Upgrade to Spring Java Format 0.0.15

This commit is contained in:
Andy Wilkinson
2019-08-30 11:07:04 +01:00
parent f7bd5faecf
commit 508b3d6593
180 changed files with 3367 additions and 5437 deletions

View File

@@ -127,7 +127,7 @@ configure(subprojects - project(":docs")) { subproject ->
checkstyle {
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
configProperties = [ 'checkstyle.config.dir' : rootProject.file('config/checkstyle') ]
toolVersion = '6.10.1'
toolVersion = '8.22'
}
configurations {
@@ -254,4 +254,4 @@ configurations {
artifacts {
archives docsZip
}
}

View File

@@ -1,3 +1,3 @@
version=1.2.7.BUILD-SNAPSHOT
javaFormatVersion=0.0.7-SNAPSHOT
javaFormatVersion=0.0.15
org.gradle.daemon=false

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -32,8 +32,8 @@ final class DefaultAttributesPreprocessor extends Preprocessor {
@Override
public PreprocessorReader process(Document document, PreprocessorReader reader) {
document.setAttr("snippets", this.snippetsDirectoryResolver
.getSnippetsDirectory(document.getAttributes()), false);
document.setAttr("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()),
false);
return reader;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -28,11 +28,9 @@ public final class RestDocsExtensionRegistry implements ExtensionRegistry {
@Override
public void register(Asciidoctor asciidoctor) {
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesPreprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesPreprocessor());
asciidoctor.rubyExtensionRegistry()
.loadClass(RestDocsExtensionRegistry.class
.getResourceAsStream("/extensions/operation_block_macro.rb"))
.loadClass(RestDocsExtensionRegistry.class.getResourceAsStream("/extensions/operation_block_macro.rb"))
.blockMacro("operation", "OperationBlockMacro");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -40,8 +40,7 @@ class SnippetsDirectoryResolver {
private File getMavenSnippetsDirectory(Map<String, Object> attributes) {
Path docdir = Paths.get(getRequiredAttribute(attributes, "docdir"));
return new File(docdir.relativize(findPom(docdir).getParent()).toFile(),
"target/generated-snippets");
return new File(docdir.relativize(findPom(docdir).getParent()).toFile(), "target/generated-snippets");
}
private Path findPom(Path docdir) {
@@ -57,8 +56,7 @@ class SnippetsDirectoryResolver {
}
private File getGradleSnippetsDirectory(Map<String, Object> attributes) {
return new File(getRequiredAttribute(attributes, "projectdir"),
"build/generated-snippets");
return new File(getRequiredAttribute(attributes, "projectdir"), "build/generated-snippets");
}
private String getRequiredAttribute(Map<String, Object> attributes, String name) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -37,8 +37,7 @@ public class DefaultAttributesPreprocessorTests {
Options options = new Options();
options.setAttributes(new Attributes("projectdir=../../.."));
String converted = Asciidoctor.Factory.create().convert("{snippets}", options);
assertThat(converted)
.contains("build" + File.separatorChar + "generated-snippets");
assertThat(converted).contains("build" + File.separatorChar + "generated-snippets");
}
@Test
@@ -53,8 +52,7 @@ public class DefaultAttributesPreprocessorTests {
public void snippetsAttributeFromDocumentPreambleIsNotOverridden() {
Options options = new Options();
options.setAttributes(new Attributes("projectdir=../../.."));
String converted = Asciidoctor.Factory.create()
.convert(":snippets: custom\n{snippets}", options);
String converted = Asciidoctor.Factory.create().convert(":snippets: custom\n{snippets}", options);
assertThat(converted).contains("custom");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -57,8 +57,7 @@ public class OperationBlockMacroTests {
public static void prepareOperationSnippets() throws IOException {
File destination = new File("build/generated-snippets/some-operation");
destination.mkdirs();
FileSystemUtils.copyRecursively(new File("src/test/resources/some-operation"),
destination);
FileSystemUtils.copyRecursively(new File("src/test/resources/some-operation"), destination);
}
@Before
@@ -68,8 +67,7 @@ public class OperationBlockMacroTests {
@Test
public void codeBlockSnippetInclude() throws Exception {
String result = this.asciidoctor.convert(
"operation::some-operation[snippets='curl-request']", this.options);
String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple"));
}
@@ -78,41 +76,34 @@ public class OperationBlockMacroTests {
Attributes attributes = getAttributes();
attributes.setAttribute("name", "some");
this.options.setAttributes(attributes);
String result = this.asciidoctor.convert(
"operation::{name}-operation[snippets='curl-request']", this.options);
String result = this.asciidoctor.convert("operation::{name}-operation[snippets='curl-request']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple"));
}
@Test
public void codeBlockSnippetIncludeWithPdfBackend() throws Exception {
File output = configurePdfOutput();
this.asciidoctor.convert("operation::some-operation[snippets='curl-request']",
this.options);
assertThat(extractStrings(output)).containsExactly("Curl request",
"$ curl 'http://localhost:8080/' -i", "1");
this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options);
assertThat(extractStrings(output)).containsExactly("Curl request", "$ curl 'http://localhost:8080/' -i", "1");
}
@Test
public void tableSnippetInclude() throws Exception {
String result = this.asciidoctor.convert(
"operation::some-operation[snippets='response-fields']", this.options);
String result = this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-table"));
}
@Test
public void tableSnippetIncludeWithPdfBackend() throws Exception {
File output = configurePdfOutput();
this.asciidoctor.convert("operation::some-operation[snippets='response-fields']",
this.options);
assertThat(extractStrings(output)).containsExactly("Response fields", "Path",
"Type", "Description", "a", "Object", "one", "a.b", "Number", "two",
"a.c", "String", "three", "1");
this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options);
assertThat(extractStrings(output)).containsExactly("Response fields", "Path", "Type", "Description", "a",
"Object", "one", "a.b", "Number", "two", "a.c", "String", "three", "1");
}
@Test
public void includeSnippetInSection() throws Exception {
String result = this.asciidoctor.convert(
"== Section\n" + "operation::some-operation[snippets='curl-request']",
String result = this.asciidoctor.convert("== Section\n" + "operation::some-operation[snippets='curl-request']",
this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section"));
}
@@ -120,83 +111,64 @@ public class OperationBlockMacroTests {
@Test
public void includeSnippetInSectionWithPdfBackend() throws Exception {
File output = configurePdfOutput();
this.asciidoctor.convert(
"== Section\n" + "operation::some-operation[snippets='curl-request']",
this.options);
this.asciidoctor.convert("== Section\n" + "operation::some-operation[snippets='curl-request']", this.options);
assertThat(extractStrings(output)).containsExactly("Section", "Curl request",
"$ curl 'http://localhost:8080/' -i", "1");
}
@Test
public void includeMultipleSnippets() throws Exception {
String result = this.asciidoctor.convert(
"operation::some-operation[snippets='curl-request,http-request']",
String result = this.asciidoctor.convert("operation::some-operation[snippets='curl-request,http-request']",
this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("multiple-snippets"));
}
@Test
public void useMacroWithoutSnippetAttributeAddsAllSnippets() throws Exception {
String result = this.asciidoctor.convert("operation::some-operation[]",
this.options);
String result = this.asciidoctor.convert("operation::some-operation[]", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets"));
}
@Test
public void useMacroWithEmptySnippetAttributeAddsAllSnippets() throws Exception {
String result = this.asciidoctor.convert("operation::some-operation[snippets=]",
this.options);
String result = this.asciidoctor.convert("operation::some-operation[snippets=]", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets"));
}
@Test
public void includingMissingSnippetAddsWarning() throws Exception {
String result = this.asciidoctor.convert(
"operation::some-operation[snippets='missing-snippet']", this.options);
String result = this.asciidoctor.convert("operation::some-operation[snippets='missing-snippet']", this.options);
assertThat(result).startsWith(getExpectedContentFromFile("missing-snippet"));
}
@Test
public void defaultTitleIsProvidedForCustomSnippet() throws Exception {
String result = this.asciidoctor.convert(
"operation::some-operation[snippets='custom-snippet']", this.options);
assertThat(result)
.isEqualTo(getExpectedContentFromFile("custom-snippet-default-title"));
String result = this.asciidoctor.convert("operation::some-operation[snippets='custom-snippet']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-default-title"));
}
@Test
public void missingOperationIsHandledGracefully() throws Exception {
String result = this.asciidoctor.convert("operation::missing-operation[]",
this.options);
String result = this.asciidoctor.convert("operation::missing-operation[]", this.options);
assertThat(result).startsWith(getExpectedContentFromFile("missing-operation"));
}
@Test
public void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute()
throws URISyntaxException, IOException {
String result = this.asciidoctor.convert(
":operation-curl-request-title: Example request\n"
+ "operation::some-operation[snippets='curl-request']",
this.options);
assertThat(result)
.isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title"));
public void titleOfBuiltInSnippetCanBeCustomizedUsingDocumentAttribute() throws URISyntaxException, IOException {
String result = this.asciidoctor.convert(":operation-curl-request-title: Example request\n"
+ "operation::some-operation[snippets='curl-request']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title"));
}
@Test
public void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute()
throws Exception {
String result = this.asciidoctor.convert(
":operation-custom-snippet-title: Customized title\n"
+ "operation::some-operation[snippets='custom-snippet']",
this.options);
assertThat(result)
.isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title"));
public void titleOfCustomSnippetCanBeCustomizedUsingDocumentAttribute() throws Exception {
String result = this.asciidoctor.convert(":operation-custom-snippet-title: Customized title\n"
+ "operation::some-operation[snippets='custom-snippet']", this.options);
assertThat(result).isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title"));
}
private String getExpectedContentFromFile(String fileName)
throws URISyntaxException, IOException {
Path filePath = Paths.get(
this.getClass().getResource("/operations/" + fileName + ".html").toURI());
private String getExpectedContentFromFile(String fileName) throws URISyntaxException, IOException {
Path filePath = Paths.get(this.getClass().getResource("/operations/" + fileName + ".html").toURI());
String content = new String(Files.readAllBytes(filePath));
if (isWindows()) {
return content.replace("\r\n", "\n");
@@ -234,8 +206,7 @@ public class OperationBlockMacroTests {
private final List<String> strings = new ArrayList<>();
@Override
protected void processOperator(Operator operator, List<COSBase> operands)
throws IOException {
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
if ("Tj".equals(operator.getName())) {
for (COSBase operand : operands) {
if (operand instanceof COSString) {
@@ -245,7 +216,7 @@ public class OperationBlockMacroTests {
}
}
public List<String> getStrings() {
private List<String> getStrings() {
return this.strings;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -43,34 +43,27 @@ public class SnippetsDirectoryResolverTests {
public ExpectedException thrown = ExpectedException.none();
@Test
public void mavenProjectsUseTargetGeneratedSnippetsRelativeToDocdir()
throws IOException {
public void mavenProjectsUseTargetGeneratedSnippetsRelativeToDocdir() throws IOException {
this.temporaryFolder.newFile("pom.xml");
Map<String, Object> attributes = new HashMap<>();
attributes.put("docdir",
new File(this.temporaryFolder.getRoot(), "src/main/asciidoc")
.getAbsolutePath());
attributes.put("docdir", new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath());
File snippetsDirectory = getMavenSnippetsDirectory(attributes);
assertThat(snippetsDirectory).isRelative();
assertThat(snippetsDirectory)
.isEqualTo(new File("../../../target/generated-snippets"));
assertThat(snippetsDirectory).isEqualTo(new File("../../../target/generated-snippets"));
}
@Test
public void illegalStateExceptionWhenMavenPomCannotBeFound() throws IOException {
Map<String, Object> attributes = new HashMap<>();
String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc")
.getAbsolutePath();
String docdir = new File(this.temporaryFolder.getRoot(), "src/main/asciidoc").getAbsolutePath();
attributes.put("docdir", docdir);
this.thrown.expect(IllegalStateException.class);
this.thrown
.expectMessage(equalTo("pom.xml not found in '" + docdir + "' or above"));
this.thrown.expectMessage(equalTo("pom.xml not found in '" + docdir + "' or above"));
getMavenSnippetsDirectory(attributes);
}
@Test
public void illegalStateWhenDocdirAttributeIsNotSetInMavenProject()
throws IOException {
public void illegalStateWhenDocdirAttributeIsNotSetInMavenProject() throws IOException {
Map<String, Object> attributes = new HashMap<>();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(equalTo("docdir attribute not found"));
@@ -78,19 +71,15 @@ public class SnippetsDirectoryResolverTests {
}
@Test
public void gradleProjectsUseBuildGeneratedSnippetsBeneathProjectDir()
throws IOException {
public void gradleProjectsUseBuildGeneratedSnippetsBeneathProjectDir() throws IOException {
Map<String, Object> attributes = new HashMap<>();
attributes.put("projectdir", "project/dir");
File snippetsDirectory = new SnippetsDirectoryResolver()
.getSnippetsDirectory(attributes);
assertThat(snippetsDirectory)
.isEqualTo(new File("project/dir/build/generated-snippets"));
File snippetsDirectory = new SnippetsDirectoryResolver().getSnippetsDirectory(attributes);
assertThat(snippetsDirectory).isEqualTo(new File("project/dir/build/generated-snippets"));
}
@Test
public void illegalStateWhenProjectdirAttributeIsNotSetInGradleProject()
throws IOException {
public void illegalStateWhenProjectdirAttributeIsNotSetInGradleProject() throws IOException {
Map<String, Object> attributes = new HashMap<>();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(equalTo("projectdir attribute not found"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -27,8 +27,7 @@ import org.junit.runners.model.Statement;
* @author Andy Wilkinson
* @since 1.1.0
*/
public class JUnitRestDocumentation
implements RestDocumentationContextProvider, TestRule {
public class JUnitRestDocumentation implements RestDocumentationContextProvider, TestRule {
private final ManualRestDocumentation delegate;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -68,11 +68,9 @@ public final class ManualRestDocumentation implements RestDocumentationContextPr
@SuppressWarnings("deprecation")
public void beforeTest(Class<?> testClass, String testMethodName) {
if (this.context != null) {
throw new IllegalStateException(
"Context already exists. Did you forget to call afterTest()?");
throw new IllegalStateException("Context already exists. Did you forget to call afterTest()?");
}
this.context = new RestDocumentationContext(testClass, testMethodName,
this.outputDirectory);
this.context = new RestDocumentationContext(testClass, testMethodName, this.outputDirectory);
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -45,8 +45,7 @@ public final class RestDocumentationContext {
* @deprecated Since 1.1 in favor of {@link ManualRestDocumentation}.
*/
@Deprecated
public RestDocumentationContext(Class<?> testClass, String testMethodName,
File outputDirectory) {
public RestDocumentationContext(Class<?> testClass, String testMethodName, File outputDirectory) {
this.testClass = testClass;
this.testMethodName = testMethodName;
this.outputDirectory = outputDirectory;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -80,8 +80,7 @@ public abstract class CliDocumentation {
* @return the snippet that will document the curl request
* @since 1.2.0
*/
public static Snippet curlRequest(Map<String, Object> attributes,
CommandFormatter commandFormatter) {
public static Snippet curlRequest(Map<String, Object> attributes, CommandFormatter commandFormatter) {
return new CurlRequestSnippet(attributes, commandFormatter);
}
@@ -127,8 +126,7 @@ public abstract class CliDocumentation {
* @return the snippet that will document the HTTPie request
* @since 1.2.0
*/
public static Snippet httpieRequest(Map<String, Object> attributes,
CommandFormatter commandFormatter) {
public static Snippet httpieRequest(Map<String, Object> attributes, CommandFormatter commandFormatter) {
return new HttpieRequestSnippet(attributes, commandFormatter);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -48,19 +48,16 @@ final class CliOperationRequest implements OperationRequest {
CliOperationRequest(OperationRequest delegate) {
this.delegate = delegate;
this.headerFilters = new HashSet<>(Arrays.asList(
new NamedHeaderFilter(HttpHeaders.CONTENT_LENGTH),
this.headerFilters = new HashSet<>(Arrays.asList(new NamedHeaderFilter(HttpHeaders.CONTENT_LENGTH),
new BasicAuthHeaderFilter(), new HostHeaderFilter(delegate.getUri())));
}
boolean isPutOrPost() {
return HttpMethod.PUT.equals(this.delegate.getMethod())
|| HttpMethod.POST.equals(this.delegate.getMethod());
return HttpMethod.PUT.equals(this.delegate.getMethod()) || HttpMethod.POST.equals(this.delegate.getMethod());
}
String getBasicAuthCredentials() {
List<String> headerValue = this.delegate.getHeaders()
.get(HttpHeaders.AUTHORIZATION);
List<String> headerValue = this.delegate.getHeaders().get(HttpHeaders.AUTHORIZATION);
if (BasicAuthHeaderFilter.isBasicAuthHeader(headerValue)) {
return BasicAuthHeaderFilter.decodeBasicAuthHeader(headerValue);
}
@@ -94,11 +91,9 @@ final class CliOperationRequest implements OperationRequest {
return false;
}
}
if (HttpHeaders.HOST.equalsIgnoreCase(header.getKey())
&& (!header.getValue().isEmpty())) {
if (HttpHeaders.HOST.equalsIgnoreCase(header.getKey()) && (!header.getValue().isEmpty())) {
String value = header.getValue().get(0);
if (value.equals(this.delegate.getUri().getHost() + ":"
+ this.delegate.getUri().getPort())) {
if (value.equals(this.delegate.getUri().getHost() + ":" + this.delegate.getUri().getPort())) {
return false;
}
}
@@ -144,8 +139,7 @@ final class CliOperationRequest implements OperationRequest {
}
static boolean isBasicAuthHeader(List<String> value) {
return value != null && (!value.isEmpty())
&& value.get(0).startsWith("Basic ");
return value != null && (!value.isEmpty()) && value.get(0).startsWith("Basic ");
}
static String decodeBasicAuthHeader(List<String> value) {
@@ -179,13 +173,11 @@ final class CliOperationRequest implements OperationRequest {
@Override
public boolean allow(String name, List<String> value) {
return !(value.isEmpty()
|| this.getImplicitHostHeader().equals(value.get(0)));
return !(value.isEmpty() || this.getImplicitHostHeader().equals(value.get(0)));
}
private String getImplicitHostHeader() {
return this.uri.getHost()
+ ((this.uri.getPort() == -1) ? "" : ":" + this.uri.getPort());
return this.uri.getHost() + ((this.uri.getPort() == -1) ? "" : ":" + this.uri.getPort());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -87,8 +87,7 @@ public class CurlRequestSnippet extends TemplatedSnippet {
* @param attributes the additional attributes
* @param commandFormatter the formatter for generating the snippet
*/
protected CurlRequestSnippet(Map<String, Object> attributes,
CommandFormatter commandFormatter) {
protected CurlRequestSnippet(Map<String, Object> attributes, CommandFormatter commandFormatter) {
super("curl-request", attributes);
Assert.notNull(commandFormatter, "Command formatter must not be null");
this.commandFormatter = commandFormatter;
@@ -104,20 +103,17 @@ public class CurlRequestSnippet extends TemplatedSnippet {
private String getUrl(Operation operation) {
OperationRequest request = operation.getRequest();
Parameters uniqueParameters = request.getParameters()
.getUniqueParameters(operation.getRequest().getUri());
Parameters uniqueParameters = request.getParameters().getUniqueParameters(operation.getRequest().getUri());
if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) {
return String.format("'%s%s%s'", request.getUri(),
StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?",
uniqueParameters.toQueryString());
StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString());
}
return String.format("'%s'", request.getUri());
}
private boolean includeParametersInUri(OperationRequest request) {
return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0
&& !MediaType.APPLICATION_FORM_URLENCODED
.isCompatibleWith(request.getHeaders().getContentType()));
&& !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType()));
}
private String getOptions(Operation operation) {
@@ -146,8 +142,7 @@ public class CurlRequestSnippet extends TemplatedSnippet {
if (cookiesBuilder.length() > 0) {
cookiesBuilder.append(";");
}
cookiesBuilder.append(
String.format("%s=%s", cookie.getName(), cookie.getValue()));
cookiesBuilder.append(String.format("%s=%s", cookie.getName(), cookie.getValue()));
}
lines.add(String.format("--cookie '%s'", cookiesBuilder.toString()));
}
@@ -157,8 +152,7 @@ public class CurlRequestSnippet extends TemplatedSnippet {
builder.append("-i");
}
private void writeUserOptionIfNecessary(CliOperationRequest request,
StringBuilder builder) {
private void writeUserOptionIfNecessary(CliOperationRequest request, StringBuilder builder) {
String credentials = request.getBasicAuthCredentials();
if (credentials != null) {
builder.append(String.format(" -u '%s'", credentials));
@@ -213,10 +207,8 @@ public class CurlRequestSnippet extends TemplatedSnippet {
}
}
private void writeContentUsingParameters(OperationRequest request,
List<String> lines) {
Parameters uniqueParameters = request.getParameters()
.getUniqueParameters(request.getUri());
private void writeContentUsingParameters(OperationRequest request, List<String> lines) {
Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri());
String queryString = uniqueParameters.toQueryString();
if (StringUtils.hasText(queryString)) {
lines.add(String.format("-d '%s'", queryString));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -88,8 +88,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
* @param attributes the additional attributes
* @param commandFormatter the formatter for generating the snippet
*/
protected HttpieRequestSnippet(Map<String, Object> attributes,
CommandFormatter commandFormatter) {
protected HttpieRequestSnippet(Map<String, Object> attributes, CommandFormatter commandFormatter) {
super("httpie-request", attributes);
Assert.notNull(commandFormatter, "Command formatter must not be null");
this.commandFormatter = commandFormatter;
@@ -124,12 +123,10 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
}
private String getUrl(OperationRequest request) {
Parameters uniqueParameters = request.getParameters()
.getUniqueParameters(request.getUri());
Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri());
if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) {
return String.format("'%s%s%s'", request.getUri(),
StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?",
uniqueParameters.toQueryString());
StringUtils.hasText(request.getUri().getRawQuery()) ? "&" : "?", uniqueParameters.toQueryString());
}
return String.format("'%s'", request.getUri());
}
@@ -146,28 +143,23 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
}
private void writeOptions(OperationRequest request, PrintWriter writer) {
if (!request.getParts().isEmpty()
|| (!request.getParameters().getUniqueParameters(request.getUri())
.isEmpty() && !includeParametersInUri(request)
&& includeParametersAsFormOptions(request))) {
if (!request.getParts().isEmpty() || (!request.getParameters().getUniqueParameters(request.getUri()).isEmpty()
&& !includeParametersInUri(request) && includeParametersAsFormOptions(request))) {
writer.print("--form ");
}
}
private boolean includeParametersInUri(OperationRequest request) {
return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0
&& !MediaType.APPLICATION_FORM_URLENCODED
.isCompatibleWith(request.getHeaders().getContentType()));
&& !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType()));
}
private boolean includeParametersAsFormOptions(OperationRequest request) {
return request.getMethod() != HttpMethod.GET && (request.getContent().length == 0
|| !MediaType.APPLICATION_FORM_URLENCODED
.isCompatibleWith(request.getHeaders().getContentType()));
|| !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType()));
}
private void writeUserOptionIfNecessary(CliOperationRequest request,
PrintWriter writer) {
private void writeUserOptionIfNecessary(CliOperationRequest request, PrintWriter writer) {
String credentials = request.getBasicAuthCredentials();
if (credentials != null) {
writer.print(String.format("--auth '%s' ", credentials));
@@ -199,8 +191,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
for (Entry<String, List<String>> entry : headers.entrySet()) {
for (String header : entry.getValue()) {
// HTTPie adds Content-Type automatically with --form
if (!request.getParts().isEmpty()
&& entry.getKey().equals(HttpHeaders.CONTENT_TYPE)
if (!request.getParts().isEmpty() && entry.getKey().equals(HttpHeaders.CONTENT_TYPE)
&& header.startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
continue;
}
@@ -211,13 +202,11 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
private void writeCookies(OperationRequest request, List<String> lines) {
for (RequestCookie cookie : request.getCookies()) {
lines.add(
String.format("'Cookie:%s=%s'", cookie.getName(), cookie.getValue()));
lines.add(String.format("'Cookie:%s=%s'", cookie.getName(), cookie.getValue()));
}
}
private void writeParametersIfNecessary(CliOperationRequest request,
List<String> lines) {
private void writeParametersIfNecessary(CliOperationRequest request, List<String> lines) {
if (StringUtils.hasText(request.getContentAsString())) {
return;
}
@@ -225,8 +214,7 @@ public class HttpieRequestSnippet extends TemplatedSnippet {
writeContentUsingParameters(request.getParameters(), lines);
}
else if (request.isPutOrPost()) {
writeContentUsingParameters(
request.getParameters().getUniqueParameters(request.getUri()), lines);
writeContentUsingParameters(request.getParameters().getUniqueParameters(request.getUri()), lines);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -24,7 +24,6 @@ package org.springframework.restdocs.cli;
* {@link org.springframework.restdocs.operation.QueryStringParser}
*/
@Deprecated
public class QueryStringParser
extends org.springframework.restdocs.operation.QueryStringParser {
public class QueryStringParser extends org.springframework.restdocs.operation.QueryStringParser {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -34,7 +34,6 @@ public abstract class AbstractConfigurer {
* @param configuration the configuration to be configured
* @param context the current documentation context
*/
public abstract void apply(Map<String, Object> configuration,
RestDocumentationContext context);
public abstract void apply(Map<String, Object> configuration, RestDocumentationContext context);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -23,8 +23,7 @@ package org.springframework.restdocs.config;
* @author Andy Wilkinson
* @since 1.1.0
*/
public abstract class AbstractNestedConfigurer<PARENT> extends AbstractConfigurer
implements NestedConfigurer<PARENT> {
public abstract class AbstractNestedConfigurer<PARENT> extends AbstractConfigurer implements NestedConfigurer<PARENT> {
private final PARENT parent;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -83,10 +83,9 @@ public abstract class RestDocumentationConfigurer<S extends AbstractConfigurer,
* @param configuration the configuration
* @param context the current context
*/
protected final void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
List<AbstractConfigurer> configurers = Arrays.asList(snippets(),
this.templateEngineConfigurer, this.writerResolverConfigurer);
protected final void apply(Map<String, Object> configuration, RestDocumentationContext context) {
List<AbstractConfigurer> configurers = Arrays.asList(snippets(), this.templateEngineConfigurer,
this.writerResolverConfigurer);
for (AbstractConfigurer configurer : configurers) {
configurer.apply(configuration, context);
}
@@ -97,21 +96,17 @@ public abstract class RestDocumentationConfigurer<S extends AbstractConfigurer,
private TemplateEngine templateEngine;
@Override
public void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
public void apply(Map<String, Object> configuration, RestDocumentationContext context) {
TemplateEngine engineToUse = this.templateEngine;
if (engineToUse == null) {
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
Map<String, Object> templateContext = new HashMap<>();
if (snippetConfiguration.getTemplateFormat().getId()
.equals(TemplateFormats.asciidoctor().getId())) {
templateContext.put("tableCellContent",
new AsciidoctorTableCellContentLambda());
if (snippetConfiguration.getTemplateFormat().getId().equals(TemplateFormats.asciidoctor().getId())) {
templateContext.put("tableCellContent", new AsciidoctorTableCellContentLambda());
}
engineToUse = new MustacheTemplateEngine(
new StandardTemplateResourceResolver(
snippetConfiguration.getTemplateFormat()),
new StandardTemplateResourceResolver(snippetConfiguration.getTemplateFormat()),
Mustache.compiler().escapeHTML(false), templateContext);
}
configuration.put(TemplateEngine.class.getName(), engineToUse);
@@ -128,16 +123,13 @@ public abstract class RestDocumentationConfigurer<S extends AbstractConfigurer,
private WriterResolver writerResolver;
@Override
public void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
public void apply(Map<String, Object> configuration, RestDocumentationContext context) {
WriterResolver resolverToUse = this.writerResolver;
if (resolverToUse == null) {
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
resolverToUse = new StandardWriterResolver(
new RestDocumentationContextPlaceholderResolverFactory(),
snippetConfiguration.getEncoding(),
snippetConfiguration.getTemplateFormat());
resolverToUse = new StandardWriterResolver(new RestDocumentationContextPlaceholderResolverFactory(),
snippetConfiguration.getEncoding(), snippetConfiguration.getTemplateFormat());
}
configuration.put(WriterResolver.class.getName(), resolverToUse);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -38,12 +38,10 @@ import org.springframework.restdocs.templates.TemplateFormats;
* @author Andy Wilkinson
* @since 1.1.0
*/
public abstract class SnippetConfigurer<PARENT, TYPE>
extends AbstractNestedConfigurer<PARENT> {
public abstract class SnippetConfigurer<PARENT, TYPE> extends AbstractNestedConfigurer<PARENT> {
private List<Snippet> defaultSnippets = new ArrayList<>(Arrays.asList(
CliDocumentation.curlRequest(), CliDocumentation.httpieRequest(),
HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse(),
private List<Snippet> defaultSnippets = new ArrayList<>(Arrays.asList(CliDocumentation.curlRequest(),
CliDocumentation.httpieRequest(), HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse(),
PayloadDocumentation.requestBody(), PayloadDocumentation.responseBody()));
/**
@@ -58,8 +56,7 @@ public abstract class SnippetConfigurer<PARENT, TYPE>
*
* @see #withTemplateFormat(TemplateFormat)
*/
public static final TemplateFormat DEFAULT_TEMPLATE_FORMAT = TemplateFormats
.asciidoctor();
public static final TemplateFormat DEFAULT_TEMPLATE_FORMAT = TemplateFormats.asciidoctor();
private String snippetEncoding = DEFAULT_SNIPPET_ENCODING;
@@ -74,12 +71,10 @@ public abstract class SnippetConfigurer<PARENT, TYPE>
}
@Override
public void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
public void apply(Map<String, Object> configuration, RestDocumentationContext context) {
configuration.put(SnippetConfiguration.class.getName(),
new SnippetConfiguration(this.snippetEncoding, this.templateFormat));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS,
this.defaultSnippets);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS, this.defaultSnippets);
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -41,8 +41,7 @@ public class ConstraintDescriptions {
* @param clazz the class
*/
public ConstraintDescriptions(Class<?> clazz) {
this(clazz, new ValidatorConstraintResolver(),
new ResourceBundleConstraintDescriptionResolver());
this(clazz, new ValidatorConstraintResolver(), new ResourceBundleConstraintDescriptionResolver());
}
/**
@@ -54,8 +53,7 @@ public class ConstraintDescriptions {
* @param constraintResolver the constraint resolver
*/
public ConstraintDescriptions(Class<?> clazz, ConstraintResolver constraintResolver) {
this(clazz, constraintResolver,
new ResourceBundleConstraintDescriptionResolver());
this(clazz, constraintResolver, new ResourceBundleConstraintDescriptionResolver());
}
/**
@@ -65,8 +63,7 @@ public class ConstraintDescriptions {
* @param clazz the class
* @param descriptionResolver the description resolver
*/
public ConstraintDescriptions(Class<?> clazz,
ConstraintDescriptionResolver descriptionResolver) {
public ConstraintDescriptions(Class<?> clazz, ConstraintDescriptionResolver descriptionResolver) {
this(clazz, new ValidatorConstraintResolver(), descriptionResolver);
}
@@ -91,8 +88,7 @@ public class ConstraintDescriptions {
* @return the list of constraint descriptions
*/
public List<String> descriptionsForProperty(String property) {
List<Constraint> constraints = this.constraintResolver
.resolveForProperty(property, this.clazz);
List<Constraint> constraints = this.constraintResolver.resolveForProperty(property, this.clazz);
List<String> descriptions = new ArrayList<>();
for (Constraint constraint : constraints) {
descriptions.add(this.descriptionResolver.resolveDescription(constraint));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -95,11 +95,9 @@ import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
*
* @author Andy Wilkinson
*/
public class ResourceBundleConstraintDescriptionResolver
implements ConstraintDescriptionResolver {
public class ResourceBundleConstraintDescriptionResolver implements ConstraintDescriptionResolver {
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(
"${", "}");
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
private final ResourceBundle defaultDescriptions;
@@ -128,8 +126,7 @@ public class ResourceBundleConstraintDescriptionResolver
private static ResourceBundle getBundle(String name) {
try {
return ResourceBundle.getBundle(
ResourceBundleConstraintDescriptionResolver.class.getPackage()
.getName() + "." + name,
ResourceBundleConstraintDescriptionResolver.class.getPackage().getName() + "." + name,
Locale.getDefault(), Thread.currentThread().getContextClassLoader());
}
catch (MissingResourceException ex) {
@@ -156,8 +153,7 @@ public class ResourceBundleConstraintDescriptionResolver
return this.defaultDescriptions.getString(key);
}
private static final class ConstraintPlaceholderResolver
implements PlaceholderResolver {
private static final class ConstraintPlaceholderResolver implements PlaceholderResolver {
private final Constraint constraint;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -64,13 +64,10 @@ public class ValidatorConstraintResolver implements ConstraintResolver {
public List<Constraint> resolveForProperty(String property, Class<?> clazz) {
List<Constraint> constraints = new ArrayList<>();
BeanDescriptor beanDescriptor = this.validator.getConstraintsForClass(clazz);
PropertyDescriptor propertyDescriptor = beanDescriptor
.getConstraintsForProperty(property);
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(property);
if (propertyDescriptor != null) {
for (ConstraintDescriptor<?> constraintDescriptor : propertyDescriptor
.getConstraintDescriptors()) {
constraints.add(new Constraint(
constraintDescriptor.getAnnotation().annotationType().getName(),
for (ConstraintDescriptor<?> constraintDescriptor : propertyDescriptor.getConstraintDescriptors()) {
constraints.add(new Constraint(constraintDescriptor.getAnnotation().annotationType().getName(),
constraintDescriptor.getAttributes()));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -30,8 +30,7 @@ import org.springframework.restdocs.snippet.Snippet;
* {@link org.springframework.restdocs.cli.CurlRequestSnippet}.
*/
@Deprecated
public class CurlRequestSnippet
extends org.springframework.restdocs.cli.CurlRequestSnippet {
public class CurlRequestSnippet extends org.springframework.restdocs.cli.CurlRequestSnippet {
/**
* Creates a new {@code CurlRequestSnippet} with no additional attributes.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -80,11 +80,9 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @param responseConverter the response converter
* @param snippets the snippets
*/
public RestDocumentationGenerator(String identifier,
RequestConverter<REQ> requestConverter,
public RestDocumentationGenerator(String identifier, RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter, Snippet... snippets) {
this(identifier, requestConverter, responseConverter,
new IdentityOperationRequestPreprocessor(),
this(identifier, requestConverter, responseConverter, new IdentityOperationRequestPreprocessor(),
new IdentityOperationResponsePreprocessor(), snippets);
}
@@ -102,10 +100,9 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @param requestPreprocessor the request preprocessor
* @param snippets the snippets
*/
public RestDocumentationGenerator(String identifier,
RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter,
OperationRequestPreprocessor requestPreprocessor, Snippet... snippets) {
public RestDocumentationGenerator(String identifier, RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter, OperationRequestPreprocessor requestPreprocessor,
Snippet... snippets) {
this(identifier, requestConverter, responseConverter, requestPreprocessor,
new IdentityOperationResponsePreprocessor(), snippets);
}
@@ -124,13 +121,11 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @param responsePreprocessor the response preprocessor
* @param snippets the snippets
*/
public RestDocumentationGenerator(String identifier,
RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter,
OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) {
this(identifier, requestConverter, responseConverter,
new IdentityOperationRequestPreprocessor(), responsePreprocessor,
snippets);
public RestDocumentationGenerator(String identifier, RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter, OperationResponsePreprocessor responsePreprocessor,
Snippet... snippets) {
this(identifier, requestConverter, responseConverter, new IdentityOperationRequestPreprocessor(),
responsePreprocessor, snippets);
}
/**
@@ -148,10 +143,8 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @param responsePreprocessor the response preprocessor
* @param snippets the snippets
*/
public RestDocumentationGenerator(String identifier,
RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter,
OperationRequestPreprocessor requestPreprocessor,
public RestDocumentationGenerator(String identifier, RequestConverter<REQ> requestConverter,
ResponseConverter<RESP> responseConverter, OperationRequestPreprocessor requestPreprocessor,
OperationResponsePreprocessor responsePreprocessor, Snippet... snippets) {
Assert.notNull(identifier, "identifier must be non-null");
Assert.notNull(requestConverter, "requestConverter must be non-null");
@@ -178,14 +171,12 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @throws RestDocumentationGenerationException if a failure occurs during handling
*/
public void handle(REQ request, RESP response, Map<String, Object> configuration) {
OperationRequest operationRequest = this.requestPreprocessor
.preprocess(this.requestConverter.convert(request));
OperationRequest operationRequest = this.requestPreprocessor.preprocess(this.requestConverter.convert(request));
OperationResponse operationResponse = this.responsePreprocessor
.preprocess(this.responseConverter.convert(response));
Map<String, Object> attributes = new HashMap<>(configuration);
Operation operation = new StandardOperation(this.identifier, operationRequest,
operationResponse, attributes);
Operation operation = new StandardOperation(this.identifier, operationRequest, operationResponse, attributes);
try {
for (Snippet snippet : getSnippets(attributes)) {
snippet.document(operation);
@@ -215,16 +206,14 @@ public final class RestDocumentationGenerator<REQ, RESP> {
* @return the new generator
*/
public RestDocumentationGenerator<REQ, RESP> withSnippets(Snippet... snippets) {
return new RestDocumentationGenerator<>(this.identifier, this.requestConverter,
this.responseConverter, this.requestPreprocessor,
this.responsePreprocessor, snippets);
return new RestDocumentationGenerator<>(this.identifier, this.requestConverter, this.responseConverter,
this.requestPreprocessor, this.responsePreprocessor, snippets);
}
@SuppressWarnings("unchecked")
private List<Snippet> getSnippets(Map<String, Object> configuration) {
List<Snippet> combinedSnippets = new ArrayList<>();
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
List<Snippet> defaultSnippets = (List<Snippet>) configuration.get(ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
if (defaultSnippets != null) {
combinedSnippets.addAll(defaultSnippets);
}
@@ -234,8 +223,7 @@ public final class RestDocumentationGenerator<REQ, RESP> {
return combinedSnippets;
}
private static final class IdentityOperationRequestPreprocessor
implements OperationRequestPreprocessor {
private static final class IdentityOperationRequestPreprocessor implements OperationRequestPreprocessor {
@Override
public OperationRequest preprocess(OperationRequest request) {
@@ -244,8 +232,7 @@ public final class RestDocumentationGenerator<REQ, RESP> {
}
private static final class IdentityOperationResponsePreprocessor
implements OperationResponsePreprocessor {
private static final class IdentityOperationResponsePreprocessor implements OperationResponsePreprocessor {
@Override
public OperationResponse preprocess(OperationResponse response) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -48,14 +48,11 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet {
* @param descriptors the header descriptors
* @param attributes the additional attributes
*/
protected AbstractHeadersSnippet(String type, List<HeaderDescriptor> descriptors,
Map<String, Object> attributes) {
protected AbstractHeadersSnippet(String type, List<HeaderDescriptor> descriptors, Map<String, Object> attributes) {
super(type + "-headers", attributes);
for (HeaderDescriptor descriptor : descriptors) {
Assert.notNull(descriptor.getName(),
"The name of the header must not be null");
Assert.notNull(descriptor.getDescription(),
"The description of the header must not be null");
Assert.notNull(descriptor.getName(), "The name of the header must not be null");
Assert.notNull(descriptor.getDescription(), "The description of the header must not be null");
}
this.headerDescriptors = descriptors;
this.type = type;
@@ -81,8 +78,8 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet {
for (HeaderDescriptor headerDescriptor : missingHeaders) {
names.add(headerDescriptor.getName());
}
throw new SnippetException("Headers with the following names were not found"
+ " in the " + this.type + ": " + names);
throw new SnippetException(
"Headers with the following names were not found" + " in the " + this.type + ": " + names);
}
}
@@ -97,8 +94,7 @@ public abstract class AbstractHeadersSnippet extends TemplatedSnippet {
List<HeaderDescriptor> missingHeaders = new ArrayList<>();
Set<String> actualHeaders = extractActualHeaders(operation);
for (HeaderDescriptor headerDescriptor : this.headerDescriptors) {
if (!headerDescriptor.isOptional()
&& !actualHeaders.contains(headerDescriptor.getName())) {
if (!headerDescriptor.isOptional() && !actualHeaders.contains(headerDescriptor.getName())) {
missingHeaders.add(headerDescriptor);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -69,8 +69,7 @@ public abstract class HeaderDocumentation {
* @return the snippet that will document the request headers
* @see #headerWithName(String)
*/
public static RequestHeadersSnippet requestHeaders(
List<HeaderDescriptor> descriptors) {
public static RequestHeadersSnippet requestHeaders(List<HeaderDescriptor> descriptors) {
return new RequestHeadersSnippet(descriptors);
}
@@ -118,8 +117,7 @@ public abstract class HeaderDocumentation {
* @return the snippet that will document the response headers
* @see #headerWithName(String)
*/
public static ResponseHeadersSnippet responseHeaders(
HeaderDescriptor... descriptors) {
public static ResponseHeadersSnippet responseHeaders(HeaderDescriptor... descriptors) {
return responseHeaders(Arrays.asList(descriptors));
}
@@ -133,8 +131,7 @@ public abstract class HeaderDocumentation {
* @return the snippet that will document the response headers
* @see #headerWithName(String)
*/
public static ResponseHeadersSnippet responseHeaders(
List<HeaderDescriptor> descriptors) {
public static ResponseHeadersSnippet responseHeaders(List<HeaderDescriptor> descriptors) {
return new ResponseHeadersSnippet(descriptors);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -51,8 +51,7 @@ public class RequestHeadersSnippet extends AbstractHeadersSnippet {
* @param descriptors the descriptors
* @param attributes the additional attributes
*/
protected RequestHeadersSnippet(List<HeaderDescriptor> descriptors,
Map<String, Object> attributes) {
protected RequestHeadersSnippet(List<HeaderDescriptor> descriptors, Map<String, Object> attributes) {
super("request", descriptors, attributes);
}
@@ -80,8 +79,7 @@ public class RequestHeadersSnippet extends AbstractHeadersSnippet {
* @return the new snippet
*/
public final RequestHeadersSnippet and(List<HeaderDescriptor> additionalDescriptors) {
List<HeaderDescriptor> combinedDescriptors = new ArrayList<>(
this.getHeaderDescriptors());
List<HeaderDescriptor> combinedDescriptors = new ArrayList<>(this.getHeaderDescriptors());
combinedDescriptors.addAll(additionalDescriptors);
return new RequestHeadersSnippet(combinedDescriptors, getAttributes());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -51,8 +51,7 @@ public class ResponseHeadersSnippet extends AbstractHeadersSnippet {
* @param descriptors the descriptors
* @param attributes the additional attributes
*/
protected ResponseHeadersSnippet(List<HeaderDescriptor> descriptors,
Map<String, Object> attributes) {
protected ResponseHeadersSnippet(List<HeaderDescriptor> descriptors, Map<String, Object> attributes) {
super("response", descriptors, attributes);
}
@@ -79,10 +78,8 @@ public class ResponseHeadersSnippet extends AbstractHeadersSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final ResponseHeadersSnippet and(
List<HeaderDescriptor> additionalDescriptors) {
List<HeaderDescriptor> combinedDescriptors = new ArrayList<>(
this.getHeaderDescriptors());
public final ResponseHeadersSnippet and(List<HeaderDescriptor> additionalDescriptors) {
List<HeaderDescriptor> combinedDescriptors = new ArrayList<>(this.getHeaderDescriptors());
combinedDescriptors.addAll(additionalDescriptors);
return new ResponseHeadersSnippet(combinedDescriptors, getAttributes());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -76,8 +76,7 @@ public class HttpRequestSnippet extends TemplatedSnippet {
private String getPath(OperationRequest request) {
String path = request.getUri().getRawPath();
String queryString = request.getUri().getRawQuery();
Parameters uniqueParameters = request.getParameters()
.getUniqueParameters(request.getUri());
Parameters uniqueParameters = request.getParameters().getUniqueParameters(request.getUri());
if (!uniqueParameters.isEmpty() && includeParametersInUri(request)) {
if (StringUtils.hasText(queryString)) {
queryString = queryString + "&" + uniqueParameters.toQueryString();
@@ -94,8 +93,7 @@ public class HttpRequestSnippet extends TemplatedSnippet {
private boolean includeParametersInUri(OperationRequest request) {
return request.getMethod() == HttpMethod.GET || (request.getContent().length > 0
&& !MediaType.APPLICATION_FORM_URLENCODED
.isCompatibleWith(request.getHeaders().getContentType()));
&& !MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(request.getHeaders().getContentType()));
}
private List<Map<String, String>> getHeaders(OperationRequest request) {
@@ -103,10 +101,8 @@ public class HttpRequestSnippet extends TemplatedSnippet {
for (Entry<String, List<String>> header : request.getHeaders().entrySet()) {
for (String value : header.getValue()) {
if (HttpHeaders.CONTENT_TYPE.equals(header.getKey())
&& !request.getParts().isEmpty()) {
headers.add(header(header.getKey(),
String.format("%s; boundary=%s", value, MULTIPART_BOUNDARY)));
if (HttpHeaders.CONTENT_TYPE.equals(header.getKey()) && !request.getParts().isEmpty()) {
headers.add(header(header.getKey(), String.format("%s; boundary=%s", value, MULTIPART_BOUNDARY)));
}
else {
headers.add(header(header.getKey(), value));
@@ -116,13 +112,11 @@ public class HttpRequestSnippet extends TemplatedSnippet {
}
for (RequestCookie cookie : request.getCookies()) {
headers.add(header(HttpHeaders.COOKIE,
String.format("%s=%s", cookie.getName(), cookie.getValue())));
headers.add(header(HttpHeaders.COOKIE, String.format("%s=%s", cookie.getName(), cookie.getValue())));
}
if (requiresFormEncodingContentTypeHeader(request)) {
headers.add(header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE));
headers.add(header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE));
}
return headers;
}
@@ -150,8 +144,7 @@ public class HttpRequestSnippet extends TemplatedSnippet {
}
private boolean isPutOrPost(OperationRequest request) {
return HttpMethod.PUT.equals(request.getMethod())
|| HttpMethod.POST.equals(request.getMethod());
return HttpMethod.PUT.equals(request.getMethod()) || HttpMethod.POST.equals(request.getMethod());
}
private void writeParts(OperationRequest request, PrintWriter writer) {
@@ -186,8 +179,7 @@ public class HttpRequestSnippet extends TemplatedSnippet {
part.getHeaders().getContentType(), writer);
}
private void writePart(String name, String value, String filename,
MediaType contentType, PrintWriter writer) {
private void writePart(String name, String value, String filename, MediaType contentType, PrintWriter writer) {
writer.printf("Content-Disposition: form-data; name=%s", name);
if (StringUtils.hasText(filename)) {
writer.printf("; filename=%s", filename);
@@ -205,9 +197,8 @@ public class HttpRequestSnippet extends TemplatedSnippet {
}
private boolean requiresFormEncodingContentTypeHeader(OperationRequest request) {
return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null
&& isPutOrPost(request) && (!request.getParameters().isEmpty()
&& !includeParametersInUri(request));
return request.getHeaders().get(HttpHeaders.CONTENT_TYPE) == null && isPutOrPost(request)
&& (!request.getParameters().isEmpty() && !includeParametersInUri(request));
}
private Map<String, String> header(String name, String value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -35,10 +35,8 @@ abstract class AbstractJsonLinkExtractor implements LinkExtractor {
@Override
@SuppressWarnings("unchecked")
public Map<String, List<Link>> extractLinks(OperationResponse response)
throws IOException {
Map<String, Object> jsonContent = this.objectMapper
.readValue(response.getContent(), Map.class);
public Map<String, List<Link>> extractLinks(OperationResponse response) throws IOException {
Map<String, Object> jsonContent = this.objectMapper.readValue(response.getContent(), Map.class);
return extractLinks(jsonContent);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -58,8 +58,7 @@ class AtomLinkExtractor extends AbstractJsonLinkExtractor {
return null;
}
private static void maybeStoreLink(Link link,
MultiValueMap<String, Link> extractedLinks) {
private static void maybeStoreLink(Link link, MultiValueMap<String, Link> extractedLinks) {
if (link != null) {
extractedLinks.add(link.getRel(), link);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -45,16 +45,14 @@ class ContentTypeLinkExtractor implements LinkExtractor {
}
@Override
public Map<String, List<Link>> extractLinks(OperationResponse response)
throws IOException {
public Map<String, List<Link>> extractLinks(OperationResponse response) throws IOException {
MediaType contentType = response.getHeaders().getContentType();
LinkExtractor extractorForContentType = getExtractorForContentType(contentType);
if (extractorForContentType != null) {
return extractorForContentType.extractLinks(response);
}
throw new IllegalStateException(
"No LinkExtractor has been provided and one is not available for the "
+ "content type " + contentType);
"No LinkExtractor has been provided and one is not available for the " + "content type " + contentType);
}
private LinkExtractor getExtractorForContentType(MediaType contentType) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -147,8 +147,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(Map<String, Object> attributes,
LinkDescriptor... descriptors) {
public static LinksSnippet links(Map<String, Object> attributes, LinkDescriptor... descriptors) {
return links(attributes, Arrays.asList(descriptors));
}
@@ -174,8 +173,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(Map<String, Object> attributes,
List<LinkDescriptor> descriptors) {
public static LinksSnippet links(Map<String, Object> attributes, List<LinkDescriptor> descriptors) {
return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes);
}
@@ -195,8 +193,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(Map<String, Object> attributes,
LinkDescriptor... descriptors) {
public static LinksSnippet relaxedLinks(Map<String, Object> attributes, LinkDescriptor... descriptors) {
return relaxedLinks(attributes, Arrays.asList(descriptors));
}
@@ -216,10 +213,8 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(Map<String, Object> attributes,
List<LinkDescriptor> descriptors) {
return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes,
true);
public static LinksSnippet relaxedLinks(Map<String, Object> attributes, List<LinkDescriptor> descriptors) {
return new LinksSnippet(new ContentTypeLinkExtractor(), descriptors, attributes, true);
}
/**
@@ -243,8 +238,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(LinkExtractor linkExtractor,
LinkDescriptor... descriptors) {
public static LinksSnippet links(LinkExtractor linkExtractor, LinkDescriptor... descriptors) {
return links(linkExtractor, Arrays.asList(descriptors));
}
@@ -269,8 +263,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(LinkExtractor linkExtractor,
List<LinkDescriptor> descriptors) {
public static LinksSnippet links(LinkExtractor linkExtractor, List<LinkDescriptor> descriptors) {
return new LinksSnippet(linkExtractor, descriptors);
}
@@ -289,8 +282,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor,
LinkDescriptor... descriptors) {
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, LinkDescriptor... descriptors) {
return relaxedLinks(linkExtractor, Arrays.asList(descriptors));
}
@@ -309,8 +301,7 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor,
List<LinkDescriptor> descriptors) {
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, List<LinkDescriptor> descriptors) {
return new LinksSnippet(linkExtractor, descriptors, true);
}
@@ -337,8 +328,8 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(LinkExtractor linkExtractor,
Map<String, Object> attributes, LinkDescriptor... descriptors) {
public static LinksSnippet links(LinkExtractor linkExtractor, Map<String, Object> attributes,
LinkDescriptor... descriptors) {
return links(linkExtractor, attributes, Arrays.asList(descriptors));
}
@@ -365,8 +356,8 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet links(LinkExtractor linkExtractor,
Map<String, Object> attributes, List<LinkDescriptor> descriptors) {
public static LinksSnippet links(LinkExtractor linkExtractor, Map<String, Object> attributes,
List<LinkDescriptor> descriptors) {
return new LinksSnippet(linkExtractor, descriptors, attributes);
}
@@ -387,8 +378,8 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor,
Map<String, Object> attributes, LinkDescriptor... descriptors) {
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, Map<String, Object> attributes,
LinkDescriptor... descriptors) {
return relaxedLinks(linkExtractor, attributes, Arrays.asList(descriptors));
}
@@ -409,8 +400,8 @@ public abstract class HypermediaDocumentation {
* @param descriptors the descriptions of the response's links
* @return the snippet that will document the links
*/
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor,
Map<String, Object> attributes, List<LinkDescriptor> descriptors) {
public static LinksSnippet relaxedLinks(LinkExtractor linkExtractor, Map<String, Object> attributes,
List<LinkDescriptor> descriptors) {
return new LinksSnippet(linkExtractor, descriptors, attributes, true);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -118,8 +118,8 @@ public class Link {
@Override
public String toString() {
return new ToStringCreator(this).append("rel", this.rel).append("href", this.href)
.append("title", this.title).toString();
return new ToStringCreator(this).append("rel", this.rel).append("href", this.href).append("title", this.title)
.toString();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -60,8 +60,7 @@ public class LinksSnippet extends TemplatedSnippet {
* @param linkExtractor the link extractor
* @param descriptors the link descriptors
*/
protected LinksSnippet(LinkExtractor linkExtractor,
List<LinkDescriptor> descriptors) {
protected LinksSnippet(LinkExtractor linkExtractor, List<LinkDescriptor> descriptors) {
this(linkExtractor, descriptors, null, false);
}
@@ -144,8 +143,7 @@ public class LinksSnippet extends TemplatedSnippet {
}
Set<String> requiredRels = new HashSet<>();
for (Entry<String, LinkDescriptor> relAndDescriptor : this.descriptorsByRel
.entrySet()) {
for (Entry<String, LinkDescriptor> relAndDescriptor : this.descriptorsByRel.entrySet()) {
if (!relAndDescriptor.getValue().isOptional()) {
requiredRels.add(relAndDescriptor.getKey());
}
@@ -157,15 +155,13 @@ public class LinksSnippet extends TemplatedSnippet {
if (!undocumentedRels.isEmpty() || !missingRels.isEmpty()) {
String message = "";
if (!undocumentedRels.isEmpty()) {
message += "Links with the following relations were not documented: "
+ undocumentedRels;
message += "Links with the following relations were not documented: " + undocumentedRels;
}
if (!missingRels.isEmpty()) {
if (message.length() > 0) {
message += ". ";
}
message += "Links with the following relations were not found in the "
+ "response: " + missingRels;
message += "Links with the following relations were not found in the " + "response: " + missingRels;
}
throw new SnippetException(message);
}
@@ -177,9 +173,7 @@ public class LinksSnippet extends TemplatedSnippet {
LinkDescriptor descriptor = entry.getValue();
if (!descriptor.isIgnored()) {
if (descriptor.getDescription() == null) {
descriptor = createDescriptor(
getDescriptionFromLinkTitle(links, descriptor.getRel()),
descriptor);
descriptor = createDescriptor(getDescriptionFromLinkTitle(links, descriptor.getRel()), descriptor);
}
model.add(createModelForDescriptor(descriptor));
}
@@ -187,8 +181,7 @@ public class LinksSnippet extends TemplatedSnippet {
return model;
}
private String getDescriptionFromLinkTitle(Map<String, List<Link>> links,
String rel) {
private String getDescriptionFromLinkTitle(Map<String, List<Link>> links, String rel) {
List<Link> linksForRel = links.get(rel);
if (linksForRel != null) {
for (Link link : linksForRel) {
@@ -197,13 +190,12 @@ public class LinksSnippet extends TemplatedSnippet {
}
}
}
throw new SnippetException("No description was provided for the link with rel '"
+ rel + "' and no title was available from the link in the payload");
throw new SnippetException("No description was provided for the link with rel '" + rel
+ "' and no title was available from the link in the payload");
}
private LinkDescriptor createDescriptor(String description, LinkDescriptor source) {
LinkDescriptor newDescriptor = new LinkDescriptor(source.getRel())
.description(description);
LinkDescriptor newDescriptor = new LinkDescriptor(source.getRel()).description(description);
if (source.isOptional()) {
newDescriptor.optional();
}
@@ -255,8 +247,7 @@ public class LinksSnippet extends TemplatedSnippet {
* @return the new snippet
*/
public final LinksSnippet and(List<LinkDescriptor> additionalDescriptors) {
List<LinkDescriptor> combinedDescriptors = new ArrayList<>(
this.descriptorsByRel.values());
List<LinkDescriptor> combinedDescriptors = new ArrayList<>(this.descriptorsByRel.values());
combinedDescriptors.addAll(additionalDescriptors);
return new LinksSnippet(this.linkExtractor, combinedDescriptors, getAttributes());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -27,7 +27,7 @@ import org.springframework.http.MediaType;
*
* @author Andy Wilkinson
*/
abstract class AbstractOperationMessage {
abstract class AbstractOperationMessage implements OperationMessage {
private final byte[] content;
@@ -38,19 +38,21 @@ abstract class AbstractOperationMessage {
this.headers = headers;
}
@Override
public byte[] getContent() {
return Arrays.copyOf(this.content, this.content.length);
}
@Override
public HttpHeaders getHeaders() {
return HttpHeaders.readOnlyHttpHeaders(this.headers);
}
@Override
public String getContentAsString() {
if (this.content.length > 0) {
Charset charset = extractCharsetFromContentTypeHeader();
return (charset != null) ? new String(this.content, charset)
: new String(this.content);
return (charset != null) ? new String(this.content, charset) : new String(this.content);
}
return "";
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2014-2019 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
*
* https://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 org.springframework.restdocs.operation;
import org.springframework.http.HttpHeaders;
/**
* Base contract for operation requests, request parts, and responses.
*
* @author Andy Wilkinson
*/
interface OperationMessage {
byte[] getContent();
String getContentAsString();
HttpHeaders getHeaders();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -43,11 +43,10 @@ public class OperationRequestFactory {
* @param cookies the request's cookies
* @return the {@code OperationRequest}
*/
public OperationRequest create(URI uri, HttpMethod method, byte[] content,
HttpHeaders headers, Parameters parameters,
Collection<OperationRequestPart> parts, Collection<RequestCookie> cookies) {
return new StandardOperationRequest(uri, method, content,
augmentHeaders(headers, uri, content), parameters, parts, cookies);
public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers,
Parameters parameters, Collection<OperationRequestPart> parts, Collection<RequestCookie> cookies) {
return new StandardOperationRequest(uri, method, content, augmentHeaders(headers, uri, content), parameters,
parts, cookies);
}
/**
@@ -62,11 +61,9 @@ public class OperationRequestFactory {
* @param parts the request's parts
* @return the {@code OperationRequest}
*/
public OperationRequest create(URI uri, HttpMethod method, byte[] content,
HttpHeaders headers, Parameters parameters,
Collection<OperationRequestPart> parts) {
return create(uri, method, content, headers, parameters, parts,
Collections.<RequestCookie>emptyList());
public OperationRequest create(URI uri, HttpMethod method, byte[] content, HttpHeaders headers,
Parameters parameters, Collection<OperationRequestPart> parts) {
return create(uri, method, content, headers, parameters, parts, Collections.<RequestCookie>emptyList());
}
/**
@@ -78,9 +75,9 @@ public class OperationRequestFactory {
* @return the new request with the new content
*/
public OperationRequest createFrom(OperationRequest original, byte[] newContent) {
return new StandardOperationRequest(original.getUri(), original.getMethod(),
newContent, getUpdatedHeaders(original.getHeaders(), newContent),
original.getParameters(), original.getParts(), original.getCookies());
return new StandardOperationRequest(original.getUri(), original.getMethod(), newContent,
getUpdatedHeaders(original.getHeaders(), newContent), original.getParameters(), original.getParts(),
original.getCookies());
}
/**
@@ -90,11 +87,9 @@ public class OperationRequestFactory {
* @param newHeaders the new headers
* @return the new request with the new headers
*/
public OperationRequest createFrom(OperationRequest original,
HttpHeaders newHeaders) {
return new StandardOperationRequest(original.getUri(), original.getMethod(),
original.getContent(), newHeaders, original.getParameters(),
original.getParts(), original.getCookies());
public OperationRequest createFrom(OperationRequest original, HttpHeaders newHeaders) {
return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(), newHeaders,
original.getParameters(), original.getParts(), original.getCookies());
}
/**
@@ -104,17 +99,13 @@ public class OperationRequestFactory {
* @param newParameters the new parameters
* @return the new request with the new parameters
*/
public OperationRequest createFrom(OperationRequest original,
Parameters newParameters) {
return new StandardOperationRequest(original.getUri(), original.getMethod(),
original.getContent(), original.getHeaders(), newParameters,
original.getParts(), original.getCookies());
public OperationRequest createFrom(OperationRequest original, Parameters newParameters) {
return new StandardOperationRequest(original.getUri(), original.getMethod(), original.getContent(),
original.getHeaders(), newParameters, original.getParts(), original.getCookies());
}
private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri,
byte[] content) {
return new HttpHeadersHelper(originalHeaders)
.addIfAbsent(HttpHeaders.HOST, createHostHeader(uri))
private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, URI uri, byte[] content) {
return new HttpHeadersHelper(originalHeaders).addIfAbsent(HttpHeaders.HOST, createHostHeader(uri))
.setContentLengthHeader(content).getHeaders();
}
@@ -125,10 +116,8 @@ public class OperationRequestFactory {
return uri.getHost() + ":" + uri.getPort();
}
private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders,
byte[] updatedContent) {
return new HttpHeadersHelper(originalHeaders)
.updateContentLengthHeaderIfPresent(updatedContent).getHeaders();
private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) {
return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent(updatedContent).getHeaders();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -35,10 +35,8 @@ public class OperationRequestPartFactory {
* @param headers the headers of the part
* @return the {@code OperationRequestPart}
*/
public OperationRequestPart create(String name, String submittedFileName,
byte[] content, HttpHeaders headers) {
return new StandardOperationRequestPart(name, submittedFileName, content,
augmentHeaders(headers, content));
public OperationRequestPart create(String name, String submittedFileName, byte[] content, HttpHeaders headers) {
return new StandardOperationRequestPart(name, submittedFileName, content, augmentHeaders(headers, content));
}
private HttpHeaders augmentHeaders(HttpHeaders input, byte[] content) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -35,10 +35,8 @@ public class OperationResponseFactory {
* @param content the content of the request
* @return the {@code OperationResponse}
*/
public OperationResponse create(HttpStatus status, HttpHeaders headers,
byte[] content) {
return new StandardOperationResponse(status, augmentHeaders(headers, content),
content);
public OperationResponse create(HttpStatus status, HttpHeaders headers, byte[] content) {
return new StandardOperationResponse(status, augmentHeaders(headers, content), content);
}
/**
@@ -51,8 +49,8 @@ public class OperationResponseFactory {
* @return the new response with the new content
*/
public OperationResponse createFrom(OperationResponse original, byte[] newContent) {
return new StandardOperationResponse(original.getStatus(),
getUpdatedHeaders(original.getHeaders(), newContent), newContent);
return new StandardOperationResponse(original.getStatus(), getUpdatedHeaders(original.getHeaders(), newContent),
newContent);
}
/**
@@ -62,21 +60,16 @@ public class OperationResponseFactory {
* @param newHeaders the new headers
* @return the new response with the new headers
*/
public OperationResponse createFrom(OperationResponse original,
HttpHeaders newHeaders) {
return new StandardOperationResponse(original.getStatus(), newHeaders,
original.getContent());
public OperationResponse createFrom(OperationResponse original, HttpHeaders newHeaders) {
return new StandardOperationResponse(original.getStatus(), newHeaders, original.getContent());
}
private HttpHeaders augmentHeaders(HttpHeaders originalHeaders, byte[] content) {
return new HttpHeadersHelper(originalHeaders).setContentLengthHeader(content)
.getHeaders();
return new HttpHeadersHelper(originalHeaders).setContentLengthHeader(content).getHeaders();
}
private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders,
byte[] updatedContent) {
return new HttpHeadersHelper(originalHeaders)
.updateContentLengthHeaderIfPresent(updatedContent).getHeaders();
private HttpHeaders getUpdatedHeaders(HttpHeaders originalHeaders, byte[] updatedContent) {
return new HttpHeadersHelper(originalHeaders).updateContentLengthHeaderIfPresent(updatedContent).getHeaders();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -69,8 +69,8 @@ public class Parameters extends LinkedMultiValueMap<String, String> {
return uniqueParameters;
}
private void addIfUnique(Map.Entry<String, List<String>> parameter,
Parameters queryStringParameters, Parameters uniqueParameters) {
private void addIfUnique(Map.Entry<String, List<String>> parameter, Parameters queryStringParameters,
Parameters uniqueParameters) {
if (!queryStringParameters.containsKey(parameter.getKey())) {
uniqueParameters.put(parameter.getKey(), parameter.getValue());
}
@@ -108,8 +108,7 @@ public class Parameters extends LinkedMultiValueMap<String, String> {
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
throw new IllegalStateException("Unable to URL encode " + s + " using UTF-8",
ex);
throw new IllegalStateException("Unable to URL encode " + s + " using UTF-8", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -71,8 +71,7 @@ public class QueryStringParser {
}
}
else {
throw new IllegalArgumentException(
"The parameter '" + parameter + "' is malformed");
throw new IllegalArgumentException("The parameter '" + parameter + "' is malformed");
}
}
@@ -81,8 +80,7 @@ public class QueryStringParser {
return URLDecoder.decode(encoded, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
throw new IllegalStateException(
"Unable to URL encode " + encoded + " using UTF-8", ex);
throw new IllegalStateException("Unable to URL encode " + encoded + " using UTF-8", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -40,8 +40,8 @@ public class StandardOperation implements Operation {
* @param response the response that was received
* @param attributes attributes to associate with the operation
*/
public StandardOperation(String name, OperationRequest request,
OperationResponse response, Map<String, Object> attributes) {
public StandardOperation(String name, OperationRequest request, OperationResponse response,
Map<String, Object> attributes) {
this.name = name;
this.request = request;
this.response = response;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -28,8 +28,7 @@ import org.springframework.http.HttpMethod;
*
* @author Andy Wilkinson
*/
class StandardOperationRequest extends AbstractOperationMessage
implements OperationRequest {
class StandardOperationRequest extends AbstractOperationMessage implements OperationRequest {
private HttpMethod method;
@@ -53,8 +52,7 @@ class StandardOperationRequest extends AbstractOperationMessage
* @param parts the parts
* @param cookies the cookies
*/
StandardOperationRequest(URI uri, HttpMethod method, byte[] content,
HttpHeaders headers, Parameters parameters,
StandardOperationRequest(URI uri, HttpMethod method, byte[] content, HttpHeaders headers, Parameters parameters,
Collection<OperationRequestPart> parts, Collection<RequestCookie> cookies) {
super(content, headers);
this.uri = uri;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -23,8 +23,7 @@ import org.springframework.http.HttpHeaders;
*
* @author Andy Wilkinson
*/
class StandardOperationRequestPart extends AbstractOperationMessage
implements OperationRequestPart {
class StandardOperationRequestPart extends AbstractOperationMessage implements OperationRequestPart {
private final String name;
@@ -37,8 +36,7 @@ class StandardOperationRequestPart extends AbstractOperationMessage
* @param content the contents of the part
* @param headers the headers of the part
*/
StandardOperationRequestPart(String name, String submittedFileName, byte[] content,
HttpHeaders headers) {
StandardOperationRequestPart(String name, String submittedFileName, byte[] content, HttpHeaders headers) {
super(content, headers);
this.name = name;
this.submittedFileName = submittedFileName;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -24,8 +24,7 @@ import org.springframework.http.HttpStatus;
*
* @author Andy Wilkinson
*/
class StandardOperationResponse extends AbstractOperationMessage
implements OperationResponse {
class StandardOperationResponse extends AbstractOperationMessage implements OperationResponse {
private final HttpStatus status;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 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.
@@ -45,14 +45,12 @@ class HeaderRemovingOperationPreprocessor implements OperationPreprocessor {
@Override
public OperationResponse preprocess(OperationResponse response) {
return this.responseFactory.createFrom(response,
removeHeaders(response.getHeaders()));
return this.responseFactory.createFrom(response, removeHeaders(response.getHeaders()));
}
@Override
public OperationRequest preprocess(OperationRequest request) {
return this.requestFactory.createFrom(request,
removeHeaders(request.getHeaders()));
return this.requestFactory.createFrom(request, removeHeaders(request.getHeaders()));
}
private HttpHeaders removeHeaders(HttpHeaders originalHeaders) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -29,8 +29,7 @@ class LinkMaskingContentModifier implements ContentModifier {
private static final String DEFAULT_MASK = "...";
private static final Pattern LINK_HREF = Pattern.compile("\"href\"\\s*:\\s*\"(.*?)\"",
Pattern.DOTALL);
private static final Pattern LINK_HREF = Pattern.compile("\"href\"\\s*:\\s*\"(.*?)\"", Pattern.DOTALL);
private final ContentModifier contentModifier;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -32,8 +32,7 @@ import org.springframework.util.Assert;
* @author Andy Wilkinson
* @since 1.1.0
*/
public final class ParametersModifyingOperationPreprocessor
extends OperationPreprocessorAdapter {
public final class ParametersModifyingOperationPreprocessor extends OperationPreprocessorAdapter {
private final OperationRequestFactory requestFactory = new OperationRequestFactory();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -44,8 +44,7 @@ public final class Preprocessors {
* @param preprocessors the preprocessors
* @return the request preprocessor
*/
public static OperationRequestPreprocessor preprocessRequest(
OperationPreprocessor... preprocessors) {
public static OperationRequestPreprocessor preprocessRequest(OperationPreprocessor... preprocessors) {
return new DelegatingOperationRequestPreprocessor(Arrays.asList(preprocessors));
}
@@ -55,8 +54,7 @@ public final class Preprocessors {
* @param preprocessors the preprocessors
* @return the response preprocessor
*/
public static OperationResponsePreprocessor preprocessResponse(
OperationPreprocessor... preprocessors) {
public static OperationResponsePreprocessor preprocessResponse(OperationPreprocessor... preprocessors) {
return new DelegatingOperationResponsePreprocessor(Arrays.asList(preprocessors));
}
@@ -66,8 +64,7 @@ public final class Preprocessors {
* @return the preprocessor
*/
public static OperationPreprocessor prettyPrint() {
return new ContentModifyingOperationPreprocessor(
new PrettyPrintingContentModifier());
return new ContentModifyingOperationPreprocessor(new PrettyPrintingContentModifier());
}
/**
@@ -79,8 +76,7 @@ public final class Preprocessors {
* @see String#equals(Object)
*/
public static OperationPreprocessor removeHeaders(String... headerNames) {
return new HeaderRemovingOperationPreprocessor(
new ExactMatchHeaderFilter(headerNames));
return new HeaderRemovingOperationPreprocessor(new ExactMatchHeaderFilter(headerNames));
}
/**
@@ -91,10 +87,8 @@ public final class Preprocessors {
* @return the preprocessor
* @see java.util.regex.Matcher#matches()
*/
public static OperationPreprocessor removeMatchingHeaders(
String... headerNamePatterns) {
return new HeaderRemovingOperationPreprocessor(
new PatternMatchHeaderFilter(headerNamePatterns));
public static OperationPreprocessor removeMatchingHeaders(String... headerNamePatterns) {
return new HeaderRemovingOperationPreprocessor(new PatternMatchHeaderFilter(headerNamePatterns));
}
/**
@@ -103,8 +97,7 @@ public final class Preprocessors {
* @return the preprocessor
*/
public static OperationPreprocessor maskLinks() {
return new ContentModifyingOperationPreprocessor(
new LinkMaskingContentModifier());
return new ContentModifyingOperationPreprocessor(new LinkMaskingContentModifier());
}
/**
@@ -114,8 +107,7 @@ public final class Preprocessors {
* @return the preprocessor
*/
public static OperationPreprocessor maskLinks(String mask) {
return new ContentModifyingOperationPreprocessor(
new LinkMaskingContentModifier(mask));
return new ContentModifyingOperationPreprocessor(new LinkMaskingContentModifier(mask));
}
/**
@@ -126,10 +118,8 @@ public final class Preprocessors {
* @param replacement the replacement
* @return the preprocessor
*/
public static OperationPreprocessor replacePattern(Pattern pattern,
String replacement) {
return new ContentModifyingOperationPreprocessor(
new PatternReplacingContentModifier(pattern, replacement));
public static OperationPreprocessor replacePattern(Pattern pattern, String replacement) {
return new ContentModifyingOperationPreprocessor(new PatternReplacingContentModifier(pattern, replacement));
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 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.
@@ -52,8 +52,7 @@ import org.springframework.http.MediaType;
public class PrettyPrintingContentModifier implements ContentModifier {
private static final List<PrettyPrinter> PRETTY_PRINTERS = Collections
.unmodifiableList(
Arrays.asList(new JsonPrettyPrinter(), new XmlPrettyPrinter()));
.unmodifiableList(Arrays.asList(new JsonPrettyPrinter(), new XmlPrettyPrinter()));
@Override
public byte[] modifyContent(byte[] originalContent, MediaType contentType) {
@@ -82,44 +81,37 @@ public class PrettyPrintingContentModifier implements ContentModifier {
public byte[] prettyPrint(byte[] original) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
"4");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
ByteArrayOutputStream transformed = new ByteArrayOutputStream();
transformer.setErrorListener(new SilentErrorListener());
transformer.transform(createSaxSource(original),
new StreamResult(transformed));
transformer.transform(createSaxSource(original), new StreamResult(transformed));
return transformed.toByteArray();
}
private SAXSource createSaxSource(byte[] original)
throws ParserConfigurationException, SAXException {
private SAXSource createSaxSource(byte[] original) throws ParserConfigurationException, SAXException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setErrorHandler(new SilentErrorHandler());
return new SAXSource(xmlReader,
new InputSource(new ByteArrayInputStream(original)));
return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(original)));
}
private static final class SilentErrorListener implements ErrorListener {
@Override
public void warning(TransformerException exception)
throws TransformerException {
public void warning(TransformerException exception) throws TransformerException {
// Suppress
}
@Override
public void error(TransformerException exception)
throws TransformerException {
public void error(TransformerException exception) throws TransformerException {
// Suppress
}
@Override
public void fatalError(TransformerException exception)
throws TransformerException {
public void fatalError(TransformerException exception) throws TransformerException {
// Suppress
}
@@ -148,13 +140,12 @@ public class PrettyPrintingContentModifier implements ContentModifier {
private static final class JsonPrettyPrinter implements PrettyPrinter {
private final ObjectMapper objectMapper = new ObjectMapper()
.configure(SerializationFeature.INDENT_OUTPUT, true);
private final ObjectMapper objectMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT,
true);
@Override
public byte[] prettyPrint(byte[] original) throws IOException {
return this.objectMapper
.writeValueAsBytes(this.objectMapper.readTree(original));
return this.objectMapper.writeValueAsBytes(this.objectMapper.readTree(original));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -46,8 +46,7 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet {
* @param subsectionExtractor the subsection extractor
* @param attributes the attributes
*/
protected AbstractBodySnippet(String type,
PayloadSubsectionExtractor<?> subsectionExtractor,
protected AbstractBodySnippet(String type, PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
this(type, type, subsectionExtractor, attributes);
}
@@ -63,12 +62,9 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet {
* @param subsectionExtractor the subsection extractor
* @param attributes the attributes
*/
protected AbstractBodySnippet(String name, String type,
PayloadSubsectionExtractor<?> subsectionExtractor,
protected AbstractBodySnippet(String name, String type, PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
super(name + "-body"
+ ((subsectionExtractor != null)
? "-" + subsectionExtractor.getSubsectionId() : ""),
super(name + "-body" + ((subsectionExtractor != null) ? "-" + subsectionExtractor.getSubsectionId() : ""),
type + "-body", attributes);
this.subsectionExtractor = subsectionExtractor;
}
@@ -79,12 +75,10 @@ public abstract class AbstractBodySnippet extends TemplatedSnippet {
MediaType contentType = getContentType(operation);
byte[] content = getContent(operation);
if (this.subsectionExtractor != null) {
content = this.subsectionExtractor.extractSubsection(content,
contentType);
content = this.subsectionExtractor.extractSubsection(content, contentType);
}
Charset charset = extractCharset(contentType);
String body = (charset != null) ? new String(content, charset)
: new String(content);
String body = (charset != null) ? new String(content, charset) : new String(content);
Map<String, Object> model = new HashMap<>();
model.put("body", body);
return model;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -61,8 +61,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
* {@link #AbstractFieldsSnippet(String, List, Map, boolean)}
*/
@Deprecated
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes) {
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors, Map<String, Object> attributes) {
this(type, descriptors, attributes, false);
}
@@ -78,8 +77,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
this(type, type, descriptors, attributes, ignoreUndocumentedFields);
}
@@ -98,11 +97,9 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
* @param subsectionExtractor the subsection extractor
* @since 1.2.0
*/
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields,
PayloadSubsectionExtractor<?> subsectionExtractor) {
this(type, type, descriptors, attributes, ignoreUndocumentedFields,
subsectionExtractor);
protected AbstractFieldsSnippet(String type, List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields, PayloadSubsectionExtractor<?> subsectionExtractor) {
this(type, type, descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor);
}
/**
@@ -118,9 +115,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected AbstractFieldsSnippet(String name, String type,
List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
protected AbstractFieldsSnippet(String name, String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
this(name, type, descriptors, attributes, ignoreUndocumentedFields, null);
}
@@ -141,20 +137,16 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
* empty string can be used to indicate that the entire payload should be documented.
* @since 1.2.0
*/
protected AbstractFieldsSnippet(String name, String type,
List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields,
protected AbstractFieldsSnippet(String name, String type, List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields,
PayloadSubsectionExtractor<?> subsectionExtractor) {
super(name + "-fields"
+ ((subsectionExtractor != null)
? "-" + subsectionExtractor.getSubsectionId() : ""),
super(name + "-fields" + ((subsectionExtractor != null) ? "-" + subsectionExtractor.getSubsectionId() : ""),
type + "-fields", attributes);
for (FieldDescriptor descriptor : descriptors) {
Assert.notNull(descriptor.getPath(), "Field descriptors must have a path");
if (!descriptor.isIgnored()) {
Assert.notNull(descriptor.getDescription() != null,
"The descriptor for '" + descriptor.getPath() + "' must have a"
+ " description or it must be marked as ignored");
Assert.notNull(descriptor.getDescription() != null, "The descriptor for '" + descriptor.getPath()
+ "' must have a" + " description or it must be marked as ignored");
}
}
this.fieldDescriptors = descriptors;
@@ -174,8 +166,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
}
MediaType contentType = getContentType(operation);
if (this.subsectionExtractor != null) {
content = verifyContent(
this.subsectionExtractor.extractSubsection(content, contentType));
content = verifyContent(this.subsectionExtractor.extractSubsection(content, contentType));
}
ContentHandler contentHandler = getContentHandler(content, contentType);
@@ -189,9 +180,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
descriptorsToDocument.add(copyWithType(descriptor, type));
}
catch (FieldDoesNotExistException ex) {
String message = "Cannot determine the type of the field '"
+ descriptor.getPath() + "' as it is not present in the "
+ "payload. Please provide a type using "
String message = "Cannot determine the type of the field '" + descriptor.getPath()
+ "' as it is not present in the " + "payload. Please provide a type using "
+ "FieldDescriptor.type(Object type).";
throw new FieldTypeRequiredException(message);
}
@@ -211,8 +201,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
private byte[] verifyContent(byte[] content) {
if (content.length == 0) {
throw new SnippetException("Cannot document " + this.type + " fields as the "
+ this.type + " body is empty");
throw new SnippetException(
"Cannot document " + this.type + " fields as the " + this.type + " body is empty");
}
return content;
}
@@ -222,8 +212,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
if (contentHandler == null) {
contentHandler = createXmlContentHandler(content);
if (contentHandler == null) {
throw new PayloadHandlingException("Cannot handle " + contentType
+ " content as it could not be parsed as JSON or XML");
throw new PayloadHandlingException(
"Cannot handle " + contentType + " content as it could not be parsed as JSON or XML");
}
}
return contentHandler;
@@ -248,8 +238,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
}
private void validateFieldDocumentation(ContentHandler payloadHandler) {
List<FieldDescriptor> missingFields = payloadHandler
.findMissingFields(this.fieldDescriptors);
List<FieldDescriptor> missingFields = payloadHandler.findMissingFields(this.fieldDescriptors);
String undocumentedPayload = this.ignoreUndocumentedFields ? null
: payloadHandler.getUndocumentedContent(this.fieldDescriptors);
@@ -257,8 +246,8 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
if (!missingFields.isEmpty() || StringUtils.hasText(undocumentedPayload)) {
String message = "";
if (StringUtils.hasText(undocumentedPayload)) {
message += String.format("The following parts of the payload were"
+ " not documented:%n%s", undocumentedPayload);
message += String.format("The following parts of the payload were" + " not documented:%n%s",
undocumentedPayload);
}
if (!missingFields.isEmpty()) {
if (message.length() > 0) {
@@ -268,8 +257,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
for (FieldDescriptor fieldDescriptor : missingFields) {
paths.add(fieldDescriptor.getPath());
}
message += "Fields with the following paths were not found in the"
+ " payload: " + paths;
message += "Fields with the following paths were not found in the" + " payload: " + paths;
}
throw new SnippetException(message);
}
@@ -334,11 +322,9 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
}
private FieldDescriptor copyWithType(FieldDescriptor source, Object type) {
FieldDescriptor result = (source instanceof SubsectionDescriptor)
? new SubsectionDescriptor(source.getPath())
FieldDescriptor result = (source instanceof SubsectionDescriptor) ? new SubsectionDescriptor(source.getPath())
: new FieldDescriptor(source.getPath());
result.description(source.getDescription()).type(type)
.attributes(asArray(source.getAttributes()));
result.description(source.getDescription()).type(type).attributes(asArray(source.getAttributes()));
if (source.isIgnored()) {
result.ignored();
}
@@ -351,8 +337,7 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
private static Attribute[] asArray(Map<String, Object> attributeMap) {
List<Attributes.Attribute> attributes = new ArrayList<>();
for (Map.Entry<String, Object> attribute : attributeMap.entrySet()) {
attributes
.add(Attributes.key(attribute.getKey()).value(attribute.getValue()));
attributes.add(Attributes.key(attribute.getKey()).value(attribute.getValue()));
}
return attributes.toArray(new Attribute[attributes.size()]);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -72,13 +72,12 @@ public class FieldPathPayloadSubsectionExtractor
@Override
public byte[] extractSubsection(byte[] payload, MediaType contentType) {
try {
ExtractedField extractedField = new JsonFieldProcessor().extract(
this.fieldPath, objectMapper.readValue(payload, Object.class));
ExtractedField extractedField = new JsonFieldProcessor().extract(this.fieldPath,
objectMapper.readValue(payload, Object.class));
Object value = extractedField.getValue();
if (value instanceof List) {
List<?> extractedList = (List<?>) value;
Set<String> uncommonPaths = JsonFieldPaths.from(extractedList)
.getUncommon();
Set<String> uncommonPaths = JsonFieldPaths.from(extractedList).getUncommon();
if (uncommonPaths.isEmpty()) {
value = extractedList.get(0);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -31,8 +31,8 @@ class FieldTypesDoNotMatchException extends RuntimeException {
* @param actualType the actual type of the field
*/
FieldTypesDoNotMatchException(FieldDescriptor fieldDescriptor, Object actualType) {
super("The documented type of the field '" + fieldDescriptor.getPath() + "' is "
+ fieldDescriptor.getType() + " but the actual type is " + actualType);
super("The documented type of the field '" + fieldDescriptor.getPath() + "' is " + fieldDescriptor.getType()
+ " but the actual type is " + actualType);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -39,8 +39,7 @@ class JsonContentHandler implements ContentHandler {
private final JsonFieldTypeResolver fieldTypeResolver = new JsonFieldTypeResolver();
private final ObjectMapper objectMapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
private final ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final byte[] rawContent;
@@ -50,15 +49,12 @@ class JsonContentHandler implements ContentHandler {
}
@Override
public List<FieldDescriptor> findMissingFields(
List<FieldDescriptor> fieldDescriptors) {
public List<FieldDescriptor> findMissingFields(List<FieldDescriptor> fieldDescriptors) {
List<FieldDescriptor> missingFields = new ArrayList<>();
Object payload = readContent();
for (FieldDescriptor fieldDescriptor : fieldDescriptors) {
if (!fieldDescriptor.isOptional()
&& !this.fieldProcessor.hasField(fieldDescriptor.getPath(), payload)
&& !isNestedBeneathMissingOptionalField(fieldDescriptor,
fieldDescriptors, payload)) {
if (!fieldDescriptor.isOptional() && !this.fieldProcessor.hasField(fieldDescriptor.getPath(), payload)
&& !isNestedBeneathMissingOptionalField(fieldDescriptor, fieldDescriptors, payload)) {
missingFields.add(fieldDescriptor);
}
}
@@ -66,13 +62,12 @@ class JsonContentHandler implements ContentHandler {
return missingFields;
}
private boolean isNestedBeneathMissingOptionalField(FieldDescriptor missing,
List<FieldDescriptor> fieldDescriptors, Object payload) {
private boolean isNestedBeneathMissingOptionalField(FieldDescriptor missing, List<FieldDescriptor> fieldDescriptors,
Object payload) {
List<FieldDescriptor> candidates = new ArrayList<>(fieldDescriptors);
candidates.remove(missing);
for (FieldDescriptor candidate : candidates) {
if (candidate.isOptional()
&& missing.getPath().startsWith(candidate.getPath())
if (candidate.isOptional() && missing.getPath().startsWith(candidate.getPath())
&& isMissing(candidate, payload)) {
return true;
}
@@ -84,8 +79,7 @@ class JsonContentHandler implements ContentHandler {
if (!this.fieldProcessor.hasField(candidate.getPath(), payload)) {
return true;
}
ExtractedField extracted = this.fieldProcessor.extract(candidate.getPath(),
payload);
ExtractedField extracted = this.fieldProcessor.extract(candidate.getPath(), payload);
return extracted.getValue() == null || isEmptyCollection(extracted.getValue());
}
@@ -147,20 +141,16 @@ class JsonContentHandler implements ContentHandler {
@Override
public Object determineFieldType(FieldDescriptor fieldDescriptor) {
if (fieldDescriptor.getType() == null) {
return this.fieldTypeResolver.resolveFieldType(fieldDescriptor,
readContent());
return this.fieldTypeResolver.resolveFieldType(fieldDescriptor, readContent());
}
if (!(fieldDescriptor.getType() instanceof JsonFieldType)) {
return fieldDescriptor.getType();
}
JsonFieldType descriptorFieldType = (JsonFieldType) fieldDescriptor.getType();
try {
JsonFieldType actualFieldType = this.fieldTypeResolver
.resolveFieldType(fieldDescriptor, readContent());
if (descriptorFieldType == JsonFieldType.VARIES
|| descriptorFieldType == actualFieldType
|| (fieldDescriptor.isOptional()
&& actualFieldType == JsonFieldType.NULL)) {
JsonFieldType actualFieldType = this.fieldTypeResolver.resolveFieldType(fieldDescriptor, readContent());
if (descriptorFieldType == JsonFieldType.VARIES || descriptorFieldType == actualFieldType
|| (fieldDescriptor.isOptional() && actualFieldType == JsonFieldType.NULL)) {
return descriptorFieldType;
}
throw new FieldTypesDoNotMatchException(fieldDescriptor, actualFieldType);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -33,8 +33,7 @@ final class JsonFieldPath {
private static final Pattern BRACKETS_AND_ARRAY_PATTERN = Pattern
.compile("\\[\'(.+?)\'\\]|\\[([0-9]+|\\*){0,1}\\]");
private static final Pattern ARRAY_INDEX_PATTERN = Pattern
.compile("\\[([0-9]+|\\*){0,1}\\]");
private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("\\[([0-9]+|\\*){0,1}\\]");
private final String rawPath;
@@ -63,8 +62,7 @@ final class JsonFieldPath {
static JsonFieldPath compile(String path) {
List<String> segments = extractSegments(path);
return new JsonFieldPath(path, segments,
matchesSingleValue(segments) ? PathType.SINGLE : PathType.MULTI);
return new JsonFieldPath(path, segments, matchesSingleValue(segments) ? PathType.SINGLE : PathType.MULTI);
}
static boolean isArraySegment(String segment) {
@@ -75,8 +73,7 @@ final class JsonFieldPath {
Iterator<String> iterator = segments.iterator();
while (iterator.hasNext()) {
String segment = iterator.next();
if ((isArraySegment(segment) && iterator.hasNext())
|| isWildcardSegment(segment)) {
if ((isArraySegment(segment) && iterator.hasNext()) || isWildcardSegment(segment)) {
return false;
}
}
@@ -95,8 +92,7 @@ final class JsonFieldPath {
List<String> segments = new ArrayList<>();
while (matcher.find()) {
if (previous != matcher.start()) {
segments.addAll(extractDotSeparatedSegments(
path.substring(previous, matcher.start())));
segments.addAll(extractDotSeparatedSegments(path.substring(previous, matcher.start())));
}
if (matcher.group(1) != null) {
segments.add(matcher.group(1));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -58,43 +58,40 @@ final class JsonFieldProcessor {
if (matches.isEmpty()) {
throw new FieldDoesNotExistException(path);
}
return new ExtractedField(
(compiledPath.getType() != PathType.SINGLE) ? matches : matches.get(0),
return new ExtractedField((compiledPath.getType() != PathType.SINGLE) ? matches : matches.get(0),
compiledPath.getType());
}
void remove(String path, Object payload) {
traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)),
new MatchCallback() {
traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), new MatchCallback() {
@Override
public void foundMatch(Match match) {
match.remove();
}
@Override
public void foundMatch(Match match) {
match.remove();
}
@Override
public void absent() {
@Override
public void absent() {
}
}
});
});
}
void removeSubsection(String path, Object payload) {
traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)),
new MatchCallback() {
traverse(new ProcessingContext(payload, JsonFieldPath.compile(path)), new MatchCallback() {
@Override
public void foundMatch(Match match) {
match.removeSubsection();
}
@Override
public void foundMatch(Match match) {
match.removeSubsection();
}
@Override
public void absent() {
@Override
public void absent() {
}
}
});
});
}
private void traverse(ProcessingContext context, MatchCallback matchCallback) {
@@ -109,54 +106,48 @@ final class JsonFieldProcessor {
}
}
private void handleCollectionPayload(ProcessingContext context,
MatchCallback matchCallback) {
handleCollectionPayload((Collection<?>) context.getPayload(), matchCallback,
context);
private void handleCollectionPayload(ProcessingContext context, MatchCallback matchCallback) {
handleCollectionPayload((Collection<?>) context.getPayload(), matchCallback, context);
}
private void handleCollectionPayload(Collection<?> collection,
MatchCallback matchCallback, ProcessingContext context) {
private void handleCollectionPayload(Collection<?> collection, MatchCallback matchCallback,
ProcessingContext context) {
if (context.isLeaf()) {
matchCallback.foundMatch(
new LeafCollectionMatch(collection, context.getParentMatch()));
matchCallback.foundMatch(new LeafCollectionMatch(collection, context.getParentMatch()));
}
else {
Iterator<?> items = collection.iterator();
while (items.hasNext()) {
Object item = items.next();
traverse(context.descend(item, new CollectionMatch(items, collection,
item, context.getParentMatch())), matchCallback);
traverse(context.descend(item, new CollectionMatch(items, collection, item, context.getParentMatch())),
matchCallback);
}
}
}
private void handleWildcardPayload(Collection<?> collection,
MatchCallback matchCallback, ProcessingContext context) {
private void handleWildcardPayload(Collection<?> collection, MatchCallback matchCallback,
ProcessingContext context) {
Iterator<?> items = collection.iterator();
if (context.isLeaf()) {
while (items.hasNext()) {
Object item = items.next();
matchCallback.foundMatch(new CollectionMatch(items, collection, item,
context.getParentMatch()));
matchCallback.foundMatch(new CollectionMatch(items, collection, item, context.getParentMatch()));
}
}
else {
while (items.hasNext()) {
Object item = items.next();
traverse(context.descend(item, new CollectionMatch(items, collection,
item, context.getParentMatch())), matchCallback);
traverse(context.descend(item, new CollectionMatch(items, collection, item, context.getParentMatch())),
matchCallback);
}
}
}
private void handleMapPayload(ProcessingContext context,
MatchCallback matchCallback) {
private void handleMapPayload(ProcessingContext context, MatchCallback matchCallback) {
Map<?, ?> map = context.getPayload();
if (map.containsKey(context.getSegment())) {
Object item = map.get(context.getSegment());
MapMatch mapMatch = new MapMatch(item, map, context.getSegment(),
context.getParentMatch());
MapMatch mapMatch = new MapMatch(item, map, context.getSegment(), context.getParentMatch());
if (context.isLeaf()) {
matchCallback.foundMatch(mapMatch);
}
@@ -181,8 +172,8 @@ final class JsonFieldProcessor {
@Override
public void foundMatch(Match match) {
this.matchType = this.matchType.combinedWith(
(match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL);
this.matchType = this.matchType
.combinedWith((match.getValue() != null) ? MatchType.NON_NULL : MatchType.NULL);
}
@Override
@@ -191,8 +182,7 @@ final class JsonFieldProcessor {
}
boolean fieldFound() {
return this.matchType == MatchType.NON_NULL
|| this.matchType == MatchType.NULL;
return this.matchType == MatchType.NON_NULL || this.matchType == MatchType.NULL;
}
private enum MatchType {
@@ -235,8 +225,7 @@ final class JsonFieldProcessor {
@Override
public void remove() {
Object removalCandidate = this.map.get(this.segment);
if (isMapWithEntries(removalCandidate)
|| isCollectionWithNonScalarEntries(removalCandidate)) {
if (isMapWithEntries(removalCandidate) || isCollectionWithNonScalarEntries(removalCandidate)) {
return;
}
this.map.remove(this.segment);
@@ -281,8 +270,7 @@ final class JsonFieldProcessor {
private final Match parent;
private CollectionMatch(Iterator<?> items, Collection<?> collection, Object item,
Match parent) {
private CollectionMatch(Iterator<?> items, Collection<?> collection, Object item, Match parent) {
this.items = items;
this.collection = collection;
this.item = item;
@@ -404,8 +392,7 @@ final class JsonFieldProcessor {
this(payload, path, null, null);
}
private ProcessingContext(Object payload, JsonFieldPath path,
List<String> segments, Match parent) {
private ProcessingContext(Object payload, JsonFieldPath path, List<String> segments, Match parent) {
this.payload = payload;
this.path = path;
this.segments = (segments != null) ? segments : path.getSegments();
@@ -430,8 +417,7 @@ final class JsonFieldProcessor {
}
private ProcessingContext descend(Object payload, Match match) {
return new ProcessingContext(payload, this.path,
this.segments.subList(1, this.segments.size()), match);
return new ProcessingContext(payload, this.path, this.segments.subList(1, this.segments.size()), match);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 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.
@@ -32,8 +32,7 @@ class JsonFieldTypeResolver {
private final JsonFieldProcessor fieldProcessor = new JsonFieldProcessor();
JsonFieldType resolveFieldType(FieldDescriptor fieldDescriptor, Object payload) {
ExtractedField extractedField = this.fieldProcessor
.extract(fieldDescriptor.getPath(), payload);
ExtractedField extractedField = this.fieldProcessor.extract(fieldDescriptor.getPath(), payload);
Object value = extractedField.getValue();
if (value instanceof Collection && extractedField.getType() == PathType.MULTI) {
JsonFieldType commonType = null;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -228,8 +228,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
FieldDescriptor... descriptors) {
public static RequestFieldsSnippet relaxedRequestFields(FieldDescriptor... descriptors) {
return relaxedRequestFields(Arrays.asList(descriptors));
}
@@ -244,8 +243,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
List<FieldDescriptor> descriptors) {
public static RequestFieldsSnippet relaxedRequestFields(List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(descriptors, true);
}
@@ -271,8 +269,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestFieldsSnippet requestFields(Map<String, Object> attributes,
FieldDescriptor... descriptors) {
public static RequestFieldsSnippet requestFields(Map<String, Object> attributes, FieldDescriptor... descriptors) {
return requestFields(attributes, Arrays.asList(descriptors));
}
@@ -316,8 +313,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
Map<String, Object> attributes, FieldDescriptor... descriptors) {
public static RequestFieldsSnippet relaxedRequestFields(Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return relaxedRequestFields(attributes, Arrays.asList(descriptors));
}
@@ -334,8 +331,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
public static RequestFieldsSnippet relaxedRequestFields(Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(descriptors, attributes, true);
}
@@ -364,8 +361,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet requestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
return requestFields(subsectionExtractor, Arrays.asList(descriptors));
}
@@ -395,8 +391,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet requestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(subsectionExtractor, descriptors);
}
@@ -416,8 +411,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
return relaxedRequestFields(subsectionExtractor, Arrays.asList(descriptors));
}
@@ -437,8 +431,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(subsectionExtractor, descriptors, true);
}
@@ -470,8 +463,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet requestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return requestFields(subsectionExtractor, attributes, Arrays.asList(descriptors));
}
@@ -503,8 +495,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet requestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet requestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes);
}
@@ -526,11 +517,9 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return relaxedRequestFields(subsectionExtractor, attributes,
Arrays.asList(descriptors));
return relaxedRequestFields(subsectionExtractor, attributes, Arrays.asList(descriptors));
}
/**
@@ -550,11 +539,9 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static RequestFieldsSnippet relaxedRequestFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestFieldsSnippet relaxedRequestFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes,
true);
return new RequestFieldsSnippet(subsectionExtractor, descriptors, attributes, true);
}
/**
@@ -581,8 +568,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
FieldDescriptor... descriptors) {
public static RequestPartFieldsSnippet requestPartFields(String part, FieldDescriptor... descriptors) {
return requestPartFields(part, Arrays.asList(descriptors));
}
@@ -609,8 +595,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
List<FieldDescriptor> descriptors) {
public static RequestPartFieldsSnippet requestPartFields(String part, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, descriptors);
}
@@ -627,8 +612,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
FieldDescriptor... descriptors) {
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, Arrays.asList(descriptors));
}
@@ -645,8 +629,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
List<FieldDescriptor> descriptors) {
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, descriptors, true);
}
@@ -675,8 +658,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
public static RequestPartFieldsSnippet requestPartFields(String part, Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return requestPartFields(part, attributes, Arrays.asList(descriptors));
}
@@ -705,8 +688,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
public static RequestPartFieldsSnippet requestPartFields(String part, Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, descriptors, attributes);
}
@@ -725,8 +708,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, attributes, Arrays.asList(descriptors));
}
@@ -745,8 +728,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part, Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, descriptors, attributes, true);
}
@@ -778,8 +761,7 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
PayloadSubsectionExtractor<?> subsectionExtractor, FieldDescriptor... descriptors) {
return requestPartFields(part, subsectionExtractor, Arrays.asList(descriptors));
}
@@ -811,8 +793,7 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
PayloadSubsectionExtractor<?> subsectionExtractor, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors);
}
@@ -834,10 +815,8 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, subsectionExtractor,
Arrays.asList(descriptors));
PayloadSubsectionExtractor<?> subsectionExtractor, FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, subsectionExtractor, Arrays.asList(descriptors));
}
/**
@@ -858,8 +837,7 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
PayloadSubsectionExtractor<?> subsectionExtractor, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, true);
}
@@ -893,10 +871,9 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return requestPartFields(part, subsectionExtractor, attributes,
Arrays.asList(descriptors));
PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return requestPartFields(part, subsectionExtractor, attributes, Arrays.asList(descriptors));
}
/**
@@ -929,10 +906,9 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet requestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors,
attributes);
PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, attributes);
}
/**
@@ -955,10 +931,9 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, subsectionExtractor, attributes,
Arrays.asList(descriptors));
PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return relaxedRequestPartFields(part, subsectionExtractor, attributes, Arrays.asList(descriptors));
}
/**
@@ -981,10 +956,9 @@ public abstract class PayloadDocumentation {
* @see #beneathPath(String)
*/
public static RequestPartFieldsSnippet relaxedRequestPartFields(String part,
PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors,
attributes, true);
PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new RequestPartFieldsSnippet(part, subsectionExtractor, descriptors, attributes, true);
}
/**
@@ -1035,8 +1009,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet responseFields(
List<FieldDescriptor> descriptors) {
public static ResponseFieldsSnippet responseFields(List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(descriptors);
}
@@ -1054,8 +1027,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
FieldDescriptor... descriptors) {
public static ResponseFieldsSnippet relaxedResponseFields(FieldDescriptor... descriptors) {
return relaxedResponseFields(Arrays.asList(descriptors));
}
@@ -1071,8 +1043,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
List<FieldDescriptor> descriptors) {
public static ResponseFieldsSnippet relaxedResponseFields(List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(descriptors, true);
}
@@ -1098,8 +1069,7 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static ResponseFieldsSnippet responseFields(Map<String, Object> attributes,
FieldDescriptor... descriptors) {
public static ResponseFieldsSnippet responseFields(Map<String, Object> attributes, FieldDescriptor... descriptors) {
return responseFields(attributes, Arrays.asList(descriptors));
}
@@ -1143,8 +1113,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
Map<String, Object> attributes, FieldDescriptor... descriptors) {
public static ResponseFieldsSnippet relaxedResponseFields(Map<String, Object> attributes,
FieldDescriptor... descriptors) {
return relaxedResponseFields(attributes, Arrays.asList(descriptors));
}
@@ -1161,8 +1131,8 @@ public abstract class PayloadDocumentation {
* @see #fieldWithPath(String)
* @see #subsectionWithPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
public static ResponseFieldsSnippet relaxedResponseFields(Map<String, Object> attributes,
List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(descriptors, attributes, true);
}
@@ -1192,8 +1162,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet responseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
return responseFields(subsectionExtractor, Arrays.asList(descriptors));
}
@@ -1224,8 +1193,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet responseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(subsectionExtractor, descriptors);
}
@@ -1246,8 +1214,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
FieldDescriptor... descriptors) {
return relaxedResponseFields(subsectionExtractor, Arrays.asList(descriptors));
}
@@ -1268,8 +1235,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(subsectionExtractor, descriptors, true);
}
@@ -1302,11 +1268,9 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet responseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return responseFields(subsectionExtractor, attributes,
Arrays.asList(descriptors));
return responseFields(subsectionExtractor, attributes, Arrays.asList(descriptors));
}
/**
@@ -1337,8 +1301,7 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet responseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet responseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes);
}
@@ -1361,11 +1324,9 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, FieldDescriptor... descriptors) {
return relaxedResponseFields(subsectionExtractor, attributes,
Arrays.asList(descriptors));
return relaxedResponseFields(subsectionExtractor, attributes, Arrays.asList(descriptors));
}
/**
@@ -1386,11 +1347,9 @@ public abstract class PayloadDocumentation {
* @see #subsectionWithPath(String)
* @see #beneathPath(String)
*/
public static ResponseFieldsSnippet relaxedResponseFields(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseFieldsSnippet relaxedResponseFields(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes, List<FieldDescriptor> descriptors) {
return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes,
true);
return new ResponseFieldsSnippet(subsectionExtractor, descriptors, attributes, true);
}
/**
@@ -1420,8 +1379,7 @@ public abstract class PayloadDocumentation {
* @param subsectionExtractor the subsection extractor
* @return the snippet that will document the request body subsection
*/
public static RequestBodySnippet requestBody(
PayloadSubsectionExtractor<?> subsectionExtractor) {
public static RequestBodySnippet requestBody(PayloadSubsectionExtractor<?> subsectionExtractor) {
return new RequestBodySnippet(subsectionExtractor);
}
@@ -1434,8 +1392,7 @@ public abstract class PayloadDocumentation {
* @param attributes the attributes
* @return the snippet that will document the request body subsection
*/
public static RequestBodySnippet requestBody(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static RequestBodySnippet requestBody(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
return new RequestBodySnippet(subsectionExtractor, attributes);
}
@@ -1467,8 +1424,7 @@ public abstract class PayloadDocumentation {
* @param subsectionExtractor the subsection extractor
* @return the snippet that will document the response body subsection
*/
public static ResponseBodySnippet responseBody(
PayloadSubsectionExtractor<?> subsectionExtractor) {
public static ResponseBodySnippet responseBody(PayloadSubsectionExtractor<?> subsectionExtractor) {
return new ResponseBodySnippet(subsectionExtractor);
}
@@ -1481,8 +1437,7 @@ public abstract class PayloadDocumentation {
* @param attributes the attributes
* @return the snippet that will document the response body subsection
*/
public static ResponseBodySnippet responseBody(
PayloadSubsectionExtractor<?> subsectionExtractor,
public static ResponseBodySnippet responseBody(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
return new ResponseBodySnippet(subsectionExtractor, attributes);
}
@@ -1505,8 +1460,7 @@ public abstract class PayloadDocumentation {
* @param attributes the attributes
* @return the snippet that will document the response body
*/
public static RequestPartBodySnippet requestPartBody(String partName,
Map<String, Object> attributes) {
public static RequestPartBodySnippet requestPartBody(String partName, Map<String, Object> attributes) {
return new RequestPartBodySnippet(partName, attributes);
}
@@ -1534,8 +1488,7 @@ public abstract class PayloadDocumentation {
* @return the snippet that will document the response body
*/
public static RequestPartBodySnippet requestPartBody(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes) {
return new RequestPartBodySnippet(partName, subsectionExtractor, attributes);
}
@@ -1546,16 +1499,13 @@ public abstract class PayloadDocumentation {
* @param descriptors the descriptors to copy
* @return the copied descriptors with the prefix applied
*/
public static List<FieldDescriptor> applyPathPrefix(String pathPrefix,
List<FieldDescriptor> descriptors) {
public static List<FieldDescriptor> applyPathPrefix(String pathPrefix, List<FieldDescriptor> descriptors) {
List<FieldDescriptor> prefixedDescriptors = new ArrayList<>();
for (FieldDescriptor descriptor : descriptors) {
String prefixedPath = pathPrefix + descriptor.getPath();
FieldDescriptor prefixedDescriptor = (descriptor instanceof SubsectionDescriptor)
? new SubsectionDescriptor(prefixedPath)
: new FieldDescriptor(prefixedPath);
prefixedDescriptor.description(descriptor.getDescription())
.type(descriptor.getType())
? new SubsectionDescriptor(prefixedPath) : new FieldDescriptor(prefixedPath);
prefixedDescriptor.description(descriptor.getDescription()).type(descriptor.getType())
.attributes(asArray(descriptor.getAttributes()));
if (descriptor.isIgnored()) {
prefixedDescriptor.ignored();
@@ -1582,8 +1532,7 @@ public abstract class PayloadDocumentation {
private static Attribute[] asArray(Map<String, Object> attributeMap) {
List<Attributes.Attribute> attributes = new ArrayList<>();
for (Map.Entry<String, Object> attribute : attributeMap.entrySet()) {
attributes
.add(Attributes.key(attribute.getKey()).value(attribute.getValue()));
attributes.add(Attributes.key(attribute.getKey()).value(attribute.getValue()));
}
return attributes.toArray(new Attribute[attributes.size()]);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -63,8 +63,7 @@ public class RequestBodySnippet extends AbstractBodySnippet {
* @param subsectionExtractor the subsection extractor
* @param attributes the additional attributes
*/
public RequestBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
public RequestBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes) {
super("request", subsectionExtractor, attributes);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -52,8 +52,7 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors,
boolean ignoreUndocumentedFields) {
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors, boolean ignoreUndocumentedFields) {
this(descriptors, null, ignoreUndocumentedFields);
}
@@ -65,8 +64,7 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param attributes the additional attributes
*/
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors,
Map<String, Object> attributes) {
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors, Map<String, Object> attributes) {
this(descriptors, attributes, false);
}
@@ -80,8 +78,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
protected RequestFieldsSnippet(List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
this(null, descriptors, attributes, ignoreUndocumentedFields);
}
@@ -108,8 +106,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
* @since 1.2.0
*/
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, boolean ignoreUndocumentedFields) {
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor, List<FieldDescriptor> descriptors,
boolean ignoreUndocumentedFields) {
this(subsectionExtractor, descriptors, null, ignoreUndocumentedFields);
}
@@ -123,8 +121,8 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param attributes the additional attributes
* @since 1.2.0
*/
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes) {
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor, List<FieldDescriptor> descriptors,
Map<String, Object> attributes) {
this(subsectionExtractor, descriptors, attributes, false);
}
@@ -141,11 +139,9 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
* @since 1.2.0
*/
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
super("request", descriptors, attributes, ignoreUndocumentedFields,
subsectionExtractor);
protected RequestFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor, List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
super("request", descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor);
}
@Override
@@ -189,14 +185,13 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final RequestFieldsSnippet andWithPrefix(String pathPrefix,
FieldDescriptor... additionalDescriptors) {
public final RequestFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>();
combinedDescriptors.addAll(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix,
Arrays.asList(additionalDescriptors)));
return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors,
getAttributes(), isIgnoredUndocumentedFields());
combinedDescriptors
.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors)));
return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, getAttributes(),
isIgnoredUndocumentedFields());
}
/**
@@ -208,14 +203,11 @@ public class RequestFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final RequestFieldsSnippet andWithPrefix(String pathPrefix,
List<FieldDescriptor> additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(
getFieldDescriptors());
combinedDescriptors.addAll(
PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors,
getAttributes(), isIgnoredUndocumentedFields());
public final RequestFieldsSnippet andWithPrefix(String pathPrefix, List<FieldDescriptor> additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new RequestFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, getAttributes(),
isIgnoredUndocumentedFields());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -50,8 +50,7 @@ public class RequestPartBodySnippet extends AbstractBodySnippet {
* @param partName the name of the request part
* @param subsectionExtractor the subsection extractor
*/
public RequestPartBodySnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor) {
public RequestPartBodySnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor) {
this(partName, subsectionExtractor, null);
}
@@ -76,11 +75,9 @@ public class RequestPartBodySnippet extends AbstractBodySnippet {
* @param subsectionExtractor the subsection extractor
* @param attributes the additional attributes
*/
public RequestPartBodySnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
public RequestPartBodySnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
super("request-part-" + partName, "request-part", subsectionExtractor,
attributes);
super("request-part-" + partName, "request-part", subsectionExtractor, attributes);
this.partName = partName;
}
@@ -100,8 +97,7 @@ public class RequestPartBodySnippet extends AbstractBodySnippet {
return candidate;
}
}
throw new SnippetException("A request part named '" + this.partName
+ "' was not found in the request");
throw new SnippetException("A request part named '" + this.partName + "' was not found in the request");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -48,8 +48,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param partName the part name
* @param descriptors the descriptors
*/
protected RequestPartFieldsSnippet(String partName,
List<FieldDescriptor> descriptors) {
protected RequestPartFieldsSnippet(String partName, List<FieldDescriptor> descriptors) {
this(partName, descriptors, null, false);
}
@@ -106,8 +105,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param subsectionExtractor the subsection extractor
* @param descriptors the descriptors
*/
protected RequestPartFieldsSnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors) {
this(partName, subsectionExtractor, descriptors, null, false);
}
@@ -123,8 +121,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected RequestPartFieldsSnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, boolean ignoreUndocumentedFields) {
this(partName, subsectionExtractor, descriptors, null, ignoreUndocumentedFields);
}
@@ -140,8 +137,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param attributes the additional attributes
*/
protected RequestPartFieldsSnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes) {
this(partName, subsectionExtractor, descriptors, attributes, false);
}
@@ -159,12 +155,10 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected RequestPartFieldsSnippet(String partName,
PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
super("request-part-" + partName, "request-part", descriptors, attributes,
ignoreUndocumentedFields, subsectionExtractor);
protected RequestPartFieldsSnippet(String partName, PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
super("request-part-" + partName, "request-part", descriptors, attributes, ignoreUndocumentedFields,
subsectionExtractor);
this.partName = partName;
}
@@ -184,8 +178,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
return candidate;
}
}
throw new SnippetException("A request part named '" + this.partName
+ "' was not found in the request");
throw new SnippetException("A request part named '" + this.partName + "' was not found in the request");
}
/**
@@ -206,8 +199,7 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final RequestPartFieldsSnippet and(
List<FieldDescriptor> additionalDescriptors) {
public final RequestPartFieldsSnippet and(List<FieldDescriptor> additionalDescriptors) {
return andWithPrefix("", additionalDescriptors);
}
@@ -220,14 +212,12 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix,
FieldDescriptor... additionalDescriptors) {
public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>();
combinedDescriptors.addAll(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix,
Arrays.asList(additionalDescriptors)));
return new RequestPartFieldsSnippet(this.partName, combinedDescriptors,
this.getAttributes());
combinedDescriptors
.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors)));
return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, this.getAttributes());
}
/**
@@ -241,12 +231,9 @@ public class RequestPartFieldsSnippet extends AbstractFieldsSnippet {
*/
public final RequestPartFieldsSnippet andWithPrefix(String pathPrefix,
List<FieldDescriptor> additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(
getFieldDescriptors());
combinedDescriptors.addAll(
PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new RequestPartFieldsSnippet(this.partName, combinedDescriptors,
this.getAttributes());
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new RequestPartFieldsSnippet(this.partName, combinedDescriptors, this.getAttributes());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -63,8 +63,7 @@ public class ResponseBodySnippet extends AbstractBodySnippet {
* @param subsectionExtractor the subsection extractor
* @param attributes the additional attributes
*/
public ResponseBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
Map<String, Object> attributes) {
public ResponseBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes) {
super("response", subsectionExtractor, attributes);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -53,8 +53,7 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors,
boolean ignoreUndocumentedFields) {
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors, boolean ignoreUndocumentedFields) {
this(descriptors, null, ignoreUndocumentedFields);
}
@@ -66,8 +65,7 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @param descriptors the descriptors
* @param attributes the additional attributes
*/
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors,
Map<String, Object> attributes) {
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors, Map<String, Object> attributes) {
this(descriptors, attributes, false);
}
@@ -81,8 +79,8 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedFields whether undocumented fields should be ignored
*/
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
protected ResponseFieldsSnippet(List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
this(null, descriptors, attributes, ignoreUndocumentedFields);
}
@@ -146,10 +144,8 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @since 1.2.0
*/
protected ResponseFieldsSnippet(PayloadSubsectionExtractor<?> subsectionExtractor,
List<FieldDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedFields) {
super("response", descriptors, attributes, ignoreUndocumentedFields,
subsectionExtractor);
List<FieldDescriptor> descriptors, Map<String, Object> attributes, boolean ignoreUndocumentedFields) {
super("response", descriptors, attributes, ignoreUndocumentedFields, subsectionExtractor);
}
@Override
@@ -193,14 +189,13 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final ResponseFieldsSnippet andWithPrefix(String pathPrefix,
FieldDescriptor... additionalDescriptors) {
public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>();
combinedDescriptors.addAll(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix,
Arrays.asList(additionalDescriptors)));
return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors,
this.getAttributes(), isIgnoredUndocumentedFields());
combinedDescriptors
.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors)));
return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, this.getAttributes(),
isIgnoredUndocumentedFields());
}
/**
@@ -212,14 +207,11 @@ public class ResponseFieldsSnippet extends AbstractFieldsSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final ResponseFieldsSnippet andWithPrefix(String pathPrefix,
List<FieldDescriptor> additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(
getFieldDescriptors());
combinedDescriptors.addAll(
PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors,
this.getAttributes(), isIgnoredUndocumentedFields());
public final ResponseFieldsSnippet andWithPrefix(String pathPrefix, List<FieldDescriptor> additionalDescriptors) {
List<FieldDescriptor> combinedDescriptors = new ArrayList<>(getFieldDescriptors());
combinedDescriptors.addAll(PayloadDocumentation.applyPathPrefix(pathPrefix, additionalDescriptors));
return new ResponseFieldsSnippet(getSubsectionExtractor(), combinedDescriptors, this.getAttributes(),
isIgnoredUndocumentedFields());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 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.
@@ -55,8 +55,7 @@ class XmlContentHandler implements ContentHandler {
XmlContentHandler(byte[] rawContent) {
try {
this.documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
this.documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
catch (ParserConfigurationException ex) {
throw new IllegalStateException("Failed to create document builder", ex);
@@ -66,8 +65,7 @@ class XmlContentHandler implements ContentHandler {
}
@Override
public List<FieldDescriptor> findMissingFields(
List<FieldDescriptor> fieldDescriptors) {
public List<FieldDescriptor> findMissingFields(List<FieldDescriptor> fieldDescriptors) {
List<FieldDescriptor> missingFields = new ArrayList<>();
Document payload = readPayload();
for (FieldDescriptor fieldDescriptor : fieldDescriptors) {
@@ -82,11 +80,9 @@ class XmlContentHandler implements ContentHandler {
return missingFields;
}
private NodeList findMatchingNodes(FieldDescriptor fieldDescriptor,
Document payload) {
private NodeList findMatchingNodes(FieldDescriptor fieldDescriptor, Document payload) {
try {
return (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload,
XPathConstants.NODESET);
return (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload, XPathConstants.NODESET);
}
catch (XPathExpressionException ex) {
throw new PayloadHandlingException(ex);
@@ -95,16 +91,14 @@ class XmlContentHandler implements ContentHandler {
private Document readPayload() {
try {
return this.documentBuilder
.parse(new InputSource(new ByteArrayInputStream(this.rawContent)));
return this.documentBuilder.parse(new InputSource(new ByteArrayInputStream(this.rawContent)));
}
catch (Exception ex) {
throw new PayloadHandlingException(ex);
}
}
private XPathExpression createXPath(String fieldPath)
throws XPathExpressionException {
private XPathExpression createXPath(String fieldPath) throws XPathExpressionException {
return XPathFactory.newInstance().newXPath().compile(fieldPath);
}
@@ -115,8 +109,8 @@ class XmlContentHandler implements ContentHandler {
for (FieldDescriptor fieldDescriptor : fieldDescriptors) {
NodeList matchingNodes;
try {
matchingNodes = (NodeList) createXPath(fieldDescriptor.getPath())
.evaluate(payload, XPathConstants.NODESET);
matchingNodes = (NodeList) createXPath(fieldDescriptor.getPath()).evaluate(payload,
XPathConstants.NODESET);
}
catch (XPathExpressionException ex) {
throw new PayloadHandlingException(ex);
@@ -128,8 +122,7 @@ class XmlContentHandler implements ContentHandler {
attr.getOwnerElement().removeAttributeNode(attr);
}
else {
if (fieldDescriptor instanceof SubsectionDescriptor
|| isLeafNode(node)) {
if (fieldDescriptor instanceof SubsectionDescriptor || isLeafNode(node)) {
node.getParentNode().removeChild(node);
}
else {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -55,8 +55,8 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
* {@link #AbstractParametersSnippet(String, List, Map, boolean)}
*/
@Deprecated
protected AbstractParametersSnippet(String snippetName,
List<ParameterDescriptor> descriptors, Map<String, Object> attributes) {
protected AbstractParametersSnippet(String snippetName, List<ParameterDescriptor> descriptors,
Map<String, Object> attributes) {
this(snippetName, descriptors, attributes, false);
}
@@ -72,18 +72,14 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
* @param ignoreUndocumentedParameters whether undocumented parameters should be
* ignored
*/
protected AbstractParametersSnippet(String snippetName,
List<ParameterDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedParameters) {
protected AbstractParametersSnippet(String snippetName, List<ParameterDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedParameters) {
super(snippetName, attributes);
for (ParameterDescriptor descriptor : descriptors) {
Assert.notNull(descriptor.getName(),
"Parameter descriptors must have a name");
Assert.notNull(descriptor.getName(), "Parameter descriptors must have a name");
if (!descriptor.isIgnored()) {
Assert.notNull(descriptor.getDescription(),
"The descriptor for parameter '" + descriptor.getName()
+ "' must either have a description or be marked as "
+ "ignored");
Assert.notNull(descriptor.getDescription(), "The descriptor for parameter '" + descriptor.getName()
+ "' must either have a description or be marked as " + "ignored");
}
this.descriptorsByName.put(descriptor.getName(), descriptor);
}
@@ -96,8 +92,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
Map<String, Object> model = new HashMap<>();
List<Map<String, Object>> parameters = new ArrayList<>();
for (Entry<String, ParameterDescriptor> entry : this.descriptorsByName
.entrySet()) {
for (Entry<String, ParameterDescriptor> entry : this.descriptorsByName.entrySet()) {
ParameterDescriptor descriptor = entry.getValue();
if (!descriptor.isIgnored()) {
parameters.add(createModelForDescriptor(descriptor));
@@ -110,8 +105,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
private void verifyParameterDescriptors(Operation operation) {
Set<String> actualParameters = extractActualParameters(operation);
Set<String> expectedParameters = new HashSet<>();
for (Entry<String, ParameterDescriptor> entry : this.descriptorsByName
.entrySet()) {
for (Entry<String, ParameterDescriptor> entry : this.descriptorsByName.entrySet()) {
if (!entry.getValue().isOptional()) {
expectedParameters.add(entry.getKey());
}
@@ -147,8 +141,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
* @param missingParameters the parameters that were documented but were not found in
* the operation
*/
protected abstract void verificationFailed(Set<String> undocumentedParameters,
Set<String> missingParameters);
protected abstract void verificationFailed(Set<String> undocumentedParameters, Set<String> missingParameters);
/**
* Returns a {@code Map} of {@link ParameterDescriptor ParameterDescriptors} that will
@@ -177,8 +170,7 @@ public abstract class AbstractParametersSnippet extends TemplatedSnippet {
* @param descriptor the descriptor
* @return the model
*/
protected Map<String, Object> createModelForDescriptor(
ParameterDescriptor descriptor) {
protected Map<String, Object> createModelForDescriptor(ParameterDescriptor descriptor) {
Map<String, Object> model = new HashMap<>();
model.put("name", descriptor.getName());
model.put("description", descriptor.getDescription());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -61,8 +61,7 @@ public class PathParametersSnippet extends AbstractParametersSnippet {
* @param ignoreUndocumentedParameters whether undocumented parameters should be
* ignored
*/
protected PathParametersSnippet(List<ParameterDescriptor> descriptors,
boolean ignoreUndocumentedParameters) {
protected PathParametersSnippet(List<ParameterDescriptor> descriptors, boolean ignoreUndocumentedParameters) {
this(descriptors, null, ignoreUndocumentedParameters);
}
@@ -74,8 +73,7 @@ public class PathParametersSnippet extends AbstractParametersSnippet {
* @param descriptors the parameter descriptors
* @param attributes the additional attributes
*/
protected PathParametersSnippet(List<ParameterDescriptor> descriptors,
Map<String, Object> attributes) {
protected PathParametersSnippet(List<ParameterDescriptor> descriptors, Map<String, Object> attributes) {
this(descriptors, attributes, false);
}
@@ -90,8 +88,8 @@ public class PathParametersSnippet extends AbstractParametersSnippet {
* @param ignoreUndocumentedParameters whether undocumented parameters should be
* ignored
*/
protected PathParametersSnippet(List<ParameterDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedParameters) {
protected PathParametersSnippet(List<ParameterDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedParameters) {
super("path-parameters", descriptors, attributes, ignoreUndocumentedParameters);
}
@@ -136,19 +134,17 @@ public class PathParametersSnippet extends AbstractParametersSnippet {
}
@Override
protected void verificationFailed(Set<String> undocumentedParameters,
Set<String> missingParameters) {
protected void verificationFailed(Set<String> undocumentedParameters, Set<String> missingParameters) {
String message = "";
if (!undocumentedParameters.isEmpty()) {
message += "Path parameters with the following names were not documented: "
+ undocumentedParameters;
message += "Path parameters with the following names were not documented: " + undocumentedParameters;
}
if (!missingParameters.isEmpty()) {
if (message.length() > 0) {
message += ". ";
}
message += "Path parameters with the following names were not found in "
+ "the request: " + missingParameters;
message += "Path parameters with the following names were not found in " + "the request: "
+ missingParameters;
}
throw new SnippetException(message);
}
@@ -171,10 +167,8 @@ public class PathParametersSnippet extends AbstractParametersSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final PathParametersSnippet and(
List<ParameterDescriptor> additionalDescriptors) {
List<ParameterDescriptor> combinedDescriptors = new ArrayList<>(
getParameterDescriptors().values());
public final PathParametersSnippet and(List<ParameterDescriptor> additionalDescriptors) {
List<ParameterDescriptor> combinedDescriptors = new ArrayList<>(getParameterDescriptors().values());
combinedDescriptors.addAll(additionalDescriptors);
return new PathParametersSnippet(combinedDescriptors, this.getAttributes());
}

View File

@@ -70,8 +70,7 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet pathParameters(
ParameterDescriptor... descriptors) {
public static PathParametersSnippet pathParameters(ParameterDescriptor... descriptors) {
return pathParameters(Arrays.asList(descriptors));
}
@@ -91,8 +90,7 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet pathParameters(
List<ParameterDescriptor> descriptors) {
public static PathParametersSnippet pathParameters(List<ParameterDescriptor> descriptors) {
return new PathParametersSnippet(descriptors);
}
@@ -106,8 +104,7 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet relaxedPathParameters(
ParameterDescriptor... descriptors) {
public static PathParametersSnippet relaxedPathParameters(ParameterDescriptor... descriptors) {
return relaxedPathParameters(Arrays.asList(descriptors));
}
@@ -121,8 +118,7 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet relaxedPathParameters(
List<ParameterDescriptor> descriptors) {
public static PathParametersSnippet relaxedPathParameters(List<ParameterDescriptor> descriptors) {
return new PathParametersSnippet(descriptors, true);
}
@@ -184,8 +180,8 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet relaxedPathParameters(
Map<String, Object> attributes, ParameterDescriptor... descriptors) {
public static PathParametersSnippet relaxedPathParameters(Map<String, Object> attributes,
ParameterDescriptor... descriptors) {
return relaxedPathParameters(attributes, Arrays.asList(descriptors));
}
@@ -201,8 +197,8 @@ public abstract class RequestDocumentation {
* @param descriptors the descriptions of the parameters in the request's path
* @return the snippet that will document the parameters
*/
public static PathParametersSnippet relaxedPathParameters(
Map<String, Object> attributes, List<ParameterDescriptor> descriptors) {
public static PathParametersSnippet relaxedPathParameters(Map<String, Object> attributes,
List<ParameterDescriptor> descriptors) {
return new PathParametersSnippet(descriptors, attributes, true);
}
@@ -223,8 +219,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet requestParameters(
ParameterDescriptor... descriptors) {
public static RequestParametersSnippet requestParameters(ParameterDescriptor... descriptors) {
return requestParameters(Arrays.asList(descriptors));
}
@@ -245,8 +240,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet requestParameters(
List<ParameterDescriptor> descriptors) {
public static RequestParametersSnippet requestParameters(List<ParameterDescriptor> descriptors) {
return new RequestParametersSnippet(descriptors);
}
@@ -261,8 +255,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet relaxedRequestParameters(
ParameterDescriptor... descriptors) {
public static RequestParametersSnippet relaxedRequestParameters(ParameterDescriptor... descriptors) {
return relaxedRequestParameters(Arrays.asList(descriptors));
}
@@ -277,8 +270,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet relaxedRequestParameters(
List<ParameterDescriptor> descriptors) {
public static RequestParametersSnippet relaxedRequestParameters(List<ParameterDescriptor> descriptors) {
return new RequestParametersSnippet(descriptors, true);
}
@@ -301,8 +293,8 @@ public abstract class RequestDocumentation {
* @return the snippet that will document the parameters
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet requestParameters(
Map<String, Object> attributes, ParameterDescriptor... descriptors) {
public static RequestParametersSnippet requestParameters(Map<String, Object> attributes,
ParameterDescriptor... descriptors) {
return requestParameters(attributes, Arrays.asList(descriptors));
}
@@ -325,8 +317,8 @@ public abstract class RequestDocumentation {
* @return the snippet that will document the parameters
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet requestParameters(
Map<String, Object> attributes, List<ParameterDescriptor> descriptors) {
public static RequestParametersSnippet requestParameters(Map<String, Object> attributes,
List<ParameterDescriptor> descriptors) {
return new RequestParametersSnippet(descriptors, attributes);
}
@@ -343,8 +335,8 @@ public abstract class RequestDocumentation {
* @return the snippet that will document the parameters
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet relaxedRequestParameters(
Map<String, Object> attributes, ParameterDescriptor... descriptors) {
public static RequestParametersSnippet relaxedRequestParameters(Map<String, Object> attributes,
ParameterDescriptor... descriptors) {
return relaxedRequestParameters(attributes, Arrays.asList(descriptors));
}
@@ -361,8 +353,8 @@ public abstract class RequestDocumentation {
* @return the snippet that will document the parameters
* @see OperationRequest#getParameters()
*/
public static RequestParametersSnippet relaxedRequestParameters(
Map<String, Object> attributes, List<ParameterDescriptor> descriptors) {
public static RequestParametersSnippet relaxedRequestParameters(Map<String, Object> attributes,
List<ParameterDescriptor> descriptors) {
return new RequestParametersSnippet(descriptors, attributes, true);
}
@@ -402,8 +394,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParts()
*/
public static RequestPartsSnippet requestParts(
List<RequestPartDescriptor> descriptors) {
public static RequestPartsSnippet requestParts(List<RequestPartDescriptor> descriptors) {
return new RequestPartsSnippet(descriptors);
}
@@ -417,8 +408,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParts()
*/
public static RequestPartsSnippet relaxedRequestParts(
RequestPartDescriptor... descriptors) {
public static RequestPartsSnippet relaxedRequestParts(RequestPartDescriptor... descriptors) {
return relaxedRequestParts(Arrays.asList(descriptors));
}
@@ -432,8 +422,7 @@ public abstract class RequestDocumentation {
* @return the snippet
* @see OperationRequest#getParts()
*/
public static RequestPartsSnippet relaxedRequestParts(
List<RequestPartDescriptor> descriptors) {
public static RequestPartsSnippet relaxedRequestParts(List<RequestPartDescriptor> descriptors) {
return new RequestPartsSnippet(descriptors, true);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -59,8 +59,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet {
* @param ignoreUndocumentedParameters whether undocumented parameters should be
* ignored
*/
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors,
boolean ignoreUndocumentedParameters) {
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors, boolean ignoreUndocumentedParameters) {
this(descriptors, null, ignoreUndocumentedParameters);
}
@@ -72,8 +71,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet {
* @param descriptors the parameter descriptors
* @param attributes the additional attributes
*/
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors,
Map<String, Object> attributes) {
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors, Map<String, Object> attributes) {
this(descriptors, attributes, false);
}
@@ -88,19 +86,16 @@ public class RequestParametersSnippet extends AbstractParametersSnippet {
* @param ignoreUndocumentedParameters whether undocumented parameters should be
* ignored
*/
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedParameters) {
super("request-parameters", descriptors, attributes,
ignoreUndocumentedParameters);
protected RequestParametersSnippet(List<ParameterDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedParameters) {
super("request-parameters", descriptors, attributes, ignoreUndocumentedParameters);
}
@Override
protected void verificationFailed(Set<String> undocumentedParameters,
Set<String> missingParameters) {
protected void verificationFailed(Set<String> undocumentedParameters, Set<String> missingParameters) {
String message = "";
if (!undocumentedParameters.isEmpty()) {
message += "Request parameters with the following names were not documented: "
+ undocumentedParameters;
message += "Request parameters with the following names were not documented: " + undocumentedParameters;
}
if (!missingParameters.isEmpty()) {
if (message.length() > 0) {
@@ -136,8 +131,7 @@ public class RequestParametersSnippet extends AbstractParametersSnippet {
* @return the new snippet
*/
public RequestParametersSnippet and(List<ParameterDescriptor> additionalDescriptors) {
List<ParameterDescriptor> combinedDescriptors = new ArrayList<>(
getParameterDescriptors().values());
List<ParameterDescriptor> combinedDescriptors = new ArrayList<>(getParameterDescriptors().values());
combinedDescriptors.addAll(additionalDescriptors);
return new RequestParametersSnippet(combinedDescriptors, this.getAttributes());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -66,8 +66,7 @@ public class RequestPartsSnippet extends TemplatedSnippet {
* @param descriptors the parameter descriptors
* @param ignoreUndocumentedParts whether undocumented parts should be ignored
*/
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors,
boolean ignoreUndocumentedParts) {
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors, boolean ignoreUndocumentedParts) {
this(descriptors, null, ignoreUndocumentedParts);
}
@@ -78,8 +77,7 @@ public class RequestPartsSnippet extends TemplatedSnippet {
* @param descriptors the parameter descriptors
* @param attributes the additional attributes
*/
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors,
Map<String, Object> attributes) {
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors, Map<String, Object> attributes) {
this(descriptors, attributes, false);
}
@@ -92,17 +90,14 @@ public class RequestPartsSnippet extends TemplatedSnippet {
* @param attributes the additional attributes
* @param ignoreUndocumentedParts whether undocumented parts should be ignored
*/
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors,
Map<String, Object> attributes, boolean ignoreUndocumentedParts) {
protected RequestPartsSnippet(List<RequestPartDescriptor> descriptors, Map<String, Object> attributes,
boolean ignoreUndocumentedParts) {
super("request-parts", attributes);
for (RequestPartDescriptor descriptor : descriptors) {
Assert.notNull(descriptor.getName(),
"Request part descriptors must have a name");
Assert.notNull(descriptor.getName(), "Request part descriptors must have a name");
if (!descriptor.isIgnored()) {
Assert.notNull(descriptor.getDescription(),
"The descriptor for request part '" + descriptor.getName()
+ "' must either have a description or be marked as "
+ "ignored");
Assert.notNull(descriptor.getDescription(), "The descriptor for request part '" + descriptor.getName()
+ "' must either have a description or be marked as " + "ignored");
}
this.descriptorsByName.put(descriptor.getName(), descriptor);
}
@@ -125,10 +120,8 @@ public class RequestPartsSnippet extends TemplatedSnippet {
* @param additionalDescriptors the additional descriptors
* @return the new snippet
*/
public final RequestPartsSnippet and(
List<RequestPartDescriptor> additionalDescriptors) {
List<RequestPartDescriptor> combinedDescriptors = new ArrayList<>(
this.descriptorsByName.values());
public final RequestPartsSnippet and(List<RequestPartDescriptor> additionalDescriptors) {
List<RequestPartDescriptor> combinedDescriptors = new ArrayList<>(this.descriptorsByName.values());
combinedDescriptors.addAll(additionalDescriptors);
return new RequestPartsSnippet(combinedDescriptors, this.getAttributes());
}
@@ -138,8 +131,7 @@ public class RequestPartsSnippet extends TemplatedSnippet {
verifyRequestPartDescriptors(operation);
Map<String, Object> model = new HashMap<>();
List<Map<String, Object>> requestParts = new ArrayList<>();
for (Entry<String, RequestPartDescriptor> entry : this.descriptorsByName
.entrySet()) {
for (Entry<String, RequestPartDescriptor> entry : this.descriptorsByName.entrySet()) {
RequestPartDescriptor descriptor = entry.getValue();
if (!descriptor.isIgnored()) {
requestParts.add(createModelForDescriptor(descriptor));
@@ -152,8 +144,7 @@ public class RequestPartsSnippet extends TemplatedSnippet {
private void verifyRequestPartDescriptors(Operation operation) {
Set<String> actualRequestParts = extractActualRequestParts(operation);
Set<String> expectedRequestParts = new HashSet<>();
for (Entry<String, RequestPartDescriptor> entry : this.descriptorsByName
.entrySet()) {
for (Entry<String, RequestPartDescriptor> entry : this.descriptorsByName.entrySet()) {
if (!entry.getValue().isOptional()) {
expectedRequestParts.add(entry.getKey());
}
@@ -183,25 +174,22 @@ public class RequestPartsSnippet extends TemplatedSnippet {
return actualRequestParts;
}
private void verificationFailed(Set<String> undocumentedRequestParts,
Set<String> missingRequestParts) {
private void verificationFailed(Set<String> undocumentedRequestParts, Set<String> missingRequestParts) {
String message = "";
if (!undocumentedRequestParts.isEmpty()) {
message += "Request parts with the following names were not documented: "
+ undocumentedRequestParts;
message += "Request parts with the following names were not documented: " + undocumentedRequestParts;
}
if (!missingRequestParts.isEmpty()) {
if (message.length() > 0) {
message += ". ";
}
message += "Request parts with the following names were not found in "
+ "the request: " + missingRequestParts;
message += "Request parts with the following names were not found in " + "the request: "
+ missingRequestParts;
}
throw new SnippetException(message);
}
private Map<String, Object> createModelForDescriptor(
RequestPartDescriptor descriptor) {
private Map<String, Object> createModelForDescriptor(RequestPartDescriptor descriptor) {
Map<String, Object> model = new HashMap<>();
model.put("name", descriptor.getName());
model.put("description", descriptor.getDescription());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -22,8 +22,7 @@ package org.springframework.restdocs.snippet;
* @param <T> the type of the descriptor
* @author Andy Wilkinson
*/
public abstract class IgnorableDescriptor<T extends IgnorableDescriptor<T>>
extends AbstractDescriptor<T> {
public abstract class IgnorableDescriptor<T extends IgnorableDescriptor<T>> extends AbstractDescriptor<T> {
private boolean ignored = false;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -133,8 +133,7 @@ public class RestDocumentationContextPlaceholderResolver implements PlaceholderR
Matcher matcher = CAMEL_CASE_PATTERN.matcher(string);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String replacement = (matcher.start() > 0)
? separator + matcher.group(1).toLowerCase()
String replacement = (matcher.start() > 0) ? separator + matcher.group(1).toLowerCase()
: matcher.group(1).toLowerCase();
matcher.appendReplacement(result, replacement);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -26,8 +26,7 @@ import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
* @author Andy Wilkinson
* @since 1.1.0
*/
public final class RestDocumentationContextPlaceholderResolverFactory
implements PlaceholderResolverFactory {
public final class RestDocumentationContextPlaceholderResolverFactory implements PlaceholderResolverFactory {
@Override
public PlaceholderResolver create(RestDocumentationContext context) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -37,8 +37,7 @@ public final class StandardWriterResolver implements WriterResolver {
private final PlaceholderResolverFactory placeholderResolverFactory;
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(
"{", "}");
private final PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}");
private String encoding = "UTF-8";
@@ -55,8 +54,7 @@ public final class StandardWriterResolver implements WriterResolver {
*/
@Deprecated
public StandardWriterResolver(PlaceholderResolver placeholderResolver) {
this(new SingleInstancePlaceholderResolverFactory(placeholderResolver), "UTF-8",
TemplateFormats.asciidoctor());
this(new SingleInstancePlaceholderResolverFactory(placeholderResolver), "UTF-8", TemplateFormats.asciidoctor());
}
/**
@@ -70,26 +68,24 @@ public final class StandardWriterResolver implements WriterResolver {
* @param encoding the encoding
* @param templateFormat the snippet format
*/
public StandardWriterResolver(PlaceholderResolverFactory placeholderResolverFactory,
String encoding, TemplateFormat templateFormat) {
public StandardWriterResolver(PlaceholderResolverFactory placeholderResolverFactory, String encoding,
TemplateFormat templateFormat) {
this.placeholderResolverFactory = placeholderResolverFactory;
this.encoding = encoding;
this.templateFormat = templateFormat;
}
@Override
public Writer resolve(String operationName, String snippetName,
RestDocumentationContext context) throws IOException {
PlaceholderResolver placeholderResolver = this.placeholderResolverFactory
.create(context);
public Writer resolve(String operationName, String snippetName, RestDocumentationContext context)
throws IOException {
PlaceholderResolver placeholderResolver = this.placeholderResolverFactory.create(context);
String outputDirectory = replacePlaceholders(placeholderResolver, operationName);
String fileName = replacePlaceholders(placeholderResolver, snippetName) + "."
+ this.templateFormat.getFileExtension();
File outputFile = resolveFile(outputDirectory, fileName, context);
if (outputFile != null) {
createDirectoriesIfNecessary(outputFile);
return new OutputStreamWriter(new FileOutputStream(outputFile),
this.encoding);
return new OutputStreamWriter(new FileOutputStream(outputFile), this.encoding);
}
else {
return new OutputStreamWriter(System.out, this.encoding);
@@ -106,8 +102,7 @@ public final class StandardWriterResolver implements WriterResolver {
return this.propertyPlaceholderHelper.replacePlaceholders(input, resolver);
}
File resolveFile(String outputDirectory, String fileName,
RestDocumentationContext context) {
File resolveFile(String outputDirectory, String fileName, RestDocumentationContext context) {
File outputFile = new File(outputDirectory, fileName);
if (!outputFile.isAbsolute()) {
outputFile = makeRelativeToConfiguredOutputDir(outputFile, context);
@@ -115,8 +110,7 @@ public final class StandardWriterResolver implements WriterResolver {
return outputFile;
}
private File makeRelativeToConfiguredOutputDir(File outputFile,
RestDocumentationContext context) {
private File makeRelativeToConfiguredOutputDir(File outputFile, RestDocumentationContext context) {
File configuredOutputDir = context.getOutputDirectory();
if (configuredOutputDir != null) {
return new File(configuredOutputDir, outputFile.getPath());
@@ -127,18 +121,15 @@ public final class StandardWriterResolver implements WriterResolver {
private void createDirectoriesIfNecessary(File outputFile) {
File parent = outputFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IllegalStateException(
"Failed to create directory '" + parent + "'");
throw new IllegalStateException("Failed to create directory '" + parent + "'");
}
}
private static final class SingleInstancePlaceholderResolverFactory
implements PlaceholderResolverFactory {
private static final class SingleInstancePlaceholderResolverFactory implements PlaceholderResolverFactory {
private final PlaceholderResolver placeholderResolver;
private SingleInstancePlaceholderResolverFactory(
PlaceholderResolver placeholderResolver) {
private SingleInstancePlaceholderResolverFactory(PlaceholderResolver placeholderResolver) {
this.placeholderResolver = placeholderResolver;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -61,8 +61,7 @@ public abstract class TemplatedSnippet implements Snippet {
* @param templateName the name of the template
* @param attributes the additional attributes
*/
protected TemplatedSnippet(String snippetName, String templateName,
Map<String, Object> attributes) {
protected TemplatedSnippet(String snippetName, String templateName, Map<String, Object> attributes) {
this.templateName = templateName;
this.snippetName = snippetName;
if (attributes != null) {
@@ -72,18 +71,15 @@ public abstract class TemplatedSnippet implements Snippet {
@Override
public void document(Operation operation) throws IOException {
RestDocumentationContext context = (RestDocumentationContext) operation
.getAttributes().get(RestDocumentationContext.class.getName());
WriterResolver writerResolver = (WriterResolver) operation.getAttributes()
.get(WriterResolver.class.getName());
try (Writer writer = writerResolver.resolve(operation.getName(), this.snippetName,
context)) {
RestDocumentationContext context = (RestDocumentationContext) operation.getAttributes()
.get(RestDocumentationContext.class.getName());
WriterResolver writerResolver = (WriterResolver) operation.getAttributes().get(WriterResolver.class.getName());
try (Writer writer = writerResolver.resolve(operation.getName(), this.snippetName, context)) {
Map<String, Object> model = createModel(operation);
model.putAll(this.attributes);
TemplateEngine templateEngine = (TemplateEngine) operation.getAttributes()
.get(TemplateEngine.class.getName());
writer.append(
templateEngine.compileTemplate(this.templateName).render(model));
writer.append(templateEngine.compileTemplate(this.templateName).render(model));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -38,8 +38,8 @@ public interface WriterResolver {
* @return the writer
* @throws IOException if a writer cannot be resolved
*/
Writer resolve(String operationName, String snippetName,
RestDocumentationContext restDocumentationContext) throws IOException;
Writer resolve(String operationName, String snippetName, RestDocumentationContext restDocumentationContext)
throws IOException;
/**
* Configures the encoding that should be used by any writers produced by this

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -75,24 +75,20 @@ public class StandardTemplateResourceResolver implements TemplateResourceResolve
if (defaultTemplate.exists()) {
return defaultTemplate;
}
throw new IllegalStateException(
"Template named '" + name + "' could not be resolved");
throw new IllegalStateException("Template named '" + name + "' could not be resolved");
}
private Resource getFormatSpecificCustomTemplate(String name) {
return new ClassPathResource(
String.format("org/springframework/restdocs/templates/%s/%s.snippet",
this.templateFormat.getId(), name));
return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s/%s.snippet",
this.templateFormat.getId(), name));
}
private Resource getCustomTemplate(String name) {
return new ClassPathResource(
String.format("org/springframework/restdocs/templates/%s.snippet", name));
return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s.snippet", name));
}
private Resource getDefaultTemplate(String name) {
return new ClassPathResource(String.format(
"org/springframework/restdocs/templates/%s/default-%s.snippet",
return new ClassPathResource(String.format("org/springframework/restdocs/templates/%s/default-%s.snippet",
this.templateFormat.getId(), name));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -50,8 +50,7 @@ public class MustacheTemplate implements Template {
* @param delegate the delegate to adapt
* @param context the context
*/
public MustacheTemplate(org.springframework.restdocs.mustache.Template delegate,
Map<String, Object> context) {
public MustacheTemplate(org.springframework.restdocs.mustache.Template delegate, Map<String, Object> context) {
this.delegate = delegate;
this.context = context;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2019 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.
@@ -60,8 +60,7 @@ public class MustacheTemplateEngine implements TemplateEngine {
* @param templateResourceResolver the resolver to use
* @param compiler the compiler to use
*/
public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver,
Compiler compiler) {
public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, Compiler compiler) {
this(templateResourceResolver, compiler, Collections.<String, Object>emptyMap());
}
@@ -76,8 +75,8 @@ public class MustacheTemplateEngine implements TemplateEngine {
* @see MustacheTemplate#MustacheTemplate(org.springframework.restdocs.mustache.Template,
* Map)
*/
public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver,
Compiler compiler, Map<String, Object> context) {
public MustacheTemplateEngine(TemplateResourceResolver templateResourceResolver, Compiler compiler,
Map<String, Object> context) {
this.templateResourceResolver = templateResourceResolver;
this.compiler = compiler;
this.context = context;
@@ -85,11 +84,8 @@ public class MustacheTemplateEngine implements TemplateEngine {
@Override
public Template compileTemplate(String name) throws IOException {
Resource templateResource = this.templateResourceResolver
.resolveTemplateResource(name);
return new MustacheTemplate(
this.compiler.compile(
new InputStreamReader(templateResource.getInputStream())),
Resource templateResource = this.templateResourceResolver.resolveTemplateResource(name);
return new MustacheTemplate(this.compiler.compile(new InputStreamReader(templateResource.getInputStream())),
this.context);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -55,8 +55,7 @@ public abstract class AbstractSnippetTests {
@Parameters(name = "{0}")
public static List<Object[]> parameters() {
return Arrays.asList(
new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() },
return Arrays.asList(new Object[] { "Asciidoctor", TemplateFormats.asciidoctor() },
new Object[] { "Markdown", TemplateFormats.markdown() });
}
@@ -79,8 +78,7 @@ public abstract class AbstractSnippetTests {
}
public TableCondition<?> tableWithTitleAndHeader(String title, String... headers) {
return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title,
headers);
return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title, headers);
}
public HttpRequestCondition httpRequest(RequestMethod method, String uri) {
@@ -92,8 +90,8 @@ public abstract class AbstractSnippetTests {
}
protected FileSystemResource snippetResource(String name) {
return new FileSystemResource("src/test/resources/custom-snippet-templates/"
+ this.templateFormat.getId() + "/" + name + ".snippet");
return new FileSystemResource(
"src/test/resources/custom-snippet-templates/" + this.templateFormat.getId() + "/" + name + ".snippet");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -54,53 +54,43 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class RestDocumentationGeneratorTests {
@SuppressWarnings("unchecked")
private final RequestConverter<Object> requestConverter = mock(
RequestConverter.class);
private final RequestConverter<Object> requestConverter = mock(RequestConverter.class);
@SuppressWarnings("unchecked")
private final ResponseConverter<Object> responseConverter = mock(
ResponseConverter.class);
private final ResponseConverter<Object> responseConverter = mock(ResponseConverter.class);
private final Object request = new Object();
private final Object response = new Object();
private final OperationRequest operationRequest = new OperationRequestFactory()
.create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(),
null, null);
.create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(), null, null);
private final OperationResponse operationResponse = new OperationResponseFactory()
.create(null, null, null);
private final OperationResponse operationResponse = new OperationResponseFactory().create(null, null, null);
private final Snippet snippet = mock(Snippet.class);
@Test
public void basicHandling() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, this.snippet).handle(this.request, this.response,
configuration);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, configuration);
}
@Test
public void defaultSnippetsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
HashMap<String, Object> configuration = new HashMap<>();
Snippet defaultSnippet1 = mock(Snippet.class);
Snippet defaultSnippet2 = mock(Snippet.class);
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS,
Arrays.asList(defaultSnippet1, defaultSnippet2));
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter, this.snippet).handle(this.request, this.response,
configuration);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter, this.snippet)
.handle(this.request, this.response, configuration);
InOrder inOrder = Mockito.inOrder(defaultSnippet1, defaultSnippet2, this.snippet);
verifySnippetInvocation(inOrder, defaultSnippet1, configuration);
verifySnippetInvocation(inOrder, defaultSnippet2, configuration);
@@ -110,20 +100,17 @@ public class RestDocumentationGeneratorTests {
@Test
@Deprecated
public void additionalSnippetsAreCalled() throws IOException {
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
Snippet additionalSnippet1 = mock(Snippet.class);
Snippet additionalSnippet2 = mock(Snippet.class);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>(
"id", this.requestConverter, this.responseConverter, this.snippet);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>("id",
this.requestConverter, this.responseConverter, this.snippet);
generator.addSnippets(additionalSnippet1, additionalSnippet2);
HashMap<String, Object> configuration = new HashMap<>();
generator.handle(this.request, this.response, configuration);
generator.handle(this.request, this.response, configuration);
InOrder inOrder = Mockito.inOrder(this.snippet, additionalSnippet1,
additionalSnippet2);
InOrder inOrder = Mockito.inOrder(this.snippet, additionalSnippet1, additionalSnippet2);
verifySnippetInvocation(inOrder, this.snippet, configuration);
verifySnippetInvocation(inOrder, additionalSnippet1, configuration);
verifySnippetInvocation(inOrder, additionalSnippet2, configuration);
@@ -133,33 +120,25 @@ public class RestDocumentationGeneratorTests {
@Test
public void newGeneratorOnlyCallsItsSnippets() throws IOException {
OperationRequestPreprocessor requestPreprocessor = mock(
OperationRequestPreprocessor.class);
OperationResponsePreprocessor responsePreprocessor = mock(
OperationResponsePreprocessor.class);
given(this.requestConverter.convert(this.request))
.willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response))
.willReturn(this.operationResponse);
given(requestPreprocessor.preprocess(this.operationRequest))
.willReturn(this.operationRequest);
given(responsePreprocessor.preprocess(this.operationResponse))
.willReturn(this.operationResponse);
OperationRequestPreprocessor requestPreprocessor = mock(OperationRequestPreprocessor.class);
OperationResponsePreprocessor responsePreprocessor = mock(OperationResponsePreprocessor.class);
given(this.requestConverter.convert(this.request)).willReturn(this.operationRequest);
given(this.responseConverter.convert(this.response)).willReturn(this.operationResponse);
given(requestPreprocessor.preprocess(this.operationRequest)).willReturn(this.operationRequest);
given(responsePreprocessor.preprocess(this.operationResponse)).willReturn(this.operationResponse);
Snippet additionalSnippet1 = mock(Snippet.class);
Snippet additionalSnippet2 = mock(Snippet.class);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>(
"id", this.requestConverter, this.responseConverter, requestPreprocessor,
responsePreprocessor, this.snippet);
RestDocumentationGenerator<Object, Object> generator = new RestDocumentationGenerator<>("id",
this.requestConverter, this.responseConverter, requestPreprocessor, responsePreprocessor, this.snippet);
HashMap<String, Object> configuration = new HashMap<>();
generator.withSnippets(additionalSnippet1, additionalSnippet2)
.handle(this.request, this.response, configuration);
generator.withSnippets(additionalSnippet1, additionalSnippet2).handle(this.request, this.response,
configuration);
verifyNoMoreInteractions(this.snippet);
verifySnippetInvocation(additionalSnippet1, configuration);
verifySnippetInvocation(additionalSnippet2, configuration);
}
private void verifySnippetInvocation(Snippet snippet, Map<String, Object> attributes)
throws IOException {
private void verifySnippetInvocation(Snippet snippet, Map<String, Object> attributes) throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
verify(snippet).document(operation.capture());
assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest());
@@ -167,8 +146,8 @@ public class RestDocumentationGeneratorTests {
assertThat(attributes).isEqualTo(operation.getValue().getAttributes());
}
private void verifySnippetInvocation(InOrder inOrder, Snippet snippet,
Map<String, Object> attributes) throws IOException {
private void verifySnippetInvocation(InOrder inOrder, Snippet snippet, Map<String, Object> attributes)
throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
inOrder.verify(snippet).document(operation.capture());
assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -35,8 +35,7 @@ public class ConcatenatingCommandFormatterTests {
@Test
public void formattingAnEmptyListProducesAnEmptyString() {
assertThat(this.singleLineFormat.format(Collections.<String>emptyList()))
.isEqualTo("");
assertThat(this.singleLineFormat.format(Collections.<String>emptyList())).isEqualTo("");
}
@Test
@@ -46,8 +45,7 @@ public class ConcatenatingCommandFormatterTests {
@Test
public void formattingASingleElement() {
assertThat(this.singleLineFormat.format(Collections.singletonList("alpha")))
.isEqualTo(" alpha");
assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))).isEqualTo(" alpha");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -53,323 +53,277 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests {
public void getRequest() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"));
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"));
}
@Test
public void getRequestWithParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET"));
}
@Test
public void nonGetRequest() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST"));
}
@Test
public void requestWithContent() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value")
.param("param", "value").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
.document(this.operationBuilder.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X GET"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
}
@Test
public void getRequestWithDisjointQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param' -i -X GET"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X GET"));
}
@Test
public void postRequestWithQueryString() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param=value' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param=value' -i -X POST"));
}
@Test
public void postRequestWithQueryStringWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?param' -i -X POST"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?param' -i -X POST"));
}
@Test
public void postRequestWithOneParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'"));
}
@Test
public void postRequestWithOneParameterWithNoValue() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='"));
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='"));
}
@Test
public void postRequestWithMultipleParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST")
.param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST"
+ " -d 'k1=v1&k1=v1-bis&k2=v2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST" + " -d 'k1=v1&k1=v1-bis&k2=v2'"));
}
@Test
public void postRequestWithUrlEncodedParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'"));
}
@Test
public void postRequestWithDisjointQueryStringAndParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST "
+ "-H 'Content-Type: application/x-www-form-urlencoded' "
+ "-d 'a=alpha&b=bravo'"));
.request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST "
+ "-H 'Content-Type: application/x-www-form-urlencoded' " + "-d 'a=alpha&b=bravo'"));
}
@Test
public void putRequestWithOneParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'"));
}
@Test
public void putRequestWithMultipleParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1")
.param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT"
+ " -d 'k1=v1&k1=v1-bis&k2=v2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT" + " -d 'k1=v1&k1=v1-bis&k2=v2'"));
}
@Test
public void putRequestWithUrlEncodedParameter() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'"));
new CurlRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'"));
}
@Test
public void requestWithHeaders() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"
+ " -H 'Content-Type: application/json' -H 'a: alpha'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo' -i -X GET" + " -H 'Content-Type: application/json' -H 'a: alpha'"));
}
@Test
public void requestWithHeadersMultiline() throws IOException {
new CurlRequestSnippet(CliDocumentation.multiLineFormat())
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n"
+ " -H 'Content-Type: application/json' \\%n"
+ " -H 'a: alpha'")));
new CurlRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder
.request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n"
+ " -H 'Content-Type: application/json' \\%n" + " -H 'a: alpha'")));
}
@Test
public void requestWithCookies() throws IOException {
new CurlRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.curlRequest()).is(
codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET"
+ " --cookie 'name1=value1;name2=value2'"));
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -X GET" + " --cookie 'name1=value1;name2=value2'"));
}
@Test
public void multipartPostWithNoSubmittedFileName() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'metadata={\"description\": \"foo\"}'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'metadata={\"description\": \"foo\"}'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png;type=image/png'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png;type=image/png'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPost() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").build());
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'Content-Type: multipart/form-data' -F " + "'image=@documents/images/example.png'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").and()
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/upload")
.method("POST").header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H "
+ "'Content-Type: multipart/form-data' -F "
+ "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' "
+ "-F 'b=banana'";
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + "-F 'b=banana'";
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
.build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET"));
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET"));
}
@Test
public void customAttributes() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent(
"$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'"
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.curlRequest())
.is(codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'"
+ " -H 'Content-Type: application/json' -H 'a: alpha'"));
}
@Test
public void postWithContentAndParameters() throws IOException {
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").method("POST")
.param("b", "bravo").content("Some content").build());
new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.param("a", "alpha").method("POST").param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash")
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i "
+ "-X POST -d 'Some content'"));
.withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + "-X POST -d 'Some content'"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -60,315 +60,274 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests {
@Test
public void getRequestWithParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha'"));
}
@Test
public void nonGetRequest() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'"));
}
@Test
public void requestWithContent() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ echo 'content' | http GET 'http://localhost/foo'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").content("content").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'content' | http GET 'http://localhost/foo'"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value")
.param("param", "value").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
.document(this.operationBuilder.request("http://localhost/foo?param=value").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param=value").param("param", "value").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param=value'"));
}
@Test
public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void getRequestWithDisjointQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'"));
}
@Test
public void postRequestWithQueryString() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?param=value'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param=value").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param=value'"));
}
@Test
public void postRequestWithQueryStringWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?param'"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?param").method("POST").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?param'"));
}
@Test
public void postRequestWithOneParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'"));
}
@Test
public void postRequestWithOneParameterWithNoValue() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1='"));
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("k1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1='"));
}
@Test
public void postRequestWithMultipleParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST")
.param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo'"
+ " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "v1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
}
@Test
public void postRequestWithUrlEncodedParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'"));
}
@Test
public void postRequestWithDisjointQueryStringAndParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
.request("http://localhost/foo?a=alpha").method("POST").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(
"$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' "
+ "'Content-Type:application/x-www-form-urlencoded'"));
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'"));
}
@Test
public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo?a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'"));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' "
+ "'Content-Type:application/x-www-form-urlencoded'"));
}
@Test
public void putRequestWithOneParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "v1").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'"));
}
@Test
public void putRequestWithMultipleParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("PUT").param("k1", "v1")
.param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(
codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo'"
+ " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "v1").param("k1", "v1-bis").param("k2", "v2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo'" + " 'k1=v1' 'k1=v1-bis' 'k2=v2'"));
}
@Test
public void putRequestWithUrlEncodedParameter() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'"));
new HttpieRequestSnippet(this.commandFormatter).document(
this.operationBuilder.request("http://localhost/foo").method("PUT").param("k1", "a&b").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'"));
}
@Test
public void requestWithHeaders() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'"
+ " 'Content-Type:application/json' 'a:alpha'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo'" + " 'Content-Type:application/json' 'a:alpha'"));
}
@Test
public void requestWithHeadersMultiline() throws IOException {
new HttpieRequestSnippet(CliDocumentation.multiLineFormat())
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent(String.format("$ http GET 'http://localhost/foo' \\%n"
+ " 'Content-Type:application/json' \\%n 'a:alpha'")));
new HttpieRequestSnippet(CliDocumentation.multiLineFormat()).document(this.operationBuilder
.request("http://localhost/foo").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(String.format(
"$ http GET 'http://localhost/foo' \\%n" + " 'Content-Type:application/json' \\%n 'a:alpha'")));
}
@Test
public void requestWithCookies() throws IOException {
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'"
+ " 'Cookie:name1=value1' 'Cookie:name2=value2'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo'" + " 'Cookie:name1=value1' 'Cookie:name2=value2'"));
}
@Test
public void multipartPostWithNoSubmittedFileName() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("metadata", "{\"description\": \"foo\"}".getBytes()).build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'metadata'@<(echo '{\"description\": \"foo\"}')";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.submittedFileName("documents/images/example.png").build());
// httpie does not yet support manually set content type by part
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPost() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0])
.submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
new HttpieRequestSnippet(this.commandFormatter)
.document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", new byte[0]).submittedFileName("documents/images/example.png").and()
.param("a", "apple", "avocado").param("b", "banana").build());
String expectedContent = "$ http --form POST 'http://localhost/upload'"
+ " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'"
+ " 'b=banana'";
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent(expectedContent));
+ " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + " 'b=banana'";
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash").withContent(expectedContent));
}
@Test
public void basicAuthCredentialsAreSuppliedUsingAuthOption() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes()))
.build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'"));
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'"));
}
@Test
public void customAttributes() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo")
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'"
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'"
+ " 'Content-Type:application/json' 'a:alpha'"));
}
@Test
public void postWithContentAndParameters() throws IOException {
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("a", "alpha")
.param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.httpieRequest())
.is(codeBlock("bash").withContent("$ echo 'Some content' | http POST "
+ "'http://localhost/foo?a=alpha&b=bravo'"));
new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("a", "alpha").param("b", "bravo").content("Some content").build());
assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash")
.withContent("$ echo 'Some content' | http POST " + "'http://localhost/foo?a=alpha&b=bravo'"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -59,62 +59,48 @@ public class RestDocumentationConfigurerTests {
Map<String, Object> configuration = new HashMap<>();
this.configurer.apply(configuration, createContext());
assertThat(configuration).containsKey(TemplateEngine.class.getName());
assertThat(configuration.get(TemplateEngine.class.getName()))
.isInstanceOf(MustacheTemplateEngine.class);
assertThat(configuration.get(TemplateEngine.class.getName())).isInstanceOf(MustacheTemplateEngine.class);
assertThat(configuration).containsKey(WriterResolver.class.getName());
assertThat(configuration.get(WriterResolver.class.getName()))
.isInstanceOf(StandardWriterResolver.class);
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
assertThat(configuration.get(WriterResolver.class.getName())).isInstanceOf(StandardWriterResolver.class);
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(
CurlRequestSnippet.class, HttpieRequestSnippet.class,
HttpRequestSnippet.class, HttpResponseSnippet.class,
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class,
HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class,
RequestBodySnippet.class, ResponseBodySnippet.class);
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getEncoding()).isEqualTo("UTF-8");
assertThat(snippetConfiguration.getTemplateFormat().getId())
.isEqualTo(TemplateFormats.asciidoctor().getId());
assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.asciidoctor().getId());
}
@Test
public void customTemplateEngine() {
Map<String, Object> configuration = new HashMap<>();
TemplateEngine templateEngine = mock(TemplateEngine.class);
this.configurer.templateEngine(templateEngine).apply(configuration,
createContext());
assertThat(configuration).containsEntry(TemplateEngine.class.getName(),
templateEngine);
this.configurer.templateEngine(templateEngine).apply(configuration, createContext());
assertThat(configuration).containsEntry(TemplateEngine.class.getName(), templateEngine);
}
@Test
public void customWriterResolver() {
Map<String, Object> configuration = new HashMap<>();
WriterResolver writerResolver = mock(WriterResolver.class);
this.configurer.writerResolver(writerResolver).apply(configuration,
createContext());
assertThat(configuration).containsEntry(WriterResolver.class.getName(),
writerResolver);
this.configurer.writerResolver(writerResolver).apply(configuration, createContext());
assertThat(configuration).containsEntry(WriterResolver.class.getName(), writerResolver);
}
@Test
public void customDefaultSnippets() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withDefaults(CliDocumentation.curlRequest())
.apply(configuration, createContext());
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
this.configurer.snippets().withDefaults(CliDocumentation.curlRequest()).apply(configuration, createContext());
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
@SuppressWarnings("unchecked")
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
@@ -127,29 +113,23 @@ public class RestDocumentationConfigurerTests {
public void additionalDefaultSnippets() {
Map<String, Object> configuration = new HashMap<>();
Snippet snippet = mock(Snippet.class);
this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration,
createContext());
assertThat(configuration)
.containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration, createContext());
assertThat(configuration).containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(configuration.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS))
.isInstanceOf(List.class);
List<Snippet> defaultSnippets = (List<Snippet>) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS);
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(
CurlRequestSnippet.class, HttpieRequestSnippet.class,
HttpRequestSnippet.class, HttpResponseSnippet.class,
assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder(CurlRequestSnippet.class,
HttpieRequestSnippet.class, HttpRequestSnippet.class, HttpResponseSnippet.class,
RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass());
}
@Test
public void customSnippetEncoding() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration,
createContext());
this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, createContext());
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getEncoding()).isEqualTo("ISO 8859-1");
@@ -158,15 +138,12 @@ public class RestDocumentationConfigurerTests {
@Test
public void customTemplateFormat() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown())
.apply(configuration, createContext());
this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()).apply(configuration, createContext());
assertThat(configuration).containsKey(SnippetConfiguration.class.getName());
assertThat(configuration.get(SnippetConfiguration.class.getName()))
.isInstanceOf(SnippetConfiguration.class);
assertThat(configuration.get(SnippetConfiguration.class.getName())).isInstanceOf(SnippetConfiguration.class);
SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration
.get(SnippetConfiguration.class.getName());
assertThat(snippetConfiguration.getTemplateFormat().getId())
.isEqualTo(TemplateFormats.markdown().getId());
assertThat(snippetConfiguration.getTemplateFormat().getId()).isEqualTo(TemplateFormats.markdown().getId());
}
@SuppressWarnings("unchecked")
@@ -174,14 +151,12 @@ public class RestDocumentationConfigurerTests {
public void asciidoctorTableCellContentLambaIsInstalledWhenUsingAsciidoctorTemplateFormat() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.apply(configuration, createContext());
TemplateEngine templateEngine = (TemplateEngine) configuration
.get(TemplateEngine.class.getName());
TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName());
MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine;
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils
.getField(mustacheTemplateEngine, "context");
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils.getField(mustacheTemplateEngine,
"context");
assertThat(templateContext).containsKey("tableCellContent");
assertThat(templateContext.get("tableCellContent"))
.isInstanceOf(AsciidoctorTableCellContentLambda.class);
assertThat(templateContext.get("tableCellContent")).isInstanceOf(AsciidoctorTableCellContentLambda.class);
}
@SuppressWarnings("unchecked")
@@ -190,27 +165,24 @@ public class RestDocumentationConfigurerTests {
Map<String, Object> configuration = new HashMap<>();
this.configurer.snippetConfigurer.withTemplateFormat(TemplateFormats.markdown());
this.configurer.apply(configuration, createContext());
TemplateEngine templateEngine = (TemplateEngine) configuration
.get(TemplateEngine.class.getName());
TemplateEngine templateEngine = (TemplateEngine) configuration.get(TemplateEngine.class.getName());
MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine;
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils
.getField(mustacheTemplateEngine, "context");
Map<String, Object> templateContext = (Map<String, Object>) ReflectionTestUtils.getField(mustacheTemplateEngine,
"context");
assertThat(templateContext.size()).isEqualTo(0);
}
private RestDocumentationContext createContext() {
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(
"build");
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build");
manualRestDocumentation.beforeTest(null, null);
RestDocumentationContext context = manualRestDocumentation.beforeOperation();
return context;
}
private static final class TestRestDocumentationConfigurer extends
RestDocumentationConfigurer<TestSnippetConfigurer, TestRestDocumentationConfigurer> {
private static final class TestRestDocumentationConfigurer
extends RestDocumentationConfigurer<TestSnippetConfigurer, TestRestDocumentationConfigurer> {
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(
this);
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(this);
@Override
public TestSnippetConfigurer snippets() {
@@ -219,8 +191,8 @@ public class RestDocumentationConfigurerTests {
}
private static final class TestSnippetConfigurer extends
SnippetConfigurer<TestRestDocumentationConfigurer, TestSnippetConfigurer> {
private static final class TestSnippetConfigurer
extends SnippetConfigurer<TestRestDocumentationConfigurer, TestSnippetConfigurer> {
private TestSnippetConfigurer(TestRestDocumentationConfigurer parent) {
super(parent);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2019 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.
@@ -37,32 +37,25 @@ public class ConstraintDescriptionsTests {
private final ConstraintDescriptionResolver constraintDescriptionResolver = mock(
ConstraintDescriptionResolver.class);
private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(
Constrained.class, this.constraintResolver,
this.constraintDescriptionResolver);
private final ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(Constrained.class,
this.constraintResolver, this.constraintDescriptionResolver);
@Test
public void descriptionsForConstraints() {
Constraint constraint1 = new Constraint("constraint1",
Collections.<String, Object>emptyMap());
Constraint constraint2 = new Constraint("constraint2",
Collections.<String, Object>emptyMap());
Constraint constraint1 = new Constraint("constraint1", Collections.<String, Object>emptyMap());
Constraint constraint2 = new Constraint("constraint2", Collections.<String, Object>emptyMap());
given(this.constraintResolver.resolveForProperty("foo", Constrained.class))
.willReturn(Arrays.asList(constraint1, constraint2));
given(this.constraintDescriptionResolver.resolveDescription(constraint1))
.willReturn("Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint2))
.willReturn("Alpha");
assertThat(this.constraintDescriptions.descriptionsForProperty("foo"))
.containsExactly("Alpha", "Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint1)).willReturn("Bravo");
given(this.constraintDescriptionResolver.resolveDescription(constraint2)).willReturn("Alpha");
assertThat(this.constraintDescriptions.descriptionsForProperty("foo")).containsExactly("Alpha", "Bravo");
}
@Test
public void emptyListOfDescriptionsWhenThereAreNoConstraints() {
given(this.constraintResolver.resolveForProperty("foo", Constrained.class))
.willReturn(Collections.<Constraint>emptyList());
assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size())
.isEqualTo(0);
assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()).isEqualTo(0);
}
private static class Constrained {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -69,8 +69,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageAssertFalse() {
assertThat(constraintDescriptionForField("assertFalse"))
.isEqualTo("Must be false");
assertThat(constraintDescriptionForField("assertFalse")).isEqualTo("Must be false");
}
@Test
@@ -80,14 +79,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageDecimalMax() {
assertThat(constraintDescriptionForField("decimalMax"))
.isEqualTo("Must be at most 9.875");
assertThat(constraintDescriptionForField("decimalMax")).isEqualTo("Must be at most 9.875");
}
@Test
public void defaultMessageDecimalMin() {
assertThat(constraintDescriptionForField("decimalMin"))
.isEqualTo("Must be at least 1.5");
assertThat(constraintDescriptionForField("decimalMin")).isEqualTo("Must be at least 1.5");
}
@Test
@@ -98,8 +95,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageFuture() {
assertThat(constraintDescriptionForField("future"))
.isEqualTo("Must be in the future");
assertThat(constraintDescriptionForField("future")).isEqualTo("Must be in the future");
}
@Test
@@ -114,8 +110,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageNotNull() {
assertThat(constraintDescriptionForField("notNull"))
.isEqualTo("Must not be null");
assertThat(constraintDescriptionForField("notNull")).isEqualTo("Must not be null");
}
@Test
@@ -125,8 +120,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessagePast() {
assertThat(constraintDescriptionForField("past"))
.isEqualTo("Must be in the past");
assertThat(constraintDescriptionForField("past")).isEqualTo("Must be in the past");
}
@Test
@@ -137,8 +131,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageSize() {
assertThat(constraintDescriptionForField("size"))
.isEqualTo("Size must be between 2 and 10 inclusive");
assertThat(constraintDescriptionForField("size")).isEqualTo("Size must be between 2 and 10 inclusive");
}
@Test
@@ -149,20 +142,17 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageEan() {
assertThat(constraintDescriptionForField("ean"))
.isEqualTo("Must be a well-formed EAN13 number");
assertThat(constraintDescriptionForField("ean")).isEqualTo("Must be a well-formed EAN13 number");
}
@Test
public void defaultMessageEmail() {
assertThat(constraintDescriptionForField("email"))
.isEqualTo("Must be a well-formed email address");
assertThat(constraintDescriptionForField("email")).isEqualTo("Must be a well-formed email address");
}
@Test
public void defaultMessageLength() {
assertThat(constraintDescriptionForField("length"))
.isEqualTo("Length must be between 2 and 10 inclusive");
assertThat(constraintDescriptionForField("length")).isEqualTo("Length must be between 2 and 10 inclusive");
}
@Test
@@ -173,44 +163,37 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageMod10Check() {
assertThat(constraintDescriptionForField("mod10Check"))
.isEqualTo("Must pass the Mod10 checksum algorithm");
assertThat(constraintDescriptionForField("mod10Check")).isEqualTo("Must pass the Mod10 checksum algorithm");
}
@Test
public void defaultMessageMod11Check() {
assertThat(constraintDescriptionForField("mod11Check"))
.isEqualTo("Must pass the Mod11 checksum algorithm");
assertThat(constraintDescriptionForField("mod11Check")).isEqualTo("Must pass the Mod11 checksum algorithm");
}
@Test
public void defaultMessageNotBlank() {
assertThat(constraintDescriptionForField("notBlank"))
.isEqualTo("Must not be blank");
assertThat(constraintDescriptionForField("notBlank")).isEqualTo("Must not be blank");
}
@Test
public void defaultMessageNotEmpty() {
assertThat(constraintDescriptionForField("notEmpty"))
.isEqualTo("Must not be empty");
assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty");
}
@Test
public void defaultMessageRange() {
assertThat(constraintDescriptionForField("range"))
.isEqualTo("Must be at least 10 and at most 100");
assertThat(constraintDescriptionForField("range")).isEqualTo("Must be at least 10 and at most 100");
}
@Test
public void defaultMessageSafeHtml() {
assertThat(constraintDescriptionForField("safeHtml"))
.isEqualTo("Must be safe HTML");
assertThat(constraintDescriptionForField("safeHtml")).isEqualTo("Must be safe HTML");
}
@Test
public void defaultMessageUrl() {
assertThat(constraintDescriptionForField("url"))
.isEqualTo("Must be a well-formed URL");
assertThat(constraintDescriptionForField("url")).isEqualTo("Must be a well-formed URL");
}
@Test
@@ -219,8 +202,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Override
public URL getResource(String name) {
if (name.startsWith(
"org/springframework/restdocs/constraints/ConstraintDescriptions")) {
if (name.startsWith("org/springframework/restdocs/constraints/ConstraintDescriptions")) {
return super.getResource(
"org/springframework/restdocs/constraints/TestConstraintDescriptions.properties");
}
@@ -230,9 +212,8 @@ public class ResourceBundleConstraintDescriptionResolverTests {
});
try {
String description = new ResourceBundleConstraintDescriptionResolver()
.resolveDescription(new Constraint(NotNull.class.getName(),
Collections.<String, Object>emptyMap()));
String description = new ResourceBundleConstraintDescriptionResolver().resolveDescription(
new Constraint(NotNull.class.getName(), Collections.<String, Object>emptyMap()));
assertThat(description).isEqualTo("Should not be null");
}
@@ -247,14 +228,12 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Override
protected Object[][] getContents() {
return new String[][] {
{ NotNull.class.getName() + ".description", "Not null" } };
return new String[][] { { NotNull.class.getName() + ".description", "Not null" } };
}
};
String description = new ResourceBundleConstraintDescriptionResolver(bundle)
.resolveDescription(new Constraint(NotNull.class.getName(),
Collections.<String, Object>emptyMap()));
.resolveDescription(new Constraint(NotNull.class.getName(), Collections.<String, Object>emptyMap()));
assertThat(description).isEqualTo("Not null");
}
@@ -263,10 +242,9 @@ public class ResourceBundleConstraintDescriptionResolverTests {
}
private Constraint getConstraintFromField(String name) {
Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name)
.getAnnotations();
Assert.isTrue(annotations.length == 1, "The field '" + name + "' must have "
+ "exactly one @Constrained annotation");
Annotation[] annotations = ReflectionUtils.findField(Constrained.class, name).getAnnotations();
Assert.isTrue(annotations.length == 1,
"The field '" + name + "' must have " + "exactly one @Constrained annotation");
return new Constraint(annotations[0].annotationType().getName(),
AnnotationUtils.getAnnotationAttributes(annotations[0]));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -51,33 +51,28 @@ public class ValidatorConstraintResolverTests {
@Test
public void singleFieldConstraint() {
List<Constraint> constraints = this.resolver.resolveForProperty("single",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("single", ConstrainedFields.class);
assertThat(constraints).hasSize(1);
assertThat(constraints.get(0).getName()).isEqualTo(NotNull.class.getName());
}
@Test
public void multipleFieldConstraints() {
List<Constraint> constraints = this.resolver.resolveForProperty("multiple",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class);
assertThat(constraints).hasSize(2);
assertThat(constraints.get(0)).is(constraint(NotNull.class));
assertThat(constraints.get(1))
.is(constraint(Size.class).config("min", 8).config("max", 16));
assertThat(constraints.get(1)).is(constraint(Size.class).config("min", 8).config("max", 16));
}
@Test
public void noFieldConstraints() {
List<Constraint> constraints = this.resolver.resolveForProperty("none",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("none", ConstrainedFields.class);
assertThat(constraints).hasSize(0);
}
@Test
public void compositeConstraint() {
List<Constraint> constraints = this.resolver.resolveForProperty("composite",
ConstrainedFields.class);
List<Constraint> constraints = this.resolver.resolveForProperty("composite", ConstrainedFields.class);
assertThat(constraints).hasSize(1);
}
@@ -126,11 +121,10 @@ public class ValidatorConstraintResolverTests {
private ConstraintCondition(Class<?> annotation) {
this.annotation = annotation;
as(new TextDescription("Constraint named %s with configuration %s",
this.annotation, this.configuration));
as(new TextDescription("Constraint named %s with configuration %s", this.annotation, this.configuration));
}
public ConstraintCondition config(String key, Object value) {
private ConstraintCondition config(String key, Object value) {
this.configuration.put(key, value);
return this;
}
@@ -141,8 +135,7 @@ public class ValidatorConstraintResolverTests {
return false;
}
for (Entry<String, Object> entry : this.configuration.entrySet()) {
if (!constraint.getConfiguration().get(entry.getKey())
.equals(entry.getValue())) {
if (!constraint.getConfiguration().get(entry.getKey()).equals(entry.getValue())) {
return false;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit
public class RequestHeadersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,24 +48,19 @@ public class RequestHeadersSnippetFailureTests {
@Test
public void missingRequestHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Headers with the following names were not found"
+ " in the request: [Accept]"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Accept").description("one"))).document(
this.operationBuilder.request("http://localhost").build());
this.thrown.expectMessage(
equalTo("Headers with the following names were not found" + " in the request: [Accept]"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost").build());
}
@Test
public void undocumentedRequestHeaderAndMissingRequestHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(endsWith("Headers with the following names were not found"
+ " in the request: [Accept]"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").build());
this.thrown.expectMessage(
endsWith("Headers with the following names were not found" + " in the request: [Accept]"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Accept").description("one")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -49,43 +49,32 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
@Test
public void requestWithHeaders() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"),
headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"),
headerWithName("Cache-Control").description("five"),
headerWithName("Connection").description("six"))).document(
this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five")
.row("`Connection`", "six"));
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"),
headerWithName("Cache-Control").description("five"), headerWithName("Connection").description("six")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six"));
}
@Test
public void caseInsensitiveRequestHeaders() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("/")
.header("X-test", "test").build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("/").header("X-test", "test").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@Test
public void undocumentedRequestHeader() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@@ -95,16 +84,11 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-headers"))
.willReturn(snippetResource("request-headers-with-title"));
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.header("X-Test", "test").build());
new RequestHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").header("X-Test", "test").build());
assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title");
}
@@ -113,61 +97,41 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("request-headers"))
.willReturn(snippetResource("request-headers-with-extra-column"));
new RequestHeadersSnippet(Arrays.asList(
headerWithName("X-Test").description("one")
.attributes(key("foo").value("alpha")),
headerWithName("Accept-Encoding").description("two")
.attributes(key("foo").value("bravo")),
headerWithName("Accept").description("three")
.attributes(key("foo").value("charlie"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.request("http://localhost")
.header("X-Test", "test")
.header("Accept-Encoding",
"gzip, deflate")
.header("Accept", "*/*").build());
new RequestHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")),
headerWithName("Accept-Encoding").description("two").attributes(key("foo").value("bravo")),
headerWithName("Accept").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost").header("X-Test", "test")
.header("Accept-Encoding", "gzip, deflate").header("Accept", "*/*").build());
assertThat(this.generatedSnippets.requestHeaders()).is(//
tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha")
.row("Accept-Encoding", "two", "bravo")
.row("Accept", "three", "charlie"));
tableWithHeader("Name", "Description", "Foo").row("X-Test", "one", "alpha")
.row("Accept-Encoding", "two", "bravo").row("Accept", "three", "charlie"));
}
@Test
public void additionalDescriptors() throws IOException {
HeaderDocumentation
.requestHeaders(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"),
headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"))
HeaderDocumentation.requestHeaders(headerWithName("X-Test").description("one"),
headerWithName("Accept").description("two"), headerWithName("Accept-Encoding").description("three"),
headerWithName("Accept-Language").description("four"))
.and(headerWithName("Cache-Control").description("five"),
headerWithName("Connection").description("six"))
.document(this.operationBuilder.request("http://localhost")
.header("X-Test", "test").header("Accept", "*/*")
.header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Cache-Control", "max-age=0")
.document(this.operationBuilder.request("http://localhost").header("X-Test", "test")
.header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "en-US,en;q=0.5").header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive").build());
assertThat(this.generatedSnippets.requestHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five")
.row("`Connection`", "six"));
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row("`X-Test`", "one").row("`Accept`", "two").row("`Accept-Encoding`", "three")
.row("`Accept-Language`", "four").row("`Cache-Control`", "five").row("`Connection`", "six"));
}
@Test
public void tableCellContentIsEscapedWhenNecessary() throws IOException {
new RequestHeadersSnippet(
Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.request("http://localhost")
.header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestHeaders()).is(
tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
new RequestHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.request("http://localhost").header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.requestHeaders()).is(tableWithHeader("Name", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -40,8 +40,7 @@ import static org.springframework.restdocs.headers.HeaderDocumentation.headerWit
public class ResponseHeadersSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -49,24 +48,19 @@ public class ResponseHeadersSnippetFailureTests {
@Test
public void missingResponseHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(equalTo("Headers with the following names were not found"
+ " in the response: [Content-Type]"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().build());
this.thrown.expectMessage(
equalTo("Headers with the following names were not found" + " in the response: [Content-Type]"));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().build());
}
@Test
public void undocumentedResponseHeaderAndMissingResponseHeader() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown
.expectMessage(endsWith("Headers with the following names were not found"
+ " in the response: [Content-Type]"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response()
.header("X-Test", "test").build());
this.thrown.expectMessage(
endsWith("Headers with the following names were not found" + " in the response: [Content-Type]"));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Content-Type").description("one")))
.document(this.operationBuilder.response().header("X-Test", "test").build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -49,39 +49,29 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
@Test
public void responseWithHeaders() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"),
headerWithName("Etag").description("three"),
headerWithName("Cache-Control").description("five"),
headerWithName("Vary").description("six"))).document(
this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0")
.header("Vary", "User-Agent").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"),
headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six")))
.document(this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Content-Type`", "two").row("`Etag`", "three")
.row("`Cache-Control`", "five").row("`Vary`", "six"));
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two")
.row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six"));
}
@Test
public void caseInsensitiveResponseHeaders() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.response()
.header("X-test", "test").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")))
.document(this.operationBuilder.response().header("X-test", "test").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@Test
public void undocumentedResponseHeader() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one"))).document(
this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "*/*").build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one"))).document(
this.operationBuilder.response().header("X-Test", "test").header("Content-Type", "*/*").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one"));
}
@@ -91,16 +81,11 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-headers"))
.willReturn(snippetResource("response-headers-with-title"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one")), attributes(
key("title").value("Custom title")))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.response().header("X-Test", "test")
.build());
new ResponseHeadersSnippet(Arrays.asList(headerWithName("X-Test").description("one")),
attributes(key("title").value("Custom title")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().header("X-Test", "test").build());
assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title");
}
@@ -109,57 +94,38 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("response-headers"))
.willReturn(snippetResource("response-headers-with-extra-column"));
new ResponseHeadersSnippet(Arrays.asList(
headerWithName("X-Test").description("one")
.attributes(key("foo").value("alpha")),
headerWithName("Content-Type").description("two")
.attributes(key("foo").value("bravo")),
headerWithName("Etag").description("three")
.attributes(key("foo").value("charlie"))))
.document(
this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(
resolver))
.response().header("X-Test", "test")
.header("Content-Type",
"application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo")
.row("Etag", "three", "charlie"));
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("X-Test").description("one").attributes(key("foo").value("alpha")),
headerWithName("Content-Type").description("two").attributes(key("foo").value("bravo")),
headerWithName("Etag").description("three").attributes(key("foo").value("charlie"))))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.response().header("X-Test", "test").header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23").build());
assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description", "Foo")
.row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo").row("Etag", "three", "charlie"));
}
@Test
public void additionalDescriptors() throws IOException {
HeaderDocumentation
.responseHeaders(headerWithName("X-Test").description("one"),
headerWithName("Content-Type").description("two"),
headerWithName("Etag").description("three"))
.and(headerWithName("Cache-Control").description("five"),
headerWithName("Vary").description("six"))
headerWithName("Content-Type").description("two"), headerWithName("Etag").description("three"))
.and(headerWithName("Cache-Control").description("five"), headerWithName("Vary").description("six"))
.document(this.operationBuilder.response().header("X-Test", "test")
.header("Content-Type", "application/json")
.header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent")
.build());
.header("Content-Type", "application/json").header("Etag", "lskjadldj3ii32l2ij23")
.header("Cache-Control", "max-age=0").header("Vary", "User-Agent").build());
assertThat(this.generatedSnippets.responseHeaders())
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one")
.row("`Content-Type`", "two").row("`Etag`", "three")
.row("`Cache-Control`", "five").row("`Vary`", "six"));
.is(tableWithHeader("Name", "Description").row("`X-Test`", "one").row("`Content-Type`", "two")
.row("`Etag`", "three").row("`Cache-Control`", "five").row("`Vary`", "six"));
}
@Test
public void tableCellContentIsEscapedWhenNecessary() throws IOException {
new ResponseHeadersSnippet(
Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.response()
.header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.responseHeaders()).is(
tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"),
escapeIfNecessary("one|two")));
new ResponseHeadersSnippet(Arrays.asList(headerWithName("Foo|Bar").description("one|two")))
.document(this.operationBuilder.response().header("Foo|Bar", "baz").build());
assertThat(this.generatedSnippets.responseHeaders()).is(tableWithHeader("Name", "Description")
.row(escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two")));
}
private String escapeIfNecessary(String input) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -51,338 +51,260 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests {
@Test
public void getRequest() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").header("Alpha", "a").build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithParameters() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.header("Alpha", "a").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?b=bravo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost"));
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").header("Alpha", "a").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.GET, "/foo?b=bravo")
.header("Alpha", "a").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithPort() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost:8080/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a")
.header(HttpHeaders.HOST, "localhost:8080"));
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost:8080/foo").header("Alpha", "a").build());
assertThat(this.generatedSnippets.httpRequest()).is(
httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a").header(HttpHeaders.HOST, "localhost:8080"));
}
@Test
public void getRequestWithCookies() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo")
.cookie("name1", "value1").cookie("name2", "value2").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.COOKIE, "name1=value1")
.header(HttpHeaders.COOKIE, "name2=value2"));
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.COOKIE, "name1=value1").header(HttpHeaders.COOKIE, "name2=value2"));
}
@Test
public void getRequestWithQueryString() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?bar=baz").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar=baz").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?bar=baz")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?bar=baz").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getRequestWithQueryStringWithNoValue() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?bar").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?bar").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST,
"localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getWithPartiallyOverlappingQueryStringAndParameters() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void getWithTotallyOverlappingQueryStringAndParameters() throws IOException {
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.param("a", "alpha").param("b", "bravo").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo")
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo")
.header(HttpHeaders.HOST, "localhost"));
.is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo").header(HttpHeaders.HOST, "localhost"));
}
@Test
public void postRequestWithContent() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").content(content).build());
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").method("POST").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost").content(content)
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("a", "alpha").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.param("a", "alpha").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndDisjointQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndDisjointQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo?b=bravo")
.method("POST").param("a", "alpha").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST")
.param("a", "alpha").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo?b=bravo").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo").method("POST")
.param("a", "alpha").param("b", "bravo").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters()
throws IOException {
public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo?b=bravo&a=alpha").method("POST")
.param("a", "alpha").param("b", "bravo").content(content).build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo?b=bravo&a=alpha")
.method("POST").param("a", "alpha").param("b", "bravo").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha")
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
.is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha").header(HttpHeaders.HOST, "localhost")
.content(content).header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody()
throws IOException {
public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException {
String content = "a=alpha&b=bravo";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
new HttpRequestSnippet().document(
this.operationBuilder.request("http://localhost/foo").method("POST").content("a=alpha&b=bravo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("a", "alpha").param("b", "bravo").build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void postRequestWithCharset() throws IOException {
String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4";
byte[] contentBytes = japaneseContent.getBytes("UTF-8");
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").header("Content-Type", "text/plain;charset=UTF-8")
.content(contentBytes).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header("Content-Type", "text/plain;charset=UTF-8")
.header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)
.content(japaneseContent));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build());
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/foo")
.header("Content-Type", "text/plain;charset=UTF-8").header(HttpHeaders.HOST, "localhost")
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length).content(japaneseContent));
}
@Test
public void postRequestWithParameter() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("POST").param("b&r", "baz").param("a", "alpha").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("POST")
.param("b&r", "baz").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("b%26r=baz&a=alpha"));
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha"));
}
@Test
public void postRequestWithParameterWithNoValue() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("POST").param("bar").build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").method("POST").param("bar").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("bar="));
.is(httpRequest(RequestMethod.POST, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("bar="));
}
@Test
public void putRequestWithContent() throws IOException {
String content = "Hello, world";
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/foo").method("PUT").content(content).build());
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo").method("PUT").content(content).build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.PUT, "/foo")
.header(HttpHeaders.HOST, "localhost").content(content)
.is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost").content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
public void putRequestWithParameter() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.method("PUT").param("b&r", "baz").param("a", "alpha").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo").method("PUT")
.param("b&r", "baz").param("a", "alpha").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.PUT, "/foo")
.header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded")
.content("b%26r=baz&a=alpha"));
.is(httpRequest(RequestMethod.PUT, "/foo").header(HttpHeaders.HOST, "localhost")
.header("Content-Type", "application/x-www-form-urlencoded").content("b%26r=baz&a=alpha"));
}
@Test
public void multipartPost() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes()).build());
String expectedContent = createPart(String.format(
"Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
String expectedContent = createPart(
String.format("Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithFilename() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes()).submittedFileName("image.png")
.build());
String expectedContent = createPart(String.format("Content-Disposition: "
+ "form-data; " + "name=image; filename=image.png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
.part("image", "<< data >>".getBytes()).submittedFileName("image.png").build());
String expectedContent = createPart(String
.format("Content-Disposition: " + "form-data; " + "name=image; filename=image.png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithParameters() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.param("a", "apple", "avocado").param("b", "banana")
.part("image", "<< data >>".getBytes()).build());
String param1Part = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n%napple"),
false);
String param2Part = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n%navocado"),
false);
String param3Part = createPart(
String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"),
false);
String filePart = createPart(String
.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a", "apple", "avocado")
.param("b", "banana").part("image", "<< data >>".getBytes()).build());
String param1Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false);
String param2Part = createPart(String.format("Content-Disposition: form-data; " + "name=a%n%navocado"), false);
String param3Part = createPart(String.format("Content-Disposition: form-data; " + "name=b%n%nbanana"), false);
String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
String expectedContent = param1Part + param2Part + param3Part + filePart;
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithParameterWithNoValue() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.param("a").part("image", "<< data >>".getBytes()).build());
String paramPart = createPart(
String.format("Content-Disposition: form-data; " + "name=a%n"), false);
String filePart = createPart(String
.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE).param("a")
.part("image", "<< data >>".getBytes()).build());
String paramPart = createPart(String.format("Content-Disposition: form-data; " + "name=a%n"), false);
String filePart = createPart(String.format("Content-Disposition: form-data; " + "name=image%n%n<< data >>"));
String expectedContent = paramPart + filePart;
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void multipartPostWithContentType() throws IOException {
new HttpRequestSnippet().document(this.operationBuilder
.request("http://localhost/upload").method("POST")
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/upload").method("POST")
.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
.part("image", "<< data >>".getBytes())
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE).build());
String expectedContent = createPart(
String.format("Content-Disposition: form-data; name=image%nContent-Type: "
+ "image/png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
.part("image", "<< data >>".getBytes()).header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
.build());
String expectedContent = createPart(String
.format("Content-Disposition: form-data; name=image%nContent-Type: " + "image/png%n%n<< data >>"));
assertThat(this.generatedSnippets.httpRequest()).is(httpRequest(RequestMethod.POST, "/upload")
.header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
.header(HttpHeaders.HOST, "localhost").content(expectedContent));
}
@Test
public void getRequestWithCustomHost() throws IOException {
new HttpRequestSnippet()
.document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com").build());
new HttpRequestSnippet().document(this.operationBuilder.request("http://localhost/foo")
.header(HttpHeaders.HOST, "api.example.com").build());
assertThat(this.generatedSnippets.httpRequest())
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST,
"api.example.com"));
.is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, "api.example.com"));
}
@Test
public void requestWithCustomSnippetAttributes() throws IOException {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("http-request"))
.willReturn(snippetResource("http-request-with-title"));
new HttpRequestSnippet(attributes(key("title").value("Title for the request")))
.document(this.operationBuilder
.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver))
given(resolver.resolveTemplateResource("http-request")).willReturn(snippetResource("http-request-with-title"));
new HttpRequestSnippet(attributes(key("title").value("Title for the request"))).document(
this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver))
.request("http://localhost/foo").build());
assertThat(this.generatedSnippets.httpRequest())
.contains("Title for the request");
assertThat(this.generatedSnippets.httpRequest()).contains("Title for the request");
}
private String createPart(String content) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -55,29 +55,25 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
@Test
public void nonOkResponse() throws IOException {
new HttpResponseSnippet().document(this.operationBuilder.response()
.status(HttpStatus.BAD_REQUEST.value()).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.BAD_REQUEST));
new HttpResponseSnippet()
.document(this.operationBuilder.response().status(HttpStatus.BAD_REQUEST.value()).build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.BAD_REQUEST));
}
@Test
public void responseWithHeaders() throws IOException {
new HttpResponseSnippet().document(this.operationBuilder.response()
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header("a", "alpha").build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)
.header("Content-Type", "application/json").header("a", "alpha"));
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).header("a", "alpha").build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).header("Content-Type", "application/json").header("a", "alpha"));
}
@Test
public void responseWithContent() throws IOException {
String content = "content";
new HttpResponseSnippet()
.document(this.operationBuilder.response().content(content).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
new HttpResponseSnippet().document(this.operationBuilder.response().content(content).build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK).content(content)
.header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length));
}
@Test
@@ -85,12 +81,10 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4";
byte[] contentBytes = japaneseContent.getBytes("UTF-8");
new HttpResponseSnippet().document(this.operationBuilder.response()
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes)
.build());
assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)
.header("Content-Type", "text/plain;charset=UTF-8")
.content(japaneseContent)
.header(HttpHeaders.CONTENT_LENGTH, contentBytes.length));
.header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes).build());
assertThat(this.generatedSnippets.httpResponse())
.is(httpResponse(HttpStatus.OK).header("Content-Type", "text/plain;charset=UTF-8")
.content(japaneseContent).header(HttpHeaders.CONTENT_LENGTH, contentBytes.length));
}
@Test
@@ -98,11 +92,9 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests {
TemplateResourceResolver resolver = mock(TemplateResourceResolver.class);
given(resolver.resolveTemplateResource("http-response"))
.willReturn(snippetResource("http-response-with-title"));
new HttpResponseSnippet(attributes(key("title").value("Title for the response")))
.document(this.operationBuilder.attribute(TemplateEngine.class.getName(),
new MustacheTemplateEngine(resolver)).build());
assertThat(this.generatedSnippets.httpResponse())
.contains("Title for the response");
new HttpResponseSnippet(attributes(key("title").value("Title for the response"))).document(this.operationBuilder
.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)).build());
assertThat(this.generatedSnippets.httpResponse()).contains("Title for the response");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2019 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.
@@ -48,8 +48,8 @@ public class ContentTypeLinkExtractorTests {
@Test
public void extractionFailsWithNullContentType() throws IOException {
this.thrown.expect(IllegalStateException.class);
new ContentTypeLinkExtractor().extractLinks(
this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null));
new ContentTypeLinkExtractor()
.extractLinks(this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), null));
}
@Test
@@ -59,8 +59,7 @@ public class ContentTypeLinkExtractorTests {
extractors.put(MediaType.APPLICATION_JSON, extractor);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
OperationResponse response = this.responseFactory.create(HttpStatus.OK,
httpHeaders, null);
OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null);
new ContentTypeLinkExtractor(extractors).extractLinks(response);
verify(extractor).extractLinks(response);
}
@@ -72,8 +71,7 @@ public class ContentTypeLinkExtractorTests {
extractors.put(MediaType.APPLICATION_JSON, extractor);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json;foo=bar"));
OperationResponse response = this.responseFactory.create(HttpStatus.OK,
httpHeaders, null);
OperationResponse response = this.responseFactory.create(HttpStatus.OK, httpHeaders, null);
new ContentTypeLinkExtractor(extractors).extractLinks(response);
verify(extractor).extractLinks(response);
}

View File

@@ -66,11 +66,8 @@ public class LinkExtractorsPayloadTests {
@Test
public void singleLink() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("single-link"));
assertLinks(
Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")),
links);
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("single-link"));
assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com", "Alpha")), links);
}
@Test
@@ -83,29 +80,24 @@ public class LinkExtractorsPayloadTests {
@Test
public void multipleLinksWithSameRels() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("multiple-links-same-rels"));
assertLinks(Arrays.asList(
new Link("alpha", "https://alpha.example.com/one", "Alpha one"),
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("multiple-links-same-rels"));
assertLinks(Arrays.asList(new Link("alpha", "https://alpha.example.com/one", "Alpha one"),
new Link("alpha", "https://alpha.example.com/two")), links);
}
@Test
public void noLinks() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("no-links"));
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("no-links"));
assertLinks(Collections.<Link>emptyList(), links);
}
@Test
public void linksInTheWrongFormat() throws IOException {
Map<String, List<Link>> links = this.linkExtractor
.extractLinks(createResponse("wrong-format"));
Map<String, List<Link>> links = this.linkExtractor.extractLinks(createResponse("wrong-format"));
assertLinks(Collections.<Link>emptyList(), links);
}
private void assertLinks(List<Link> expectedLinks,
Map<String, List<Link>> actualLinks) {
private void assertLinks(List<Link> expectedLinks, Map<String, List<Link>> actualLinks) {
MultiValueMap<String, Link> expectedLinksByRel = new LinkedMultiValueMap<>();
for (Link expectedLink : expectedLinks) {
expectedLinksByRel.add(expectedLink.getRel(), expectedLink);
@@ -119,8 +111,7 @@ public class LinkExtractorsPayloadTests {
}
private File getPayloadFile(String name) {
return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name
+ ".json");
return new File("src/test/resources/link-payloads/" + this.linkType + "/" + name + ".json");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2018 the original author or authors.
* Copyright 2014-2019 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.
@@ -39,8 +39,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
public class LinksSnippetFailureTests {
@Rule
public OperationBuilder operationBuilder = new OperationBuilder(
TemplateFormats.asciidoctor());
public OperationBuilder operationBuilder = new OperationBuilder(TemplateFormats.asciidoctor());
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -48,43 +47,36 @@ public class LinksSnippetFailureTests {
@Test
public void undocumentedLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo(
"Links with the following relations were not" + " documented: [foo]"));
this.thrown.expectMessage(equalTo("Links with the following relations were not" + " documented: [foo]"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")),
Collections.<LinkDescriptor>emptyList())
.document(this.operationBuilder.build());
Collections.<LinkDescriptor>emptyList()).document(this.operationBuilder.build());
}
@Test
public void missingLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Links with the following relations were not"
+ " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor(),
Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
this.thrown.expectMessage(
equalTo("Links with the following relations were not" + " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
}
@Test
public void undocumentedLinkAndMissingLink() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(equalTo("Links with the following relations were not"
+ " documented: [a]. Links with the following relations were not"
+ " found in the response: [foo]"));
+ " documented: [a]. Links with the following relations were not" + " found in the response: [foo]"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("a", "alpha")),
Arrays.asList(new LinkDescriptor("foo").description("bar")))
.document(this.operationBuilder.build());
Arrays.asList(new LinkDescriptor("foo").description("bar"))).document(this.operationBuilder.build());
}
@Test
public void linkWithNoDescription() throws IOException {
this.thrown.expect(SnippetException.class);
this.thrown.expectMessage(
equalTo("No description was provided for the link with rel 'foo' and no"
+ " title was available from the link in the payload"));
this.thrown.expectMessage(equalTo("No description was provided for the link with rel 'foo' and no"
+ " title was available from the link in the payload"));
new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "bar")),
Arrays.asList(new LinkDescriptor("foo")))
.document(this.operationBuilder.build());
Arrays.asList(new LinkDescriptor("foo"))).document(this.operationBuilder.build());
}
}

Some files were not shown because too many files have changed in this diff Show More