Merge branch '1.2.x'

This commit is contained in:
Andy Wilkinson
2019-08-30 11:20:34 +01:00
192 changed files with 3407 additions and 5493 deletions

View File

@@ -131,7 +131,7 @@ configure(codeProjects) {
checkstyle {
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
configProperties = [ 'checkstyle.config.dir' : rootProject.file('config/checkstyle') ]
toolVersion = '6.10.1'
toolVersion = '8.22'
}
configurations {
@@ -270,4 +270,4 @@ configurations {
artifacts {
archives docsZip
}
}

View File

@@ -1,5 +1,5 @@
version=2.0.4.BUILD-SNAPSHOT
javaFormatVersion=0.0.7-SNAPSHOT
javaFormatVersion=0.0.15
org.gradle.daemon=false
asciidoctorj15Version=1.5.8.1
asciidoctorj16Version=1.6.2

View File

@@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ15Preprocessor 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

@@ -31,8 +31,7 @@ public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionR
if (!asciidoctorJ15()) {
return;
}
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor());
asciidoctor.rubyExtensionRegistry()
.loadClass(RestDocsAsciidoctorJ15ExtensionRegistry.class
.getResourceAsStream("/extensions/operation_block_macro.rb"))
@@ -41,8 +40,7 @@ public final class RestDocsAsciidoctorJ15ExtensionRegistry implements ExtensionR
private boolean asciidoctorJ15() {
try {
return !Class.forName("org.asciidoctor.extension.JavaExtensionRegistry")
.isInterface();
return !Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface();
}
catch (Throwable ex) {
return false;

View File

@@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ15PreprocessorTests {
@Test
public void snippetsAttributeIsSet() {
String converted = createAsciidoctor().convert("{snippets}",
createOptions("projectdir=../../.."));
assertThat(converted)
.contains("build" + File.separatorChar + "generated-snippets");
String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../.."));
assertThat(converted).contains("build" + File.separatorChar + "generated-snippets");
}
@Test
@@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ15PreprocessorTests {
private Asciidoctor createAsciidoctor() {
Asciidoctor asciidoctor = Asciidoctor.Factory.create();
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ15Preprocessor());
return asciidoctor;
}

View File

@@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ16Preprocessor extends Preprocessor {
@Override
public void process(Document document, PreprocessorReader reader) {
document.setAttribute("snippets", this.snippetsDirectoryResolver
.getSnippetsDirectory(document.getAttributes()), false);
document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()),
false);
}
}

View File

@@ -31,8 +31,7 @@ public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionR
if (!asciidoctorJ16()) {
return;
}
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor());
asciidoctor.rubyExtensionRegistry()
.loadClass(RestDocsAsciidoctorJ16ExtensionRegistry.class
.getResourceAsStream("/extensions/operation_block_macro.rb"))
@@ -41,8 +40,7 @@ public final class RestDocsAsciidoctorJ16ExtensionRegistry implements ExtensionR
private boolean asciidoctorJ16() {
try {
return Class.forName("org.asciidoctor.extension.JavaExtensionRegistry")
.isInterface();
return Class.forName("org.asciidoctor.extension.JavaExtensionRegistry").isInterface();
}
catch (Throwable ex) {
return false;

View File

@@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ16PreprocessorTests {
@Test
public void snippetsAttributeIsSet() {
String converted = createAsciidoctor().convert("{snippets}",
createOptions("projectdir=../../.."));
assertThat(converted)
.contains("build" + File.separatorChar + "generated-snippets");
String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../.."));
assertThat(converted).contains("build" + File.separatorChar + "generated-snippets");
}
@Test
@@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ16PreprocessorTests {
private Asciidoctor createAsciidoctor() {
Asciidoctor asciidoctor = Asciidoctor.Factory.create();
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ16Preprocessor());
return asciidoctor;
}

View File

@@ -32,8 +32,8 @@ final class DefaultAttributesAsciidoctorJ20Preprocessor extends Preprocessor {
@Override
public void process(Document document, PreprocessorReader reader) {
document.setAttribute("snippets", this.snippetsDirectoryResolver
.getSnippetsDirectory(document.getAttributes()), false);
document.setAttribute("snippets", this.snippetsDirectoryResolver.getSnippetsDirectory(document.getAttributes()),
false);
}
}

View File

@@ -28,8 +28,7 @@ public final class RestDocsAsciidoctorJ20ExtensionRegistry implements ExtensionR
@Override
public void register(Asciidoctor asciidoctor) {
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor());
asciidoctor.rubyExtensionRegistry()
.loadClass(RestDocsAsciidoctorJ20ExtensionRegistry.class
.getResourceAsStream("/extensions/operation_block_macro.rb"))

View File

@@ -34,10 +34,8 @@ public class DefaultAttributesAsciidoctorJ20PreprocessorTests {
@Test
public void snippetsAttributeIsSet() {
String converted = createAsciidoctor().convert("{snippets}",
createOptions("projectdir=../../.."));
assertThat(converted)
.contains("build" + File.separatorChar + "generated-snippets");
String converted = createAsciidoctor().convert("{snippets}", createOptions("projectdir=../../.."));
assertThat(converted).contains("build" + File.separatorChar + "generated-snippets");
}
@Test
@@ -62,8 +60,7 @@ public class DefaultAttributesAsciidoctorJ20PreprocessorTests {
private Asciidoctor createAsciidoctor() {
Asciidoctor asciidoctor = Asciidoctor.Factory.create();
asciidoctor.javaExtensionRegistry()
.preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor());
asciidoctor.javaExtensionRegistry().preprocessor(new DefaultAttributesAsciidoctorJ20Preprocessor());
return asciidoctor;
}

View File

@@ -41,8 +41,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) {
@@ -58,18 +57,15 @@ class SnippetsDirectoryResolver {
}
private File getGradleSnippetsDirectory(Map<String, Object> attributes) {
return new File(
getRequiredAttribute(attributes, "gradle-projectdir",
() -> getRequiredAttribute(attributes, "projectdir")),
"build/generated-snippets");
return new File(getRequiredAttribute(attributes, "gradle-projectdir",
() -> getRequiredAttribute(attributes, "projectdir")), "build/generated-snippets");
}
private String getRequiredAttribute(Map<String, Object> attributes, String name) {
return getRequiredAttribute(attributes, name, null);
}
private String getRequiredAttribute(Map<String, Object> attributes, String name,
Supplier<String> fallback) {
private String getRequiredAttribute(Map<String, Object> attributes, String name, Supplier<String> fallback) {
String attribute = (String) attributes.get(name);
if (attribute == null || attribute.length() == 0) {
if (fallback != null) {

View File

@@ -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,14 +71,11 @@ public class SnippetsDirectoryResolverTests {
}
@Test
public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdir()
throws IOException {
public void gradleProjectsUseBuildGeneratedSnippetsBeneathGradleProjectdir() throws IOException {
Map<String, Object> attributes = new HashMap<>();
attributes.put("gradle-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
@@ -94,10 +84,8 @@ public class SnippetsDirectoryResolverTests {
Map<String, Object> attributes = new HashMap<>();
attributes.put("gradle-projectdir", "project/dir");
attributes.put("projectdir", "fallback/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
@@ -105,15 +93,12 @@ public class SnippetsDirectoryResolverTests {
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 illegalStateWhenGradleProjectdirAndProjectdirAttributesAreNotSetInGradleProject()
throws IOException {
public void illegalStateWhenGradleProjectdirAndProjectdirAttributesAreNotSetInGradleProject() throws IOException {
Map<String, Object> attributes = new HashMap<>();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(equalTo("projectdir attribute not found"));

View File

@@ -62,23 +62,19 @@ public abstract class AbstractOperationBlockMacroTests {
@Before
public void setUp() throws IOException {
prepareOperationSnippets(getBuildOutputLocation());
this.options = OptionsBuilder.options().safe(SafeMode.UNSAFE)
.baseDir(getSourceLocation()).get();
this.options = OptionsBuilder.options().safe(SafeMode.UNSAFE).baseDir(getSourceLocation()).get();
this.options.setAttributes(getAttributes());
}
public void prepareOperationSnippets(File buildOutputLocation) throws IOException {
File destination = new File(buildOutputLocation,
"generated-snippets/some-operation");
File destination = new File(buildOutputLocation, "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);
}
@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"));
}
@@ -87,41 +83,34 @@ public abstract class AbstractOperationBlockMacroTests {
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"));
}
@@ -129,83 +118,64 @@ public abstract class AbstractOperationBlockMacroTests {
@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");
@@ -243,8 +213,7 @@ public abstract class AbstractOperationBlockMacroTests {
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) {
@@ -254,7 +223,7 @@ public abstract class AbstractOperationBlockMacroTests {
}
}
public List<String> getStrings() {
private List<String> getStrings() {
return this.strings;
}

View File

@@ -44,8 +44,7 @@ public class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroT
protected Attributes getAttributes() {
Attributes attributes = new Attributes();
attributes.setAttribute(this.attributeName,
new File(temp.getRoot(), "gradle-project").getAbsolutePath());
attributes.setAttribute(this.attributeName, new File(temp.getRoot(), "gradle-project").getAbsolutePath());
return attributes;
}
@@ -58,8 +57,7 @@ public class GradleOperationBlockMacroTests extends AbstractOperationBlockMacroT
@Override
protected File getSourceLocation() {
File sourceLocation = new File(temp.getRoot(),
"gradle-project/src/docs/asciidoc");
File sourceLocation = new File(temp.getRoot(), "gradle-project/src/docs/asciidoc");
if (!sourceLocation.exists()) {
sourceLocation.mkdirs();
}

View File

@@ -43,8 +43,7 @@ public class MavenOperationBlockMacroTests extends AbstractOperationBlockMacroTe
protected Attributes getAttributes() {
try {
File sourceLocation = getSourceLocation();
new File(sourceLocation.getParentFile().getParentFile().getParentFile(),
"pom.xml").createNewFile();
new File(sourceLocation.getParentFile().getParentFile().getParentFile(), "pom.xml").createNewFile();
Attributes attributes = new Attributes();
attributes.setAttribute("docdir", sourceLocation.getAbsolutePath());
return attributes;

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.
@@ -67,11 +67,9 @@ public final class ManualRestDocumentation implements RestDocumentationContextPr
*/
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 StandardRestDocumentationContext(testClass, testMethodName,
this.outputDirectory);
this.context = new StandardRestDocumentationContext(testClass, testMethodName, this.outputDirectory);
}
/**

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.
@@ -30,13 +30,11 @@ import org.junit.jupiter.api.extension.ParameterResolver;
*
* @author Andy Wilkinson
*/
public class RestDocumentationExtension
implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
public class RestDocumentationExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
this.getDelegate(context).beforeTest(context.getRequiredTestClass(),
context.getRequiredTestMethod().getName());
this.getDelegate(context).beforeTest(context.getRequiredTestClass(), context.getRequiredTestMethod().getName());
}
@Override
@@ -45,20 +43,16 @@ public class RestDocumentationExtension
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
if (isTestMethodContext(extensionContext)) {
return RestDocumentationContextProvider.class
.isAssignableFrom(parameterContext.getParameter().getType());
return RestDocumentationContextProvider.class.isAssignableFrom(parameterContext.getParameter().getType());
}
return false;
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext context) {
return (RestDocumentationContextProvider) () -> getDelegate(context)
.beforeOperation();
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) {
return (RestDocumentationContextProvider) () -> getDelegate(context).beforeOperation();
}
private boolean isTestMethodContext(ExtensionContext context) {
@@ -67,9 +61,8 @@ public class RestDocumentationExtension
private ManualRestDocumentation getDelegate(ExtensionContext context) {
Namespace namespace = Namespace.create(getClass(), context.getUniqueId());
return context.getStore(namespace).getOrComputeIfAbsent(
ManualRestDocumentation.class, (key) -> new ManualRestDocumentation(),
ManualRestDocumentation.class);
return context.getStore(namespace).getOrComputeIfAbsent(ManualRestDocumentation.class,
(key) -> new ManualRestDocumentation(), ManualRestDocumentation.class);
}
}

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.
@@ -34,8 +34,7 @@ final class StandardRestDocumentationContext implements RestDocumentationContext
private final File outputDirectory;
StandardRestDocumentationContext(Class<?> testClass, String testMethodName,
File outputDirectory) {
StandardRestDocumentationContext(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.
@@ -66,8 +66,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;
@@ -83,20 +82,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) {
@@ -125,8 +121,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()));
}
@@ -136,8 +131,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));
@@ -192,10 +186,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.
@@ -67,8 +67,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;
@@ -103,12 +102,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());
}
@@ -125,28 +122,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));
@@ -178,8 +170,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;
}
@@ -190,13 +181,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;
}
@@ -204,8 +193,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.
@@ -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.
@@ -34,8 +34,7 @@ import org.springframework.restdocs.operation.preprocess.Preprocessors;
* @author Andy Wilkinson
* @since 2.0.0
*/
public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
extends AbstractNestedConfigurer<PARENT> {
public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE> extends AbstractNestedConfigurer<PARENT> {
private OperationRequestPreprocessor defaultOperationRequestPreprocessor;
@@ -51,13 +50,10 @@ public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
}
@Override
public void apply(Map<String, Object> configuration,
RestDocumentationContext context) {
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
public void apply(Map<String, Object> configuration, RestDocumentationContext context) {
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
this.defaultOperationRequestPreprocessor);
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
this.defaultOperationResponsePreprocessor);
}
@@ -68,8 +64,7 @@ public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
*/
@SuppressWarnings("unchecked")
public TYPE withRequestDefaults(OperationPreprocessor... preprocessors) {
this.defaultOperationRequestPreprocessor = Preprocessors
.preprocessRequest(preprocessors);
this.defaultOperationRequestPreprocessor = Preprocessors.preprocessRequest(preprocessors);
return (TYPE) this;
}
@@ -80,8 +75,7 @@ public abstract class OperationPreprocessorsConfigurer<PARENT, TYPE>
*/
@SuppressWarnings("unchecked")
public TYPE withResponseDefaults(OperationPreprocessor... preprocessors) {
this.defaultOperationResponsePreprocessor = Preprocessors
.preprocessResponse(preprocessors);
this.defaultOperationResponsePreprocessor = Preprocessors.preprocessResponse(preprocessors);
return (TYPE) this;
}

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.
@@ -92,11 +92,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(),
operationPreprocessors(), this.templateEngineConfigurer,
this.writerResolverConfigurer);
protected final void apply(Map<String, Object> configuration, RestDocumentationContext context) {
List<AbstractConfigurer> configurers = Arrays.asList(snippets(), operationPreprocessors(),
this.templateEngineConfigurer, this.writerResolverConfigurer);
for (AbstractConfigurer configurer : configurers) {
configurer.apply(configuration, context);
}
@@ -107,21 +105,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);
@@ -138,16 +132,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.
@@ -115,11 +115,9 @@ import org.springframework.util.StringUtils;
*
* @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;
@@ -148,8 +146,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) {
@@ -176,8 +173,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-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.
@@ -92,11 +92,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);
}
@@ -114,10 +112,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);
}
@@ -136,13 +133,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);
}
/**
@@ -160,10 +155,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");
@@ -190,12 +183,9 @@ public final class RestDocumentationGenerator<REQ, RESP> {
*/
public void handle(REQ request, RESP response, Map<String, Object> configuration) {
Map<String, Object> attributes = new HashMap<>(configuration);
OperationRequest operationRequest = preprocessRequest(
this.requestConverter.convert(request), attributes);
OperationResponse operationResponse = preprocessResponse(
this.responseConverter.convert(response), attributes);
Operation operation = new StandardOperation(this.identifier, operationRequest,
operationResponse, attributes);
OperationRequest operationRequest = preprocessRequest(this.requestConverter.convert(request), attributes);
OperationResponse operationResponse = preprocessResponse(this.responseConverter.convert(response), attributes);
Operation operation = new StandardOperation(this.identifier, operationRequest, operationResponse, attributes);
try {
for (Snippet snippet : getSnippets(attributes)) {
snippet.document(operation);
@@ -214,16 +204,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);
}
@@ -231,44 +219,33 @@ public final class RestDocumentationGenerator<REQ, RESP> {
return combinedSnippets;
}
private OperationRequest preprocessRequest(OperationRequest request,
Map<String, Object> configuration) {
return preprocess(getRequestPreprocessors(configuration), request,
this::preprocess);
private OperationRequest preprocessRequest(OperationRequest request, Map<String, Object> configuration) {
return preprocess(getRequestPreprocessors(configuration), request, this::preprocess);
}
private OperationRequest preprocess(OperationRequestPreprocessor preprocessor,
OperationRequest request) {
private OperationRequest preprocess(OperationRequestPreprocessor preprocessor, OperationRequest request) {
return preprocessor.preprocess(request);
}
private List<OperationRequestPreprocessor> getRequestPreprocessors(
Map<String, Object> configuration) {
private List<OperationRequestPreprocessor> getRequestPreprocessors(Map<String, Object> configuration) {
return getPreprocessors(this.requestPreprocessor,
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
configuration);
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR, configuration);
}
private OperationResponse preprocessResponse(OperationResponse response,
Map<String, Object> configuration) {
return preprocess(getResponsePreprocessors(configuration), response,
this::preprocess);
private OperationResponse preprocessResponse(OperationResponse response, Map<String, Object> configuration) {
return preprocess(getResponsePreprocessors(configuration), response, this::preprocess);
}
private OperationResponse preprocess(OperationResponsePreprocessor preprocessor,
OperationResponse response) {
private OperationResponse preprocess(OperationResponsePreprocessor preprocessor, OperationResponse response) {
return preprocessor.preprocess(response);
}
private List<OperationResponsePreprocessor> getResponsePreprocessors(
Map<String, Object> configuration) {
private List<OperationResponsePreprocessor> getResponsePreprocessors(Map<String, Object> configuration) {
return getPreprocessors(this.responsePreprocessor,
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
configuration);
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR, configuration);
}
private <P, T> T preprocess(List<P> preprocessors, T target,
BiFunction<P, T, T> function) {
private <P, T> T preprocess(List<P> preprocessors, T target, BiFunction<P, T, T> function) {
T processed = target;
for (P preprocessor : preprocessors) {
processed = function.apply(preprocessor, processed);
@@ -288,8 +265,7 @@ public final class RestDocumentationGenerator<REQ, RESP> {
return preprocessors;
}
private static final class IdentityOperationRequestPreprocessor
implements OperationRequestPreprocessor {
private static final class IdentityOperationRequestPreprocessor implements OperationRequestPreprocessor {
@Override
public OperationRequest preprocess(OperationRequest request) {
@@ -298,8 +274,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-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,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-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.
@@ -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.
@@ -132,19 +132,17 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor
}
URI modifiedUri = uriBuilder.build(true).toUri();
HttpHeaders modifiedHeaders = modify(request.getHeaders());
modifiedHeaders.set(HttpHeaders.HOST, modifiedUri.getHost()
+ ((modifiedUri.getPort() != -1) ? ":" + modifiedUri.getPort() : ""));
return this.contentModifyingDelegate.preprocess(new OperationRequestFactory()
.create(uriBuilder.build(true).toUri(), request.getMethod(),
request.getContent(), modifiedHeaders, request.getParameters(),
modify(request.getParts()), request.getCookies()));
modifiedHeaders.set(HttpHeaders.HOST,
modifiedUri.getHost() + ((modifiedUri.getPort() != -1) ? ":" + modifiedUri.getPort() : ""));
return this.contentModifyingDelegate.preprocess(new OperationRequestFactory().create(
uriBuilder.build(true).toUri(), request.getMethod(), request.getContent(), modifiedHeaders,
request.getParameters(), modify(request.getParts()), request.getCookies()));
}
@Override
public OperationResponse preprocess(OperationResponse response) {
return this.contentModifyingDelegate
.preprocess(new OperationResponseFactory().create(response.getStatus(),
modify(response.getHeaders()), response.getContent()));
return this.contentModifyingDelegate.preprocess(new OperationResponseFactory().create(response.getStatus(),
modify(response.getHeaders()), response.getContent()));
}
private HttpHeaders modify(HttpHeaders headers) {
@@ -157,14 +155,12 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor
return modified;
}
private Collection<OperationRequestPart> modify(
Collection<OperationRequestPart> parts) {
private Collection<OperationRequestPart> modify(Collection<OperationRequestPart> parts) {
List<OperationRequestPart> modifiedParts = new ArrayList<>();
OperationRequestPartFactory factory = new OperationRequestPartFactory();
for (OperationRequestPart part : parts) {
modifiedParts.add(factory.create(part.getName(), part.getSubmittedFileName(),
this.contentModifier.modifyContent(part.getContent(),
part.getHeaders().getContentType()),
this.contentModifier.modifyContent(part.getContent(), part.getHeaders().getContentType()),
modify(part.getHeaders())));
}
return modifiedParts;
@@ -172,8 +168,7 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor
private static final class UriModifyingContentModifier implements ContentModifier {
private static final Pattern SCHEME_HOST_PORT_PATTERN = Pattern
.compile("(http[s]?)://([^/:#?]+)(:[0-9]+)?");
private static final Pattern SCHEME_HOST_PORT_PATTERN = Pattern.compile("(http[s]?)://([^/:#?]+)(:[0-9]+)?");
private String scheme;
@@ -222,8 +217,7 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor
if (matcher.start(i) >= 0) {
previous = matcher.end(i);
}
builder.append(
getReplacement(matcher.group(i), replacements.get(i - 1)));
builder.append(getReplacement(matcher.group(i), replacements.get(i - 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.
@@ -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.
@@ -62,8 +62,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);
}
@@ -82,11 +82,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);
}
/**
@@ -102,9 +100,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);
}
@@ -125,20 +122,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;
@@ -158,8 +151,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 = ContentHandler.forContent(content, contentType);
@@ -173,9 +165,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);
}
@@ -195,15 +186,14 @@ 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;
}
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);
@@ -211,8 +201,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) {
@@ -222,8 +212,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);
}
@@ -288,11 +277,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();
}
@@ -305,8 +292,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-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.
@@ -67,8 +67,8 @@ interface ContentHandler extends FieldTypeResolver {
return new XmlContentHandler(content);
}
catch (Exception xe) {
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");
}
}
}

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.
@@ -40,8 +40,7 @@ class JsonContentHandler implements ContentHandler {
private final JsonFieldTypesDiscoverer fieldTypesDiscoverer = new JsonFieldTypesDiscoverer();
private final ObjectMapper objectMapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
private final ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final byte[] rawContent;
@@ -51,15 +50,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);
}
}
@@ -67,13 +63,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;
}
@@ -85,8 +80,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());
}
@@ -148,8 +142,7 @@ class JsonContentHandler implements ContentHandler {
@Override
public Object resolveFieldType(FieldDescriptor fieldDescriptor) {
if (fieldDescriptor.getType() == null) {
return this.fieldTypesDiscoverer
.discoverFieldTypes(fieldDescriptor.getPath(), readContent())
return this.fieldTypesDiscoverer.discoverFieldTypes(fieldDescriptor.getPath(), readContent())
.coalesce(fieldDescriptor.isOptional());
}
if (!(fieldDescriptor.getType() instanceof JsonFieldType)) {
@@ -160,10 +153,8 @@ class JsonContentHandler implements ContentHandler {
JsonFieldType actualFieldType = this.fieldTypesDiscoverer
.discoverFieldTypes(fieldDescriptor.getPath(), readContent())
.coalesce(fieldDescriptor.isOptional());
if (descriptorFieldType == JsonFieldType.VARIES
|| descriptorFieldType == actualFieldType
|| (fieldDescriptor.isOptional()
&& actualFieldType == JsonFieldType.NULL)) {
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,33 +58,30 @@ final class JsonFieldProcessor {
if (values.isEmpty()) {
values.add(ExtractedField.ABSENT);
}
return new ExtractedField(
(compiledPath.getType() != PathType.SINGLE) ? values : values.get(0),
return new ExtractedField((compiledPath.getType() != PathType.SINGLE) ? values : values.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();
}
});
});
}
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();
}
});
});
}
private void traverse(ProcessingContext context, MatchCallback matchCallback) {
@@ -99,54 +96,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);
}
@@ -171,8 +162,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
@@ -181,8 +172,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 {
@@ -225,8 +215,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);
@@ -271,8 +260,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;
@@ -395,8 +383,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();
@@ -421,8 +408,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-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-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,18 +55,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);
}
@@ -79,8 +75,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));
@@ -93,8 +88,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());
}
@@ -130,8 +124,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
@@ -160,8 +153,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-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.
@@ -36,8 +36,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";
@@ -54,26 +53,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);
@@ -84,8 +81,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);
@@ -93,8 +89,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());
@@ -105,8 +100,7 @@ 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 + "'");
}
}

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-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,7 +38,7 @@ 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;
}

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,24 +64,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.
@@ -57,59 +57,47 @@ 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);
private final OperationPreprocessor requestPreprocessor = mock(
OperationPreprocessor.class);
private final OperationPreprocessor requestPreprocessor = mock(OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(
OperationPreprocessor.class);
private final OperationPreprocessor responsePreprocessor = mock(OperationPreprocessor.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);
@@ -118,90 +106,67 @@ public class RestDocumentationGeneratorTests {
@Test
public void defaultOperationRequestPreprocessorsAreCalled() 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<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1,
defaultPreprocessor2));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR,
Preprocessors.preprocessRequest(defaultPreprocessor1, defaultPreprocessor2));
OperationRequest first = createRequest();
OperationRequest second = createRequest();
OperationRequest third = createRequest();
given(this.requestPreprocessor.preprocess(this.operationRequest))
.willReturn(first);
given(this.requestPreprocessor.preprocess(this.operationRequest)).willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter,
Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse,
configuration, 1);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter,
Preprocessors.preprocessRequest(this.requestPreprocessor), this.snippet).handle(this.request,
this.response, configuration);
verifySnippetInvocation(this.snippet, third, this.operationResponse, configuration, 1);
}
@Test
public void defaultOperationResponsePreprocessorsAreCalled() 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<>();
OperationPreprocessor defaultPreprocessor1 = mock(OperationPreprocessor.class);
OperationPreprocessor defaultPreprocessor2 = mock(OperationPreprocessor.class);
configuration.put(
RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1,
defaultPreprocessor2));
configuration.put(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR,
Preprocessors.preprocessResponse(defaultPreprocessor1, defaultPreprocessor2));
OperationResponse first = createResponse();
OperationResponse second = createResponse();
OperationResponse third = new OperationResponseFactory()
.createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse))
.willReturn(first);
OperationResponse third = new OperationResponseFactory().createFrom(this.operationResponse, new HttpHeaders());
given(this.responsePreprocessor.preprocess(this.operationResponse)).willReturn(first);
given(defaultPreprocessor1.preprocess(first)).willReturn(second);
given(defaultPreprocessor2.preprocess(second)).willReturn(third);
new RestDocumentationGenerator<>("id", this.requestConverter,
this.responseConverter,
Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet)
.handle(this.request, this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration,
1);
new RestDocumentationGenerator<>("id", this.requestConverter, this.responseConverter,
Preprocessors.preprocessResponse(this.responsePreprocessor), this.snippet).handle(this.request,
this.response, configuration);
verifySnippetInvocation(this.snippet, this.operationRequest, third, configuration, 1);
}
@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());
@@ -209,17 +174,16 @@ public class RestDocumentationGeneratorTests {
assertThat(attributes).isEqualTo(operation.getValue().getAttributes());
}
private void verifySnippetInvocation(Snippet snippet,
OperationRequest operationRequest, OperationResponse operationResponse,
Map<String, Object> attributes, int times) throws IOException {
private void verifySnippetInvocation(Snippet snippet, OperationRequest operationRequest,
OperationResponse operationResponse, Map<String, Object> attributes, int times) throws IOException {
ArgumentCaptor<Operation> operation = ArgumentCaptor.forClass(Operation.class);
verify(snippet, Mockito.times(times)).document(operation.capture());
assertThat(operationRequest).isEqualTo(operation.getValue().getRequest());
assertThat(operationResponse).isEqualTo(operation.getValue().getResponse());
}
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());
@@ -228,8 +192,8 @@ public class RestDocumentationGeneratorTests {
}
private static OperationRequest createRequest() {
return new OperationRequestFactory().create(URI.create("http://localhost:8080"),
null, null, new HttpHeaders(), null, null);
return new OperationRequestFactory().create(URI.create("http://localhost:8080"), null, null, new HttpHeaders(),
null, null);
}
private static OperationResponse createResponse() {

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.
@@ -72,30 +72,23 @@ 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());
OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
assertThat(defaultOperationRequestPreprocessor).isNull();
@@ -109,32 +102,25 @@ public class RestDocumentationConfigurerTests {
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);
@@ -147,29 +133,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");
@@ -178,15 +158,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")
@@ -194,14 +171,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")
@@ -210,11 +185,10 @@ 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);
}
@@ -222,40 +196,33 @@ public class RestDocumentationConfigurerTests {
public void customDefaultOperationRequestPreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withRequestDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.withRequestDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
OperationRequestPreprocessor preprocessor = (OperationRequestPreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationRequest request = new OperationRequestFactory().create(
URI.create("http://localhost:8080"), HttpMethod.GET, null, headers, null,
Collections.emptyList());
assertThat(preprocessor.preprocess(request).getHeaders())
.doesNotContainKey("Foo");
OperationRequest request = new OperationRequestFactory().create(URI.create("http://localhost:8080"),
HttpMethod.GET, null, headers, null, Collections.emptyList());
assertThat(preprocessor.preprocess(request).getHeaders()).doesNotContainKey("Foo");
}
@Test
public void customDefaultOperationResponsePreprocessor() {
Map<String, Object> configuration = new HashMap<>();
this.configurer.operationPreprocessors()
.withResponseDefaults(Preprocessors.prettyPrint(),
Preprocessors.removeHeaders("Foo"))
.withResponseDefaults(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Foo"))
.apply(configuration, createContext());
OperationResponsePreprocessor preprocessor = (OperationResponsePreprocessor) configuration
.get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR);
HttpHeaders headers = new HttpHeaders();
headers.add("Foo", "value");
OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK,
headers, null);
assertThat(preprocessor.preprocess(response).getHeaders())
.doesNotContainKey("Foo");
OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, headers, null);
assertThat(preprocessor.preprocess(response).getHeaders()).doesNotContainKey("Foo");
}
private RestDocumentationContext createContext() {
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation(
"build");
ManualRestDocumentation manualRestDocumentation = new ManualRestDocumentation("build");
manualRestDocumentation.beforeTest(null, null);
RestDocumentationContext context = manualRestDocumentation.beforeOperation();
return context;
@@ -264,8 +231,7 @@ public class RestDocumentationConfigurerTests {
private static final class TestRestDocumentationConfigurer extends
RestDocumentationConfigurer<TestSnippetConfigurer, TestOperationPreprocessorsConfigurer, TestRestDocumentationConfigurer> {
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(
this);
private final TestSnippetConfigurer snippetConfigurer = new TestSnippetConfigurer(this);
private final TestOperationPreprocessorsConfigurer operationPreprocessorsConfigurer = new TestOperationPreprocessorsConfigurer(
this);
@@ -282,8 +248,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);
@@ -294,8 +260,7 @@ public class RestDocumentationConfigurerTests {
private static final class TestOperationPreprocessorsConfigurer extends
OperationPreprocessorsConfigurer<TestRestDocumentationConfigurer, TestOperationPreprocessorsConfigurer> {
protected TestOperationPreprocessorsConfigurer(
TestRestDocumentationConfigurer parent) {
protected TestOperationPreprocessorsConfigurer(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-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.
@@ -78,8 +78,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@Test
public void defaultMessageAssertFalse() {
assertThat(constraintDescriptionForField("assertFalse"))
.isEqualTo("Must be false");
assertThat(constraintDescriptionForField("assertFalse")).isEqualTo("Must be false");
}
@Test
@@ -101,14 +100,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
@@ -119,14 +116,12 @@ 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
public void defaultMessageFutureOrPresent() {
assertThat(constraintDescriptionForField("futureOrPresent"))
.isEqualTo("Must be in the future or the present");
assertThat(constraintDescriptionForField("futureOrPresent")).isEqualTo("Must be in the future or the present");
}
@Test
@@ -141,8 +136,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
@@ -152,14 +146,12 @@ 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
public void defaultMessagePastOrPresent() {
assertThat(constraintDescriptionForField("pastOrPresent"))
.isEqualTo("Must be in the past or the present");
assertThat(constraintDescriptionForField("pastOrPresent")).isEqualTo("Must be in the past or the present");
}
@Test
@@ -170,8 +162,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
@@ -182,14 +173,12 @@ 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
@@ -200,8 +189,7 @@ public class ResourceBundleConstraintDescriptionResolverTests {
@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
@@ -212,80 +200,67 @@ 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 defaultMessageNegative() {
assertThat(constraintDescriptionForField("negative"))
.isEqualTo("Must be negative");
assertThat(constraintDescriptionForField("negative")).isEqualTo("Must be negative");
}
@Test
public void defaultMessageNegativeOrZero() {
assertThat(constraintDescriptionForField("negativeOrZero"))
.isEqualTo("Must be negative or zero");
assertThat(constraintDescriptionForField("negativeOrZero")).isEqualTo("Must be negative or zero");
}
@Test
public void defaultMessageNotBlank() {
assertThat(constraintDescriptionForField("notBlank"))
.isEqualTo("Must not be blank");
assertThat(constraintDescriptionForField("notBlank")).isEqualTo("Must not be blank");
}
@Test
public void defaultMessageNotBlankHibernateValidator() {
assertThat(constraintDescriptionForField("notBlankHibernateValidator"))
.isEqualTo("Must not be blank");
assertThat(constraintDescriptionForField("notBlankHibernateValidator")).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 defaultMessageNotEmptyHibernateValidator() {
assertThat(constraintDescriptionForField("notEmpty"))
.isEqualTo("Must not be empty");
assertThat(constraintDescriptionForField("notEmpty")).isEqualTo("Must not be empty");
}
@Test
public void defaultMessagePositive() {
assertThat(constraintDescriptionForField("positive"))
.isEqualTo("Must be positive");
assertThat(constraintDescriptionForField("positive")).isEqualTo("Must be positive");
}
@Test
public void defaultMessagePositiveOrZero() {
assertThat(constraintDescriptionForField("positiveOrZero"))
.isEqualTo("Must be positive or zero");
assertThat(constraintDescriptionForField("positiveOrZero")).isEqualTo("Must be positive or zero");
}
@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
@@ -294,8 +269,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");
}
@@ -305,9 +279,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");
}
@@ -322,14 +295,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");
}
@@ -338,10 +309,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;
}
}

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