Support documenting fields in XML payloads with any content type

Previously, the document fields in an XML payload, the request or
response had to have an application/xml content type. This prevented
documenting standard XML content types such as text/xml and
application/rss+xml as well as payloads with custom XML content types.

This commit updates the logic that sets up the ContentHandler to
first attempt to parse the content as JSON. If that fails it then
parses it as XML. If that fails an exception is thrown. This allows
any JSON or XML content, irrespective of the actual content type, to
be documented.

Closes gh-393
This commit is contained in:
Andy Wilkinson
2017-05-12 12:31:18 +01:00
parent 88db798b25
commit 113976f2d9
9 changed files with 126 additions and 45 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2016 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -219,17 +219,32 @@ public abstract class AbstractFieldsSnippet extends TemplatedSnippet {
}
private ContentHandler getContentHandler(byte[] content, MediaType contentType) {
try {
if (contentType != null
&& MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
return new XmlContentHandler(content);
}
else {
return new JsonContentHandler(content);
ContentHandler contentHandler = createJsonContentHandler(content);
if (contentHandler == null) {
contentHandler = createXmlContentHandler(content);
if (contentHandler == null) {
throw new PayloadHandlingException("Cannot handle " + contentType
+ " content as it could not be parsed as JSON or XML");
}
}
catch (IOException ex) {
throw new ModelCreationException(ex);
return contentHandler;
}
private ContentHandler createJsonContentHandler(byte[] content) {
try {
return new JsonContentHandler(content);
}
catch (Exception ex) {
return null;
}
}
private ContentHandler createXmlContentHandler(byte[] content) {
try {
return new XmlContentHandler(content);
}
catch (Exception ex) {
return null;
}
}

View File

@@ -41,8 +41,9 @@ class JsonContentHandler implements ContentHandler {
private final byte[] rawContent;
JsonContentHandler(byte[] content) throws IOException {
JsonContentHandler(byte[] content) {
this.rawContent = content;
readContent();
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,6 +62,7 @@ class XmlContentHandler implements ContentHandler {
throw new IllegalStateException("Failed to create document builder", ex);
}
this.rawContent = rawContent;
readPayload();
}
@Override