Merge remote-tracking branch 'origin/3.1.x' into 4.0.x

# Conflicts:
#	samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION
#	samples/server/petstore/kotlin-server/ktor/README.md
#	samples/server/petstore/php-silex/.openapi-generator/VERSION
This commit is contained in:
Jeremie Bresson 2018-06-25 19:09:41 +02:00
commit b0c02d8ea6
1446 changed files with 46647 additions and 40688 deletions

View File

@ -112,7 +112,7 @@ after_success:
./gradlew -Psigning.keyId="$SIGNING_KEY" -Psigning.password="$SIGNING_PASSPHRASE" -Psigning.secretKeyRingFile="${TRAVIS_BUILD_DIR}/sec.gpg" -PossrhUsername="${SONATYPE_USERNAME}" -PossrhPassword="${SONATYPE_PASSWORD}" uploadArchives --no-daemon;
echo "Finished ./gradlew uploadArchives";
popd;
else
elif ([ "$TRAVIS_BRANCH" == "3.1.x" ] || [ "$TRAVIS_BRANCH" == "4.0.x" ]) ; then
mvn clean deploy --settings CI/settings.xml;
echo "Finished mvn clean deploy for $TRAVIS_BRANCH";
pushd .;
@ -128,4 +128,4 @@ after_success:
- if [ $DOCKER_HUB_USERNAME ]; then echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin && docker build -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; fi && if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME && echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; fi; fi
env:
- DOCKER_GENERATOR_IMAGE_NAME=openapitools/openapi-generator-online DOCKER_CODEGEN_CLI_IMAGE_NAME=openapitools/openapi-generator-cli
- DOCKER_GENERATOR_IMAGE_NAME=openapitools/openapi-generator-online DOCKER_CODEGEN_CLI_IMAGE_NAME=openapitools/openapi-generator-cli NODE_ENV=test

View File

@ -836,8 +836,8 @@
<!-- test non-java projects -->
<module>samples/client/petstore/go</module>
<!-- test java-related projects -->
<module>samples/client/petstore/akka-scala</module>
<module>samples/client/petstore/scala</module>
<module>samples/client/petstore/scala-akka</module>
<module>samples/client/petstore/scala-httpclient</module>
<module>samples/client/petstore/scalaz</module>
<module>samples/client/petstore/clojure</module>
<module>samples/client/petstore/java/feign</module>

View File

@ -834,8 +834,8 @@
<modules>
<!-- clients -->
<!-- test java-related projects -->
<module>samples/client/petstore/akka-scala</module>
<module>samples/client/petstore/scala</module>
<module>samples/client/petstore/scala-akka</module>
<module>samples/client/petstore/scala-httpclient</module>
<module>samples/client/petstore/scalaz</module>
<module>samples/client/petstore/clojure</module>
<module>samples/client/petstore/java/feign</module>

View File

@ -0,0 +1,15 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class ConfigurationTest {
@Test
public void testDefaultApiClient() {
ApiClient apiClient = Configuration.getDefaultApiClient();
assertNotNull(apiClient);
assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath());
assertFalse(apiClient.isDebugging());
}
}

View File

@ -0,0 +1,33 @@
package org.openapitools.client;
import org.junit.*;
import static org.junit.Assert.*;
public class StringUtilTest {
@Test
public void testContainsIgnoreCase() {
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
}
@Test
public void testJoin() {
String[] array = {"aa", "bb", "cc"};
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
assertEquals("aabbcc", StringUtil.join(array, ""));
assertEquals("aa bb cc", StringUtil.join(array, " "));
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
assertEquals("", StringUtil.join(new String[]{}, ","));
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
}
}

View File

@ -0,0 +1,292 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> auths = apiClient.getAuthentications();
Authentication auth = auths.get("api_key");
assertNotNull(auth);
assertTrue(auth instanceof ApiKeyAuth);
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
assertEquals("header", apiKeyAuth.getLocation());
assertEquals("api_key", apiKeyAuth.getParamName());
auth = auths.get("petstore_auth");
assertTrue(auth instanceof OAuth);
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
assertNull(auths.get("unknown"));
try {
auths.put("my_auth", new HttpBasicAuth());
fail("the authentications returned should not be modifiable");
} catch (UnsupportedOperationException e) {
}
}
@Ignore("There is no more basic auth in petstore security definitions")
@Test
public void testSetUsernameAndPassword() {
HttpBasicAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof HttpBasicAuth) {
auth = (HttpBasicAuth) _auth;
break;
}
}
auth.setUsername(null);
auth.setPassword(null);
apiClient.setUsername("my-username");
apiClient.setPassword("my-password");
assertEquals("my-username", auth.getUsername());
assertEquals("my-password", auth.getPassword());
// reset values
auth.setUsername(null);
auth.setPassword(null);
}
@Test
public void testSetApiKeyAndPrefix() {
ApiKeyAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof ApiKeyAuth) {
auth = (ApiKeyAuth) _auth;
break;
}
}
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
apiClient.setApiKey("my-api-key");
apiClient.setApiKeyPrefix("Token");
assertEquals("my-api-key", auth.getApiKey());
assertEquals("Token", auth.getApiKeyPrefix());
// reset values
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
}
@Test
public void testParameterToPairWhenNameIsInvalid() throws Exception {
List<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> concatStrings = apiClient.parameterToPairs("csv", "param-a", strs);
assertEquals(1, concatStrings.size());
assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters
}
@Test
public void testParameterToPairsWhenValueIsCollection() throws Exception {
Map<String, String> collectionFormatMap = new HashMap<String, String>();
collectionFormatMap.put("csv", ",");
collectionFormatMap.put("tsv", "\t");
collectionFormatMap.put("ssv", " ");
collectionFormatMap.put("pipes", "|");
collectionFormatMap.put("", ","); // no format, must default to csv
collectionFormatMap.put("unknown", ","); // all other formats, must default to csv
String name = "param-a";
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
for (int i = 0; i < values.size(); i++) {
assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue());
}
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values);
assertEquals(1, pairs.size());
String delimiter = collectionFormatMap.get(collectionFormat);
if (!delimiter.equals(",")) {
// commas are not escaped because they are reserved characters in URIs
delimiter = apiClient.escapeString(delimiter);
}
String[] pairValueSplit = pairs.get(0).getValue().split(delimiter);
// must equal input values
assertEquals(values.size(), pairValueSplit.length);
for (int i = 0; i < values.size(); i++) {
assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]);
}
}
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
assertEquals(expected, headerParams.get("Authorization"));
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,45 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.*;
import static org.junit.Assert.*;
public class JSONTest {
JSON json = null;
Order order = null;
@Before
public void setup() {
json = new JSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime::from));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}

View File

@ -0,0 +1,250 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> auths = apiClient.getAuthentications();
Authentication auth = auths.get("api_key");
assertNotNull(auth);
assertTrue(auth instanceof ApiKeyAuth);
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
assertEquals("header", apiKeyAuth.getLocation());
assertEquals("api_key", apiKeyAuth.getParamName());
auth = auths.get("petstore_auth");
assertTrue(auth instanceof OAuth);
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
assertNull(auths.get("unknown"));
try {
auths.put("my_auth", new HttpBasicAuth());
fail("the authentications returned should not be modifiable");
} catch (UnsupportedOperationException e) {
}
}
@Ignore("There is no more basic auth in petstore security definitions")
@Test
public void testSetUsernameAndPassword() {
HttpBasicAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof HttpBasicAuth) {
auth = (HttpBasicAuth) _auth;
break;
}
}
auth.setUsername(null);
auth.setPassword(null);
apiClient.setUsername("my-username");
apiClient.setPassword("my-password");
assertEquals("my-username", auth.getUsername());
assertEquals("my-password", auth.getPassword());
// reset values
auth.setUsername(null);
auth.setPassword(null);
}
@Test
public void testSetApiKeyAndPrefix() {
ApiKeyAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof ApiKeyAuth) {
auth = (ApiKeyAuth) _auth;
break;
}
}
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
apiClient.setApiKey("my-api-key");
apiClient.setApiKeyPrefix("Token");
assertEquals("my-api-key", auth.getApiKey());
assertEquals("Token", auth.getApiKeyPrefix());
// reset values
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> concatStrings = apiClient.parameterToPairs("csv", "param-a", strs);
assertEquals(1, concatStrings.size());
assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters
}
@Test
public void testParameterToPairsWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPairs("csv", name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairsWhenValueIsCollection() throws Exception {
Map<String, String> collectionFormatMap = new HashMap<String, String>();
collectionFormatMap.put("csv", ",");
collectionFormatMap.put("tsv", "\t");
collectionFormatMap.put("ssv", " ");
collectionFormatMap.put("pipes", "\\|");
collectionFormatMap.put("", ","); // no format, must default to csv
collectionFormatMap.put("unknown", ","); // all other formats, must default to csv
String name = "param-a";
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values);
assertEquals(1, pairs.size());
String delimiter = collectionFormatMap.get(collectionFormat);
String[] pairValueSplit = pairs.get(0).getValue().split(delimiter);
// must equal input values
assertEquals(values.size(), pairValueSplit.length);
}
}
}

View File

@ -0,0 +1,58 @@
package org.openapitools.client;
import org.openapitools.client.model.Order;
import org.junit.Before;
import org.junit.Test;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private JSON json = null;
private Order order = null;
@Before
public void setup() {
json = new ApiClient().getJSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter dateFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testSqlDateSerialization() throws Exception {
String str = json.getContext(null).writeValueAsString(new java.sql.Date(10));
assertEquals("\"1970-01-01\"", str);
}
@Test
public void testSqlDateDeserialization() throws Exception {
final String str = "1970-01-01";
java.sql.Date date = json.getContext(null).readValue("\"" + str + "\"", java.sql.Date.class);
assertEquals(date.toString(), str);
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
}

View File

@ -0,0 +1,52 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
assertEquals(expected, headerParams.get("Authorization"));
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,330 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.TimeZone;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient;
JSON json;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime(null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
assertTrue(apiClient.isJsonMime("application/json-patch+json"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> auths = apiClient.getAuthentications();
Authentication auth = auths.get("api_key");
assertNotNull(auth);
assertTrue(auth instanceof ApiKeyAuth);
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
assertEquals("header", apiKeyAuth.getLocation());
assertEquals("api_key", apiKeyAuth.getParamName());
auth = auths.get("petstore_auth");
assertTrue(auth instanceof OAuth);
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
assertNull(auths.get("unknown"));
try {
auths.put("my_auth", new HttpBasicAuth());
fail("the authentications returned should not be modifiable");
} catch (UnsupportedOperationException e) {
}
}
/*
@Test
public void testSetUsernameAndPassword() {
HttpBasicAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof HttpBasicAuth) {
auth = (HttpBasicAuth) _auth;
break;
}
}
auth.setUsername(null);
auth.setPassword(null);
apiClient.setUsername("my-username");
apiClient.setPassword("my-password");
assertEquals("my-username", auth.getUsername());
assertEquals("my-password", auth.getPassword());
// reset values
auth.setUsername(null);
auth.setPassword(null);
}
*/
@Test
public void testSetApiKeyAndPrefix() {
ApiKeyAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof ApiKeyAuth) {
auth = (ApiKeyAuth) _auth;
break;
}
}
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
apiClient.setApiKey("my-api-key");
apiClient.setApiKeyPrefix("Token");
assertEquals("my-api-key", auth.getApiKey());
assertEquals("Token", auth.getApiKeyPrefix());
// reset values
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
}
@Test
public void testGetAndSetConnectTimeout() {
// connect timeout defaults to 10 seconds
assertEquals(10000, apiClient.getConnectTimeout());
assertEquals(10000, apiClient.getHttpClient().getConnectTimeout());
apiClient.setConnectTimeout(0);
assertEquals(0, apiClient.getConnectTimeout());
assertEquals(0, apiClient.getHttpClient().getConnectTimeout());
apiClient.setConnectTimeout(10000);
}
@Test
public void testGetAndSetReadTimeout() {
// read timeout defaults to 10 seconds
assertEquals(10000, apiClient.getReadTimeout());
assertEquals(10000, apiClient.getHttpClient().getReadTimeout());
apiClient.setReadTimeout(0);
assertEquals(0, apiClient.getReadTimeout());
assertEquals(0, apiClient.getHttpClient().getReadTimeout());
apiClient.setReadTimeout(10000);
}
@Test
public void testGetAndSetWriteTimeout() {
// write timeout defaults to 10 seconds
assertEquals(10000, apiClient.getWriteTimeout());
assertEquals(10000, apiClient.getHttpClient().getWriteTimeout());
apiClient.setWriteTimeout(0);
assertEquals(0, apiClient.getWriteTimeout());
assertEquals(0, apiClient.getHttpClient().getWriteTimeout());
apiClient.setWriteTimeout(10000);
}
@Test
public void testParameterToPairWhenNameIsInvalid() throws Exception {
List<Pair> pairs_a = apiClient.parameterToPair(null, new Integer(1));
List<Pair> pairs_b = apiClient.parameterToPair("", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPair("param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairWhenValueIsEmptyString() throws Exception {
// single empty string
List<Pair> pairs = apiClient.parameterToPair("param-a", " ");
assertEquals(1, pairs.size());
}
@Test
public void testParameterToPairWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
List<Pair> pairs = apiClient.parameterToPair(name, value);
assertEquals(1, pairs.size());
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
}
@Test
public void testParameterToPairWhenValueIsCollection() throws Exception {
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
List<Pair> pairs = apiClient.parameterToPair("param-a", values);
assertEquals(0, pairs.size());
}
@Test
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
List<Integer> objects = new ArrayList<Integer>();
objects.add(new Integer(1));
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, objects);
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", objects);
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsNull() throws Exception {
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
List<Pair> concatStrings = apiClient.parameterToPairs("csv", "param-a", strs);
assertEquals(1, concatStrings.size());
assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters
}
@Test
public void testParameterToPairsWhenValueIsCollection() throws Exception {
Map<String, String> collectionFormatMap = new HashMap<String, String>();
collectionFormatMap.put("csv", ",");
collectionFormatMap.put("tsv", "\t");
collectionFormatMap.put("ssv", " ");
collectionFormatMap.put("pipes", "|");
collectionFormatMap.put("", ","); // no format, must default to csv
collectionFormatMap.put("unknown", ","); // all other formats, must default to csv
String name = "param-a";
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
assertEquals(values.size(), multiPairs.size());
for (int i = 0; i < values.size(); i++) {
assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), multiPairs.get(i).getValue());
}
// all other formats
for (String collectionFormat : collectionFormatMap.keySet()) {
List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values);
assertEquals(1, pairs.size());
String delimiter = collectionFormatMap.get(collectionFormat);
if (!delimiter.equals(",")) {
// commas are not escaped because they are reserved characters in URIs
delimiter = apiClient.escapeString(delimiter);
}
String[] pairValueSplit = pairs.get(0).getValue().split(delimiter);
// must equal input values
assertEquals(values.size(), pairValueSplit.length);
for (int i = 0; i < values.size(); i++) {
assertEquals(apiClient.escapeString(apiClient.parameterToString(values.get(i))), pairValueSplit[i]);
}
}
}
@Test
public void testSanitizeFilename() {
assertEquals("sun", apiClient.sanitizeFilename("sun"));
assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif"));
assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif"));
}
}

View File

@ -0,0 +1,201 @@
package org.openapitools.client;
import com.google.gson.reflect.TypeToken;
import org.openapitools.client.model.Order;
import java.lang.Exception;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import okio.ByteString;
import org.junit.*;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;
import static org.junit.Assert.*;
public class JSONTest {
private ApiClient apiClient = null;
private JSON json = null;
private Order order = null;
@Before
public void setup() {
apiClient = new ApiClient();
json = apiClient.getJSON();
order = new Order();
}
@Test
public void testSqlDateTypeAdapter() {
final String str = "\"2015-11-07\"";
final java.sql.Date date = java.sql.Date.valueOf("2015-11-07");
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, java.sql.Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString());
// custom date format: without day
DateFormat format = new SimpleDateFormat("yyyy-MM");
apiClient.setSqlDateFormat(format);
String dateStr = "\"2015-11\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class)));
}
@Test
public void testDateTypeAdapter() {
Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 300);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime());
cal.set(Calendar.MILLISECOND, 356);
Date date = cal.getTime();
final String utcDate = "\"2015-11-07T03:49:09.356Z\"";
assertEquals(json.deserialize(utcDate, Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date);
assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date);
assertEquals(utcDate, json.serialize(date));
// custom datetime format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
String dateStr = "\"2015-11-07T13:49:09+10:00\"";
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class)));
assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class)));
try {
// invalid time zone format
json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
try {
// unexpected miliseconds
json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class);
fail("json parsing should fail");
} catch (RuntimeException e) {
// OK
}
}
@Test
public void testOffsetDateTimeTypeAdapter() {
final String str = "\"2016-09-09T08:02:03.123-03:00\"";
OffsetDateTime date = OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3"));
assertEquals(str, json.serialize(date));
//Use toString() instead of isEqual to verify that the offset is preserved
assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString());
}
@Test
public void testLocalDateTypeAdapter() {
final String str = "\"2016-09-09\"";
final LocalDate date = LocalDate.of(2016, 9, 9);
assertEquals(str, json.serialize(date));
assertEquals(json.deserialize(str, LocalDate.class), date);
}
@Test
public void testDefaultDate() throws Exception {
final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.getType();
Order o = json.deserialize(str, type);
assertEquals(dateStr, datetimeFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM));
String str = json.serialize(order);
Type type = new TypeToken<Order>() { }.getType();
Order o = json.deserialize(str, type);
assertEquals(dateStr, datetimeFormat.format(o.getShipDate()));
}
@Test
public void testByteArrayTypeAdapterSerialization() {
// Arrange
final String expectedBytesAsString = "Let's pretend this a jpg or something";
final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8);
// Act
String serializedBytesWithQuotes = json.serialize(expectedBytes);
// Assert
String serializedBytes = serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1);
if (json.getGson().htmlSafe()) {
serializedBytes = serializedBytes.replaceAll("\\\\u003d", "=");
}
ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes);
byte[] actualBytes = actualAsByteString.toByteArray();
assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8));
}
@Test
public void testByteArrayTypeAdapterDeserialization() {
// Arrange
final String expectedBytesAsString = "Let's pretend this a jpg or something";
final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8);
final ByteString expectedByteString = ByteString.of(expectedBytes);
final String serializedBytes = expectedByteString.base64();
final String serializedBytesWithQuotes = "\"" + serializedBytes + "\"";
Type type = new TypeToken<byte[]>() { }.getType();
// Act
byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type);
// Assert
assertEquals(expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8));
}
// Obtained 22JAN2018 from stackoverflow answer by PuguaSoft https://stackoverflow.com/questions/11399491/java-timezone-offset
// Direct link https://stackoverflow.com/a/16680815/3166133
public static String getCurrentTimezoneOffset() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
}

View File

@ -0,0 +1,76 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
assertEquals(1, queryParams.size());
for (Pair queryParam : queryParams) {
assertEquals("my-api-key", queryParam.getValue());
}
// no changes to header parameters
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInQueryWithNullValue() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey(null);
auth.applyToParams(queryParams, headerParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
}
@Test
public void testApplyToParamsInHeaderWithNullValue() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey(null);
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
}
}

View File

@ -0,0 +1,62 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.openapitools.client.Pair;
import org.junit.*;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
assertEquals(expected, headerParams.get("Authorization"));
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization"));
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization"));
// null username and password should be ignored
queryParams = new ArrayList<Pair>();
headerParams = new HashMap<String, String>();
auth.setUsername(null);
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// no changes to parameters
assertEquals(0, queryParams.size());
assertEquals(0, headerParams.size());
}
}

View File

@ -0,0 +1,56 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.google.gson.Gson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
// test serialization
Gson gson = new Gson();
String json = gson.toJson(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":1,\"enum_number\":1.1}");
// test deserialization
EnumTest fromString = gson.fromJson(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumString().getValue(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertTrue(fromString.getEnumInteger().getValue() == 1);
assertEquals(fromString.getEnumNumber().toString(), "1.1");
assertTrue(fromString.getEnumNumber().getValue() == 1.1);
}
}

View File

@ -0,0 +1,254 @@
package org.openapitools.client;
import org.openapitools.client.auth.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.junit.*;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiClientTest {
ApiClient apiClient = null;
@Before
public void setup() {
apiClient = new ApiClient();
}
/**
*
*/
@Test
public void testParseAndFormatDate() {
// default date format
String dateStr = "2015-11-07T03:49:09.356Z";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));
// custom date format: without milli-seconds, custom time zone
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
apiClient.setDateFormat(format);
dateStr = "2015-11-07T13:49:09+10:00";
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
@Test
public void testIsJsonMime() {
assertFalse(apiClient.isJsonMime((String) null));
assertFalse(apiClient.isJsonMime(""));
assertFalse(apiClient.isJsonMime("text/plain"));
assertFalse(apiClient.isJsonMime("application/xml"));
assertFalse(apiClient.isJsonMime("application/jsonp"));
assertFalse(apiClient.isJsonMime("example/json"));
assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx"));
assertFalse(apiClient.isJsonMime("example/foo+bar+xjson"));
assertTrue(apiClient.isJsonMime("application/json"));
assertTrue(apiClient.isJsonMime("application/json; charset=UTF8"));
assertTrue(apiClient.isJsonMime("APPLICATION/JSON"));
assertTrue(apiClient.isJsonMime("application/problem+json"));
assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON"));
assertTrue(apiClient.isJsonMime("application/json\t"));
assertTrue(apiClient.isJsonMime("example/foo+bar+json"));
assertTrue(apiClient.isJsonMime("example/foo+json;x;y"));
assertTrue(apiClient.isJsonMime("example/foo+json\t;"));
assertTrue(apiClient.isJsonMime("Example/fOO+JSON"));
}
@Test
public void testSelectHeaderAccept() {
String[] accepts = {"application/json", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"};
assertEquals(Arrays.asList(MediaType.parseMediaType("APPLICATION/JSON")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(Arrays.asList(MediaType.parseMediaType("application/json; charset=UTF8")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{"text/plain", "application/xml"};
assertEquals(Arrays.asList(MediaType.parseMediaType("text/plain"),MediaType.parseMediaType("application/xml")), apiClient.selectHeaderAccept(accepts));
accepts = new String[]{};
assertNull(apiClient.selectHeaderAccept(accepts));
}
@Test
public void testSelectHeaderContentType() {
String[] contentTypes = {"application/json", "application/xml"};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"};
assertEquals(MediaType.parseMediaType("APPLICATION/JSON"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"};
assertEquals(MediaType.parseMediaType("application/json; charset=UTF8"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{"text/plain", "application/xml"};
assertEquals(MediaType.parseMediaType("text/plain"), apiClient.selectHeaderContentType(contentTypes));
contentTypes = new String[]{};
assertEquals(MediaType.parseMediaType("application/json"), apiClient.selectHeaderContentType(contentTypes));
}
@Test
public void testGetAuthentications() {
Map<String, Authentication> auths = apiClient.getAuthentications();
Authentication auth = auths.get("api_key");
assertNotNull(auth);
assertTrue(auth instanceof ApiKeyAuth);
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
assertEquals("header", apiKeyAuth.getLocation());
assertEquals("api_key", apiKeyAuth.getParamName());
auth = auths.get("petstore_auth");
assertTrue(auth instanceof OAuth);
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
assertNull(auths.get("unknown"));
try {
auths.put("my_auth", new HttpBasicAuth());
fail("the authentications returned should not be modifiable");
} catch (UnsupportedOperationException e) {
}
}
@Ignore("There is no more basic auth in petstore security definitions")
@Test
public void testSetUsernameAndPassword() {
HttpBasicAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof HttpBasicAuth) {
auth = (HttpBasicAuth) _auth;
break;
}
}
auth.setUsername(null);
auth.setPassword(null);
apiClient.setUsername("my-username");
apiClient.setPassword("my-password");
assertEquals("my-username", auth.getUsername());
assertEquals("my-password", auth.getPassword());
// reset values
auth.setUsername(null);
auth.setPassword(null);
}
@Test
public void testSetApiKeyAndPrefix() {
ApiKeyAuth auth = null;
for (Authentication _auth : apiClient.getAuthentications().values()) {
if (_auth instanceof ApiKeyAuth) {
auth = (ApiKeyAuth) _auth;
break;
}
}
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
apiClient.setApiKey("my-api-key");
apiClient.setApiKeyPrefix("Token");
assertEquals("my-api-key", auth.getApiKey());
assertEquals("Token", auth.getApiKeyPrefix());
// reset values
auth.setApiKey(null);
auth.setApiKeyPrefix(null);
}
@Test
public void testParameterToMultiValueMapWhenNameIsInvalid() throws Exception {
MultiValueMap<String, String> pairs_a = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, null, new Integer(1));
MultiValueMap<String, String> pairs_b = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "", new Integer(1));
assertTrue(pairs_a.isEmpty());
assertTrue(pairs_b.isEmpty());
}
@Test
public void testParameterToMultiValueMapWhenValueIsNull() throws Exception {
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", null);
assertTrue(pairs.isEmpty());
}
@Test
public void testParameterToMultiValueMapWhenValueIsEmptyStrings() throws Exception {
// single empty string
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", " ");
assertEquals(1, pairs.size());
// list of empty strings
List<String> strs = new ArrayList<String>();
strs.add(" ");
strs.add(" ");
strs.add(" ");
MultiValueMap<String, String> concatStrings = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, "param-a", strs);
assertEquals(1, concatStrings.get("param-a").size());
assertFalse(concatStrings.get("param-a").isEmpty()); // should contain some delimiters
}
@Test
public void testParameterToMultiValueMapWhenValueIsNotCollection() throws Exception {
String name = "param-a";
Integer value = 1;
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.CSV, name, value);
assertEquals(1, pairs.get(name).size());
assertEquals(value, Integer.valueOf(pairs.get(name).get(0)));
}
@Test
public void testParameterToMultiValueMapWhenValueIsCollection() throws Exception {
Map<ApiClient.CollectionFormat, String> collectionFormatMap = new HashMap<ApiClient.CollectionFormat, String>();
collectionFormatMap.put(ApiClient.CollectionFormat.CSV, ",");
collectionFormatMap.put(ApiClient.CollectionFormat.TSV, "\t");
collectionFormatMap.put(ApiClient.CollectionFormat.SSV, " ");
collectionFormatMap.put(ApiClient.CollectionFormat.PIPES, "\\|");
collectionFormatMap.put(null, ","); // no format, must default to csv
String name = "param-a";
List<Object> values = new ArrayList<Object>();
values.add("value-a");
values.add(123);
values.add(new Date());
// check for multi separately
MultiValueMap<String, String> multiValueMap = apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.MULTI, name, values);
assertEquals(values.size(), multiValueMap.get(name).size());
// all other formats
for (ApiClient.CollectionFormat collectionFormat : collectionFormatMap.keySet()) {
MultiValueMap<String, String> pairs = apiClient.parameterToMultiValueMap(collectionFormat, name, values);
assertEquals(1, pairs.size());
String delimiter = collectionFormatMap.get(collectionFormat);
String[] pairValueSplit = pairs.get(name).get(0).split(delimiter);
assertEquals(values.size(), pairValueSplit.length);
}
}
}

View File

@ -0,0 +1,47 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class ApiKeyAuthTest {
@Test
public void testApplyToParamsInQuery() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
auth.setApiKey("my-api-key");
auth.applyToParams(queryParams, headerParams);
assertEquals(1, queryParams.size());
assertEquals("my-api-key", queryParams.get("api_key").get(0));
// no changes to header parameters
assertEquals(0, headerParams.size());
}
@Test
public void testApplyToParamsInHeaderWithPrefix() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
auth.setApiKey("my-api-token");
auth.setApiKeyPrefix("Token");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0));
}
}

View File

@ -0,0 +1,54 @@
package org.openapitools.client.auth;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.junit.*;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
public class HttpBasicAuthTest {
HttpBasicAuth auth = null;
@Before
public void setup() {
auth = new HttpBasicAuth();
}
@Test
public void testApplyToParams() {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
HttpHeaders headerParams = new HttpHeaders();
auth.setUsername("my-username");
auth.setPassword("my-password");
auth.applyToParams(queryParams, headerParams);
// no changes to query parameters
assertEquals(0, queryParams.size());
assertEquals(1, headerParams.size());
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
assertEquals(expected, headerParams.get("Authorization").get(0));
// null username should be treated as empty string
auth.setUsername(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
expected = "Basic Om15LXBhc3N3b3Jk";
assertEquals(expected, headerParams.get("Authorization").get(1));
// null password should be treated as empty string
auth.setUsername("my-username");
auth.setPassword(null);
auth.applyToParams(queryParams, headerParams);
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
expected = "Basic bXktdXNlcm5hbWU6";
assertEquals(expected, headerParams.get("Authorization").get(2));
}
}

View File

@ -0,0 +1,63 @@
package org.openapitools.client.model;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class EnumValueTest {
@Test
public void testEnumClass() {
assertEquals(EnumClass._ABC.toString(), "_abc");
assertEquals(EnumClass._EFG.toString(), "-efg");
assertEquals(EnumClass._XYZ_.toString(), "(xyz)");
}
@Test
public void testEnumTest() {
// test enum value
EnumTest enumTest = new EnumTest();
enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);
assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);
try {
// test serialization (object => json)
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
ObjectWriter ow = mapper.writer();
String json = ow.writeValueAsString(enumTest);
assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");
// test deserialization (json => object)
EnumTest fromString = mapper.readValue(json, EnumTest.class);
assertEquals(fromString.getEnumString().toString(), "lower");
assertEquals(fromString.getEnumInteger().toString(), "1");
assertEquals(fromString.getEnumNumber().toString(), "1.1");
} catch (Exception e) {
fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
}
}
}

View File

@ -2,7 +2,7 @@
<div align="center">
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`3.0.2-SNAPSHOT`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`3.0.3-SNAPSHOT`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator)
[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator)
[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator)
[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu)
@ -36,6 +36,9 @@
:warning: If the OpenAPI spec is obtained from an untrusted source, please make sure you've reviewed the spec before using OpenAPI Generator to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning:
:bangbang: Both "OpenAPI Tools" (https://OpenAPITools.org - the parent organization of OpenAPI Generator) and "OpenAPI Generator" are not affiliated with OpenAPI Initiative (OAI) :bangbang:
</div>
## Overview
@ -43,7 +46,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| | Languages/Frameworks |
|-|-|
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 6.x), Aurelia, Fetch, Inversify, jQuery, Node)
**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C#** (.net 2.0, 3.5 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured), **Kotlin**, **Lua**, **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types) **Objective-C**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x), **Typescript** (AngularJS, Angular (2.x - 6.x), Aurelia, Fetch, Inversify, jQuery, Node)
**Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed), **Erlang**, **Go**, **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples)), **Kotlin**, **PHP** (Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), Scalatra)
**API documentation generators** | **HTML**, **Confluence Wiki**
**Configuration files** | [**Apache2**](https://httpd.apache.org/)
@ -85,9 +88,10 @@ OpenAPI Generator Version | Release Date | OpenAPI Spec compatibility | Notes
---------------------------- | ------------ | -------------------------- | -----
4.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/4.0.0-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2, 2.0, 3.0 | Major release with breaking changes (no fallback)
3.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.1.0-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2, 2.0, 3.0 | Minor release with breaking changes (with fallbacks)
3.0.2 (current master, upcoming release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.0.2-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2,
3.0.1 | 11.06.2018 | 1.0, 1.1, 1.2, 2.0, 3.0 | Bugfix release
3.0.0 | 01.06.2018 | 1.0, 1.1, 1.2, 2.0, 3.0 | First release with breaking changes
3.0.3 (current master, upcoming release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/3.1.0-SNAPSHOT/)| TBD | 1.0, 1.1, 1.2,
[3.0.2](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.0.2) | 18.06.2018 | 1.0, 1.1, 1.2, 2.0, 3.0 | Bugfix release
[3.0.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.0.1) | 11.06.2018 | 1.0, 1.1, 1.2, 2.0, 3.0 | Bugfix release
[3.0.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v3.0.0) | 01.06.2018 | 1.0, 1.1, 1.2, 2.0, 3.0 | First release with breaking changes
### [1.2 - Artifacts on Maven Central](#table-of-contents)
@ -143,12 +147,12 @@ JAR location: `http://central.maven.org/maven2/org/openapitools/openapi-generato
For **Mac/Linux** users:
```sh
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.0.1/openapi-generator-cli-3.0.1.jar -O openapi-generator-cli.jar
wget http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.0.2/openapi-generator-cli-3.0.2.jar -O openapi-generator-cli.jar
```
For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.
```
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.0.1/openapi-generator-cli-3.0.1.jar
Invoke-WebRequest -OutFile openapi-generator-cli.jar http://central.maven.org/maven2/org/openapitools/openapi-generator-cli/3.0.2/openapi-generator-cli-3.0.2.jar
```
After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage.
@ -179,13 +183,15 @@ If you don't have maven installed, you may directly use the included [maven wrap
### [1.5 - Homebrew](#table-of-contents)
To install, run `brew install openapi-generator` (the new brew formula is pending https://github.com/Homebrew/homebrew-core/pull/28584)
To install, run `brew install openapi-generator`
Here is an example usage to generate a Ruby client:
```sh
openapi-generator generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g ruby -o /tmp/test/
```
To reinstall with the latest master, run `brew reinstall --HEAD openapi-generator`
### [1.6 - Docker](#table-of-contents)
#### Public Pre-built Docker images
@ -410,6 +416,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [GMO Pepabo](https://pepabo.com/en/)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
- [REST United](https://restunited.com)
- [Telstra](https://dev.telstra.com)
- [unblu inc.](https://www.unblu.com/)
@ -470,6 +477,7 @@ Here is a list of template creators:
* Java (Rest-assured): @viclovsky
* Javascript/NodeJS: @jfiala
* Javascript (Closure-annotated Angular) @achew22
* Javascript (Flow types) @jaypea
* JMeter: @davidkiss
* Kotlin: @jimschubert
* Lua: @daurnimator

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-qt5 -o samples/client/petstore/cpp-qt5 $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-qt5 -o samples/client/petstore/cpp-qt5 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/cpprest -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-restsdk -o samples/client/petstore/cpp-restsdk $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-rest-sdk-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-restsdk -o samples/client/petstore/cpp-restsdk $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/tizen -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-tizen -o samples/client/petstore/cpp-tizen $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-tizen-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g cpp-tizen -o samples/client/petstore/cpp-tizen $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -33,3 +33,8 @@ echo "Removing files and folders under samples/client/petstore/java/feign/src/ma
rm -rf samples/client/petstore/java/feign/src/main
find samples/client/petstore/java/feign -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/feign/src/test/java/org/openapitools/client
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/feign/src/test/java/org/openapitools/client/StringUtilTest.java

View File

@ -33,3 +33,15 @@ echo "Removing files and folders under samples/client/petstore/java/jersey1/src/
rm -rf samples/client/petstore/java/jersey1/src/main
find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/ApiClientTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey1/model/EnumValueTest.java samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/model/EnumValueTest.java

View File

@ -29,7 +29,7 @@ fi
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate --artifact-id petstore-jersey2-java6 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2-java6 -DhideGenerationTimestamp=true,supportJava6=true $@"
echo "Removing files and folders under samples/client/petstore/java/jersey2/src/main"
echo "Removing files and folders under samples/client/petstore/java/jersey2-java6/src/main"
rm -rf samples/client/petstore/java/jersey2-java6/src/main
find samples/client/petstore/java/jersey2-java6 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

View File

@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2/src/
rm -rf samples/client/petstore/java/jersey2/src/main
find samples/client/petstore/java/jersey2 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/JSONTest.java samples/client/petstore/java/jersey2/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -32,3 +32,16 @@ ags="generate -t modules/openapi-generator/src/main/resources/Java/libraries/okh
rm -rf samples/client/petstore/java/okhttp-gson/src/main
find samples/client/petstore/java/okhttp-gson -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/ApiClientTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/ApiKeyAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/auth/HttpBasicAuthTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/model/EnumValueTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/okhttp-gson/JSONTest.java samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -33,3 +33,13 @@ echo "Removing files and folders under samples/client/petstore/java/resttemplate
rm -rf samples/client/petstore/java/resttemplate/src/main
find samples/client/petstore/java/resttemplate -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/ApiClientTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/ApiKeyAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/auth/HttpBasicAuthTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/resttemplate/model/EnumValueTest.java samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/model/EnumValueTest.java

View File

@ -33,3 +33,16 @@ echo "Removing files and folders under samples/client/petstore/java/jersey2-java
rm -rf samples/client/petstore/java/jersey2-java8/src/main
find samples/client/petstore/java/jersey2-java8 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags
# copy additional manually written unit-tests
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth
mkdir samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model
cp CI/samples.ci/client/petstore/java/test-manual/common/StringUtilTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/StringUtilTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/ApiClientTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java
cp CI/samples.ci/client/petstore/java/test-manual/common/ConfigurationTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ConfigurationTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/ApiKeyAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/auth/HttpBasicAuthTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2/model/EnumValueTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/model/EnumValueTest.java
cp CI/samples.ci/client/petstore/java/test-manual/jersey2-java8/JSONTest.java samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/Javascript-Flowtyped -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g javascript-flowtyped -o samples/client/petstore/javascript-flowtyped -DappName=PetstoreClient $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g cpp-qt5 -o samples/client/petstore/cpp-qt5 $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g cpp-qt5 -o samples/client/petstore/cpp-qt5 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/tizen -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g cpp-tizen -o samples/client/petstore/cpp-tizen $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-tizen-client -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g cpp-tizen -o samples/client/petstore/cpp-tizen $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/akka-scala -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g akka-scala -o samples/client/petstore/akka-scala $@"
ags="generate --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/scala-akka-client -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g akka-scala -o samples/client/petstore/scala-akka $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/scala -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g scala -o samples/client/petstore/scala $@"
ags="generate -t modules/openapi-generator/src/main/resources/scala-httpclient -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g scala -o samples/client/petstore/scala-httpclient $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/slim -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g php-slim -o samples/server/petstore/php-slim $@"
ags="generate -t modules/openapi-generator/src/main/resources/slim -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim -o samples/server/petstore/php-slim $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/akka-scala -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g scala-akka -o samples/client/petstore/akka-scala $@"
ags="generate --artifact-id "scala-akka-petstore-client" -t modules/openapi-generator/src/main/resources/scala-akka-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g scala-akka -o samples/client/petstore/scala-akka $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/scala -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g scala-httpclient -o samples/client/petstore/scala $@"
ags="generate -t modules/openapi-generator/src/main/resources/scala-httpclient -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g scala-httpclient -o samples/client/petstore/scala-httpclient $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules/openapi-generator/src/test/resources/2_0/petstore-security-test.yaml -g cpp-qt5 -o samples/client/petstore-security-test/cpp-qt5 $@"
ags="generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules/openapi-generator/src/test/resources/2_0/petstore-security-test.yaml -g cpp-qt5 -o samples/client/petstore-security-test/cpp-qt5 $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/scala -i modules/openapi-generator/src/test/resources/2_0/petstore-security-test.yaml -g scala-httpclient -o samples/client/petstore-security-test/scala $@"
ags="generate -t modules/openapi-generator/src/main/resources/scala-httpclient -i modules/openapi-generator/src/test/resources/2_0/petstore-security-test.yaml -g scala-httpclient -o samples/client/petstore-security-test/scala-httpclient $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -t modules/openapi-generator/src/main/resources/qt5cpp -i modules\openapi-generator\src\test\resources\2_0\petstore-security-test.yaml -g qt5cpp -o samples\client\petstore-security-test\qt5cpp
set ags=generate -t modules/openapi-generator/src/main/resources/cpp-qt5-client -i modules\openapi-generator\src\test\resources\2_0\petstore-security-test.yaml -g qt5cpp -o samples\client\petstore-security-test\qt5cpp
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -4,3 +4,4 @@
./bin/swift4-petstore-promisekit.sh
./bin/swift4-petstore-rxswift.sh
./bin/swift4-petstore-objcCompatible.sh
./bin/swift4-petstore-unwrapRequired.sh

View File

@ -0,0 +1,7 @@
{
"podSummary": "PetstoreClient",
"podHomepage": "https://github.com/openapitools/openapi-generator",
"podAuthors": "",
"projectName": "PetstoreClient",
"unwrapRequired": true
}

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/swift4 -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g swift4 -c ./bin/swift4-petstore-unwrapRequired.json -o samples/client/petstore/swift4/unwrapRequired $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -1,6 +1,6 @@
#!/bin/bash
# this bash script run the scripts for the 'mature' generators
# it ensures that all changes are commited into the 'samples/' folder
# it ensures that all changes are committed into the 'samples/' folder
echo "# START SCRIPT: $0"

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g php-slim -o samples\server\petstore\php-slim
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g php-slim -o samples\server\petstore\php-slim
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate --artifact-id "scala-akka-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g scala-akka -o samples\client\petstore\akka-scala
set ags=generate --artifact-id "scala-akka-petstore-client" -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g scala-akka -o samples\client\petstore\scala-akka
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g scala-httpclient -o samples\client\petstore\scala
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g scala-httpclient -o samples\client\petstore\scala-httpclient
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -1,54 +1,93 @@
# Java-related client, server tests
version: 2
jobs:
build:
machine:
java:
version: openjdk8
services:
- docker
# Override /etc/hosts
hosts:
petstore.swagger.io: 127.0.0.1
docker_layer_caching: true
working_directory: ~/OpenAPITools/openapi-generator
parallelism: 1
shell: /bin/bash --login
environment:
CIRCLE_ARTIFACTS: /tmp/circleci-artifacts
CIRCLE_TEST_REPORTS: /tmp/circleci-test-results
DOCKER_GENERATOR_IMAGE_NAME: openapitools/openapi-generator
DOCKER_CODEGEN_CLI_IMAGE_NAME: openapitools/openapi-generator-cli
dependencies:
cache_directories:
- "~/.m2"
- "~/.sbt"
- "~/.ivy2"
pre:
- sudo add-apt-repository ppa:duggan/bats --yes
- sudo apt-get update -qq
- sudo apt-get install -qq bats
- sudo apt-get install -qq curl
# to run petstore server locally via docker
- docker pull swaggerapi/petstore
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- docker ps -a
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /etc/hosts
override:
- cp CI/pom.xml.circleci pom.xml
test:
override:
## test with jdk8
- java -version
- mvn --quiet clean install
- mvn --quiet verify -Psamples
# skip the rest if previous mvn task fails
- if [ $? -ne 0 ]; then exit 1; fi
## test with jdk7
- sudo update-java-alternatives -s java-1.7.0-openjdk-amd64
- java -version
- cp CI/pom.xml.circleci.java7 pom.xml # use jdk7 pom
- mvn --quiet clean install
- mvn --quiet verify -Psamples
# skip the rest if previous mvn task fails
- if [ $? -ne 0 ]; then exit 1; fi
## docker push done in Travis instead
## docker: build generator image and push to Docker Hub
#- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build --rm=false -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/opeanapi-generator && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_GENERATOR_IMAGE_NAME; fi; fi
### docker: build cli image and push to Docker Hub
#- if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build --rm=false -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli && if [ ! -z "$CIRCLE_TAG" ]; then docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$CIRCLE_TAG; fi && if [ ! -z "$CIRCLE_TAG" ] || [ "$CIRCLE_BRANCH" = "master" ]; then docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; fi; fi
steps:
# Machine Setup
# If you break your build into multiple jobs with workflows, you will probably want to do the parts of this that are relevant in each
# The following `checkout` command checks out your code to your working directory. In 1.0 we did this implicitly. In 2.0 you can choose where in the course of a job your code should be checked out.
- checkout
# Prepare for artifact and test results collection equivalent to how it was done on 1.0.
# In many cases you can simplify this from what is generated here.
# 'See docs on artifact collection here https://circleci.com/docs/2.0/artifacts/'
- run: mkdir -p $CIRCLE_ARTIFACTS $CIRCLE_TEST_REPORTS
# This is based on your 1.0 configuration file or project settings
- run:
command: sudo update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java; sudo update-alternatives --set javac /usr/lib/jvm/java-8-openjdk-amd64/bin/javac; echo -e "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64" >> $BASH_ENV
- run:
command: 'sudo docker info >/dev/null 2>&1 || sudo service docker start; '
- run:
command: |-
printf '127.0.0.1 petstore.swagger.io
' | sudo tee -a /etc/hosts
# Dependencies
# This would typically go in either a build or a build-and-test job when using workflows
# Restore the dependency cache
- restore_cache:
keys:
# This branch if available
- v1-dep-{{ .Branch }}-
# Default branch if not
- v1-dep-master-
# This is based on your 1.0 configuration file or project settings
- run: sudo add-apt-repository ppa:duggan/bats --yes
- run: sudo apt-get update -qq
- run: sudo apt-get install -qq bats
- run: sudo apt-get install -qq curl
# - run: docker pull openapitools/openapi-petstore
# - run: docker run -d -e OPENAPI_BASE_PATH=/v3 -e DISABLE_API_KEY=1 -e DISABLE_OAUTH=1 -p 80:8080 openapitools/openapi-petstore
- run: docker pull swaggerapi/petstore
- run: docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- run: docker ps -a
- run: sleep 30
- run: cat /etc/hosts
# This is based on your 1.0 configuration file or project settings
- run: cp CI/pom.xml.circleci pom.xml
# Save dependency cache
- save_cache:
key: v1-dep-{{ .Branch }}
paths:
# This is a broad list of cache paths to include many possible development environments
# You can probably delete some of these entries
- vendor/bundle
- ~/virtualenvs
- ~/.m2
- ~/.ivy2
- ~/.bundle
- ~/.go_workspace
- ~/.gradle
- ~/.cache/bower
# These cache paths were specified in the 1.0 config
- ~/.sbt
# Test
# This would typically be a build job when using workflows, possibly combined with build
# This is based on your 1.0 configuration file or project settings
- run: java -version
- run: mvn --quiet clean install
- run: mvn --quiet verify -Psamples
- run: if [ $? -ne 0 ]; then exit 1; fi
- run: sudo update-java-alternatives -s java-1.7.0-openjdk-amd64
- run: java -version
- run: cp CI/pom.xml.circleci.java7 pom.xml
- run: mvn --quiet clean install
- run: mvn --quiet verify -Psamples
- run: if [ $? -ne 0 ]; then exit 1; fi
# Teardown
# If you break your build into multiple jobs with workflows, you will probably want to do the parts of this that are relevant in each
# Save test results
- store_test_results:
path: /tmp/circleci-test-results
# Save artifacts
- store_artifacts:
path: /tmp/circleci-artifacts
- store_artifacts:
path: /tmp/circleci-test-results

View File

@ -166,7 +166,7 @@ cf8d8d56f [PHP] Fix code example from README. Variable name was missing when usi
76907cacd [PHP] declare property headerSelector
### Python
7184f1ec6 [python] asyncio supports _preload_content; remove unsed imports (#107)
7184f1ec6 [python] asyncio supports _preload_content; remove unused imports (#107)
d74d2ba03 fix: python clients
8e0a0ebd6 Fix python / tornado body handling
b39c35c76 Fix inconsistency between model name and file name in python client
@ -250,7 +250,7 @@ ce930e7a6 [Jaxrs-cxf] Add bean-level cascaded beanvalidation for pojos (@Valid)
ff1178ad7 [Java][Spring] fix missing optional query params
2103fadab Fix package declaration for play-framework
2c6380c84 fix inner item (list, map) for play framework
e33b350c8 Fix an issue in Play Framework generator where a CSV is empty and transfered to the controllerImp with an empty item.
e33b350c8 Fix an issue in Play Framework generator where a CSV is empty and transferred to the controllerImp with an empty item.
99fc27246 [JAX-RS][Spec] Removes throws Exception.
fe2a44339 Fixes issue (SpringCodeGen dateLibrary "java8-localdatetime" option is ignored).
d890d733f [JaxRS][Java] issue with implFolder on windows, and required fields generation for containers (#88)

View File

@ -16,6 +16,8 @@ There are several reasons:
1. According to SmartBear, [Swagger Codegen 2.x and 3.x should be supported in parallel for a while](https://github.com/swagger-api/swagger-codegen/issues/7754#issuecomment-375039048) without the possibility to work with git branches to merge the fixes from one branch to the next. Having to implement everything twice is not a good idea and the best use of the Swagger Codegen community resources.
1. Having a community-driven version can bring the project to the next level.
UPDATE: After the public launch of OpenAPI Generator, some of the core team members were contacted by Ron (SmartBear) and we explained to him the reasons of the fork as explained above. We also asked him to contact team@openapitools.org if he wants to discuss further but so far we don't see any email from him to team@openapitools.org.
#### Has anything been done in attempt to address the issues before deciding to fork Swagger Codegen and maintain a community-driven version?
There were several conversations with SmartBear (Ron, Hugo) via emails, gitter, Skype call and GitHub issues.

79
docs/roadmap.adoc Normal file
View File

@ -0,0 +1,79 @@
== Roadmap
This document lists short-term, medium-term, and long-term goals for the project.
[NOTE]
====
These are goals, not necessarily commitments. The sections are not intended to represent exclusive focus during these terms. For example, when you start at a college or university you may have a long-term goal to graduate and a short-term goal to find a job for supplemental income. We will similarly work toward many of our medium-term and long-term goals in the near future as we move toward meeting our short-term goals.
====
=== Short-term
> Usability, stability, and marketing.
Short term are focused on improving contributor and user productivity (part of this is getting the word out).
* CLI improvements
** Search functionality (e.g. what generators support retrofit, what generators are available for kotlin)
* Build automation improvements
** Discuss consolidating current third-party build systems
** Investigate custom docker containerization for prepared build environments
** Automated release stability
* General
** OAS3.0 features support: anyOf, oneOf, callbacks, etc
** Consider opt-in telemetry about generators being used, limited to a counter of invocations by generator name). This would allow us to make prioritization decisions based on statistics.
** Code clean up
*** centralize build scripts
*** organize samples/bin scripts according to new generator names
*** consolidate typescript generators
*** jaxrs => use Swagger core v3 (see https://github.com/OpenAPITools/openapi-generator/issues/27[#27])
* Documentation
** Static pages, preferably on gh-pages, devoted to each generator
** Explain generator options
** Centralized docs on generated code usage/examples/configuration
=== Medium-term
> Feature set, well-defined API (code and templates), and extensibility improvements.
* API
** Typed representation of the model bound to our templates. As it is, everything is treated an an Object, and this can lead to changes in the interface which might be unexpected from the template perspective.
* Feature set (potential generators to add; not an exhaustive list)
** Azure functions (node.js, server)
** Finagle HTTP Client (Scala, client)
** Finagle Http Server (Scala, server)
** Finatra (Scala, server)
** Kotlin Spring MVC/Springboot (server)
** C++ Server, any framework (server)
* General
** Migrate from Maven to Gradle
** Java 9+ support
* Feature set (other options to investigate)
** SPI plugins
*** Templating engine
*** Language extensions
*** Custom extensions (e.g. allowing users to load support for https://github.com/Azure/azure-rest-api-specs[azure-rest-api-specs])
** Customizable templating engines (handlebars support)
** Unit-testing templates (to previously mentioned explicit type as an interface to the template)
* Reduce coupling
** Make types extending `CodegenConfig` become the generation entrypoint
** Allow current `CodegenConfig` types to define templating engine
** Allow current `CodegenConfig` types to modify workflow (currently encapsulated in `DefaultGenerator` and tightly coupled to the template engine
** Clearer reuse of "language" features, outside of "generator" types. That is, rather than enforcing polymorphic sharing of "language" which currently allows the super type to redefine framework-specific mapping functionality, generators could compose one or more language support types.
* Define template deprecation/removal process
=== Long-term
> Expanding tooling offered, integrations, potentially SaaS offering to partially fund efforts.
* Generator UI wrappers
** Move jimschubert/intellij-swagger-codegen plugin under the org, and rename
** Look into an Eclipse UI wrapper around the generator
** Look at Visual Studio Code (and/or Atom, sublime text) integration
* Provide a native GUI for viewing/editing specs. Most tools are currently geared toward developers, but often times it may be non-technical business users who are interested in an API.
* A paid service (SaaS) for generation may be enticing for some users. Such a service would allow for statistics (mentioned earlier in telemetry)
* Additional tools
** node.js build system(s) integration (grunt/gulp/webpack/etc)
** ruby gem
** others (which may require previously mentioned SaaS API)

View File

@ -21,7 +21,9 @@ import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import org.openapitools.codegen.utils.ModelUtils;
import java.util.HashSet;
import java.util.List;
@ -34,26 +36,58 @@ public class Validate implements Runnable {
description = "location of the OpenAPI spec, as URL or file (required)")
private String spec;
@Option(name = { "--recommend"}, title = "recommend spec improvements")
private Boolean recommend;
@Override
public void run() {
System.out.println("Validating spec (" + spec + ")");
SwaggerParseResult result = new OpenAPIParser().readLocation(spec, null, null);
List<String> messageList = result.getMessages();
Set<String> messages = new HashSet<String>(messageList);
Set<String> errors = new HashSet<String>(messageList);
Set<String> warnings = new HashSet<String>();
if (messages.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append(System.lineSeparator());
for (String message : messages) {
sb.append(String.format("\t- %s%s", message, System.lineSeparator()));
OpenAPI specification = result.getOpenAPI();
if (Boolean.TRUE.equals(recommend)) {
if (specification != null) {
// Add information about unused models to the warnings set.
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
if (unusedModels != null) {
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
}
}
}
if (errors.size() > 0) {
sb.append("Errors:").append(System.lineSeparator());
errors.forEach(msg ->
sb.append("\t-").append(msg).append(System.lineSeparator())
);
}
if (!warnings.isEmpty()) {
sb.append("Warnings: ").append(System.lineSeparator());
warnings.forEach(msg ->
sb.append("\t-").append(msg).append(System.lineSeparator())
);
}
if (!errors.isEmpty()) {
sb.append(System.lineSeparator());
sb.append("[error] Spec is invalid.");
sb.append("[error] Spec has ").append(errors.size()).append(" errors.");
System.err.println(sb.toString());
System.exit(1);
} else if (!warnings.isEmpty()) {
sb.append(System.lineSeparator());
sb.append("[info] Spec has ").append(warnings.size()).append(" recommendation(s).");
} else {
System.out.println("No validation errors detected.");
}
// we say "issues" here rather than "errors" to account for both errors and issues.
sb.append("No validation issues detected.");
}
System.out.println(sb.toString());
}
}

View File

@ -34,7 +34,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:3.0.1"
classpath "org.openapitools:openapi-generator-gradle-plugin:3.0.2"
}
}

View File

@ -13,6 +13,9 @@
<name>openapi-generator-gradle-plugin (maven wrapper)</name>
<description>This is a maven wrapper to call gradle during installation phase</description>
<properties>
<skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo>
</properties>
<dependencies>
<dependency>
@ -23,19 +26,28 @@
</dependencies>
<build>
<plugins>
<!-- NOTE: Consider this temporary, as a way to cleanly hook into our pipeline.
We've discussed moving the entire project to gradle https://github.com/OpenAPITools/openapi-generator/issues/200, which would avoid this fitting. -->
<pluginManagement>
<plugins>
<!-- 1) disable maven install. This wrapper is not needed. (gradle will install a jar and a pom into the local maven repo) -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<!-- 3) disable maven deploy. This wrapper is not needed. -->
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<!-- 2) run gradle -->
<plugin>
<groupId>org.fortasoft</groupId>
@ -65,15 +77,6 @@
</execution>
</executions>
</plugin>
<!-- 3) disable maven deploy. This wrapper is not needed. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -16,5 +16,5 @@ gradle buildGoSdk
The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example:
```bash
gradle -PopenApiGeneratorVersion=3.0.1 openApiValidate
gradle -PopenApiGeneratorVersion=3.0.2 openApiValidate
```

View File

@ -11,7 +11,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase)
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>3.0.1</version>
<version>3.0.2</version>
<executions>
<execution>
<goals>

View File

@ -1 +1 @@
3.0.0-SNAPSHOT
3.0.1-SNAPSHOT

View File

@ -10,6 +10,6 @@ This is an example of building a OpenAPI-enabled server in Java using the Spring
The underlying library integrating OpenAPI to SpringBoot is [springfox](https://github.com/springfox/springfox)
Start your server as an simple java application
Start your server as a simple java application
Change default port value in application.properties

View File

@ -210,7 +210,7 @@ public class DefaultCodegen implements CodegenConfig {
for (String name : allModels.keySet()) {
CodegenModel cm = allModels.get(name);
CodegenModel parent = allModels.get(cm.getParent());
// if a discriminator exists on the parent, don't add this child to the inheritance heirarchy
// if a discriminator exists on the parent, don't add this child to the inheritance hierarchy
// TODO Determine what to do if the parent discriminator name == the grandparent discriminator name
while (parent != null) {
if (parent.getChildren() == null) {
@ -1201,7 +1201,7 @@ public class DefaultCodegen implements CodegenConfig {
*/
private static String getPrimitiveType(Schema schema) {
if (schema == null) {
throw new RuntimeException("schema cannnot be null in getPrimitiveType");
throw new RuntimeException("schema cannot be null in getPrimitiveType");
} else if (ModelUtils.isStringSchema(schema) && "number".equals(schema.getFormat())) {
// special handle of type: string, format: number
return "BigDecimal";
@ -1300,7 +1300,7 @@ public class DefaultCodegen implements CodegenConfig {
/**
* Determine the type alias for the given type if it exists. This feature
* was original developed for Java because the language does not have a aliasing
* was originally developed for Java because the language does not have an aliasing
* mechanism of its own but later extends to handle other languages
*
* @param name The type name.
@ -1383,6 +1383,9 @@ public class DefaultCodegen implements CodegenConfig {
typeAliases = getAllAliases(allDefinitions);
}
// unalias schema
schema = ModelUtils.unaliasSchema(allDefinitions, schema);
CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL);
if (reservedWords.contains(name)) {
@ -1508,9 +1511,8 @@ public class DefaultCodegen implements CodegenConfig {
addProperties(allProperties, allRequired, child, allDefinitions);
}
}
addVars(m, properties, required, allProperties, allRequired);
// TODO
//} else if (schema instanceof RefModel) {
addVars(m, unaliasPropertySchema(allDefinitions, properties), required, allProperties, allRequired);
} else {
m.dataType = getSchemaType(schema);
if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
@ -1522,7 +1524,7 @@ public class DefaultCodegen implements CodegenConfig {
if (ModelUtils.isMapSchema(schema)) {
addAdditionPropertiesToCodeGenModel(m, schema);
}
addVars(m, schema.getProperties(), schema.getRequired());
addVars(m, unaliasPropertySchema(allDefinitions, schema.getProperties()), schema.getRequired());
}
if (m.vars != null) {
@ -1591,7 +1593,6 @@ public class DefaultCodegen implements CodegenConfig {
return null;
}
LOGGER.debug("debugging fromProperty for " + name + " : " + p);
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
property.name = toVarName(name);
property.baseName = name;
@ -1832,7 +1833,6 @@ public class DefaultCodegen implements CodegenConfig {
// property.baseType = getSimpleRef(p.get$ref());
//}
// --END of revision
setNonArrayMapProperty(property, type);
}
@ -2055,7 +2055,7 @@ public class DefaultCodegen implements CodegenConfig {
}
if (operation == null)
throw new RuntimeException("operation cannnot be null in fromOperation");
throw new RuntimeException("operation cannot be null in fromOperation");
// store the original operationId for plug-in
op.operationIdOriginal = operation.getOperationId();
@ -3047,6 +3047,24 @@ public class DefaultCodegen implements CodegenConfig {
}
}
/**
* Loop through propertiies and unalias the reference if $ref (reference) is defined
*
* @param allSchemas all schemas defined in the spec
* @param properties model properties (schemas)
* @return model properties with direct reference to schemas
*/
private Map<String, Schema> unaliasPropertySchema(Map<String, Schema> allSchemas, Map<String, Schema> properties) {
if (properties != null) {
for (String key : properties.keySet()) {
properties.put(key, ModelUtils.unaliasSchema(allSchemas, properties.get(key)));
}
}
return properties;
}
private void addVars(CodegenModel model, Map<String, Schema> properties, List<String> required) {
addVars(model, properties, required, null, null);
}
@ -3160,9 +3178,11 @@ public class DefaultCodegen implements CodegenConfig {
String oasName = entry.getKey();
Schema schema = entry.getValue();
String schemaType = getPrimitiveType(schema);
if (schemaType != null && !schemaType.equals("object") && !schemaType.equals("array") && schema.getEnum() == null) {
if (schemaType != null && !schemaType.equals("object") && !schemaType.equals("array")
&& schema.getEnum() == null && !ModelUtils.isMapSchema(schema)) {
aliases.put(oasName, schemaType);
}
}
return aliases;
@ -3853,7 +3873,7 @@ public class DefaultCodegen implements CodegenConfig {
RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody());
if (requestBody == null || requestBody.getContent() == null || requestBody.getContent().isEmpty()) {
return Collections.emptySet(); // return emtpy set
return Collections.emptySet(); // return empty set
}
return requestBody.getContent().keySet();
}
@ -4026,8 +4046,7 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.dataType = getTypeDeclaration(s);
if (codegenParameter.baseType != null && codegenParameter.enumName != null) {
codegenParameter.datatypeWithEnum = codegenParameter.dataType.replace(codegenParameter.baseType, codegenParameter.enumName);
}
else {
} else {
LOGGER.warn("Could not compute datatypeWithEnum from " + codegenParameter.baseType + ", " + codegenParameter.enumName);
}
//TODO fix collectformat for form parameters
@ -4226,7 +4245,7 @@ public class DefaultCodegen implements CodegenConfig {
codegenProperty = codegenProperty.items;
}
} else if (ModelUtils.isObjectSchema(schema)) {
} else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) {
CodegenModel codegenModel = null;
if (StringUtils.isNotBlank(name)) {
schema.setName(name);
@ -4249,7 +4268,7 @@ public class DefaultCodegen implements CodegenConfig {
if (schema.getAdditionalProperties() != null) {// http body is map
LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue.");
} else if (codegenProperty != null) {
LOGGER.warn("The folowing schema has undefined (null) baseType. " +
LOGGER.warn("The following schema has undefined (null) baseType. " +
"It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " +
"A correct 'consumes' for form parameters should be " +
"'application/x-www-form-urlencoded' or 'multipart/form-data'");

View File

@ -1012,7 +1012,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String key : definitions.keySet()) {
Schema schema = definitions.get(key);
if (schema == null)
throw new RuntimeException("schema cannnot be null in processMoels");
throw new RuntimeException("schema cannot be null in processMoels");
CodegenModel cm = config.fromModel(key, schema, allDefinitions);
Map<String, Object> mo = new HashMap<String, Object>();
mo.put("model", cm);

View File

@ -378,7 +378,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
/**
* Post process the media types (produces and consumes) for Ada code generator.
* <p>
* For each media type, add a adaMediaType member that gives the Ada enum constant
* For each media type, add an adaMediaType member that gives the Ada enum constant
* for the corresponding type.
*
* @param types the list of media types.

View File

@ -341,7 +341,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("An property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. ");
objs.put("_lambda", lambdas);

View File

@ -105,7 +105,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
typeMapping.put("file", "*os.File");
typeMapping.put("binary", "*os.File");
typeMapping.put("ByteArray", "string");
typeMapping.put("object", "interface{}");
typeMapping.put("object", "map[string]interface{}");
importMapping = new HashMap<String, String>();

View File

@ -48,7 +48,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
importMapping.clear();
supportsInheritance = true;
setReservedWordsLowerCase(Arrays.asList(
// NOTE: TypeScript uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons.
reservedWords.addAll(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
@ -345,6 +347,12 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
protected boolean isReservedWord(String word) {
// NOTE: This differs from super's implementation in that TypeScript does _not_ want case insensitive matching.
return reservedWords.contains(word);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);

View File

@ -74,7 +74,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
apiTemplateFiles.put("api-impl-source.mustache", ".cpp");
apiTemplateFiles.put("main-api-server.mustache", ".cpp");
embeddedTemplateDir = templateDir = "pistache-server";
embeddedTemplateDir = templateDir = "cpp-pistache-server";
cliOptions.clear();
@ -219,14 +219,14 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
//TODO: This changes the info about the real type but it is needed to parse the header params
if (param.isHeaderParam) {
param.dataType = "Optional<Net::Http::Header::Raw>";
param.baseType = "Optional<Net::Http::Header::Raw>";
param.dataType = "Pistache::Optional<Pistache::Http::Header::Raw>";
param.baseType = "Pistache::Optional<Pistache::Http::Header::Raw>";
} else if (param.isQueryParam) {
if (param.isPrimitiveType) {
param.dataType = "Optional<" + param.dataType + ">";
param.dataType = "Pistache::Optional<" + param.dataType + ">";
} else {
param.dataType = "Optional<" + param.baseType + ">";
param.baseType = "Optional<" + param.baseType + ">";
param.dataType = "Pistache::Optional<" + param.baseType + ">";
param.baseType = "Pistache::Optional<" + param.baseType + ">";
}
}
}
@ -299,7 +299,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
return toModelName(openAPIType);
}
return "std::shared_ptr<" + openAPIType + ">";
return openAPIType;
}
@Override
@ -326,30 +326,14 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
}
return "std::vector<" + inner + ">()";
} else if (!StringUtils.isEmpty(p.get$ref())) { // model
return "new " + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()";
} else if (ModelUtils.isStringSchema(p)) {
return "\"\"";
}
return "nullptr";
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
}
return "";
}
/**

View File

@ -92,7 +92,7 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "qt5cpp";
embeddedTemplateDir = templateDir = "cpp-qt5-client";
// CLI options
addOption(CPP_NAMESPACE, CPP_NAMESPACE_DESC, this.cppNamespace);
@ -248,7 +248,7 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo
if (!folder.isEmpty())
folder += File.separator;
return "#include \"" + folder + name + ".h\"";
return "#include \"" + folder + toModelName(name) + ".h\"";
}
/**
@ -285,7 +285,7 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo
@Override
public String toModelFilename(String name) {
return modelNamePrefix + initialCaps(name);
return initialCaps(toModelName(name));
}
@Override
@ -381,7 +381,7 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo
@Override
public String toModelName(String type) {
if (type == null) {
LOGGER.warn("Model name can't be null. Defaul to 'UnknownModel'.");
LOGGER.warn("Model name can't be null. Default to 'UnknownModel'.");
type = "UnknownModel";
}
@ -392,30 +392,31 @@ public class CppQt5ClientCodegen extends AbstractCppCodegen implements CodegenCo
languageSpecificPrimitives.contains(type)) {
return type;
} else {
return modelNamePrefix + Character.toUpperCase(type.charAt(0)) + type.substring(1);
String typeName = sanitizeName(type);
return modelNamePrefix + Character.toUpperCase(typeName.charAt(0)) + typeName.substring(1);
}
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
String varName = sanitizeName(name);
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
if (varName.matches("^[A-Z_]*$")) {
varName = varName.toLowerCase();
}
// camelize (lower first character) the variable name
// petId => pet_id
name = underscore(name);
varName = underscore(varName);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
if (isReservedWord(varName) || varName.matches("^\\d.*")) {
varName = escapeReservedWord(varName);
}
return name;
return varName;
}
@Override

View File

@ -99,7 +99,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
embeddedTemplateDir = templateDir = "cpprest";
embeddedTemplateDir = templateDir = "cpp-rest-sdk-client";
cliOptions.clear();

View File

@ -53,7 +53,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen {
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
embeddedTemplateDir = templateDir = "restbed";
embeddedTemplateDir = templateDir = "cpp-restbed-server";
cliOptions.clear();

View File

@ -44,7 +44,7 @@ public class CppTizenClientCodegen extends DefaultCodegen implements CodegenConf
modelTemplateFiles.put("model-body.mustache", ".cpp");
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-body.mustache", ".cpp");
embeddedTemplateDir = templateDir = "tizen";
embeddedTemplateDir = templateDir = "cpp-tizen-client";
modelPackage = "";
defaultIncludes = new HashSet<String>(

View File

@ -19,18 +19,13 @@ package org.openapitools.codegen.languages;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.*;
import org.openapitools.codegen.mustache.*;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.*;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.parameters.*;
import io.swagger.v3.oas.models.info.Info;
import java.util.*;
import java.io.File;
public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
public class JMeterClientCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
protected String sourceFolder = "";
@ -69,11 +64,11 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
return "Generates a JMeter .jmx file.";
}
public JMeterCodegen() {
public JMeterClientCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/JMeterCodegen";
outputFolder = "generated-code/JMeterClientCodegen";
/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
@ -90,7 +85,7 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig {
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "JMeter";
embeddedTemplateDir = templateDir = "jmeter-client";
/*
* Api Package. Optional, if needed, this can be used in templates

View File

@ -986,6 +986,11 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
}
String jsdocType = getJSDocType(operation);
operation.vendorExtensions.put("x-jsdoc-type", jsdocType);
// Format the return type correctly
if (operation.returnType != null) {
operation.vendorExtensions.put("x-return-type", normalizeType(operation.returnType));
}
}
}
return objs;

View File

@ -0,0 +1,281 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.utils.ModelUtils;
import java.text.SimpleDateFormat;
import java.util.*;
public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");
public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String SNAPSHOT = "snapshot";
protected String npmName = null;
protected String npmVersion = "1.0.0";
protected String npmRepository = null;
public JavascriptFlowtypedClientCodegen() {
super();
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
setReservedWordsLowerCase(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "arguments", "boolean", "break", "byte",
"case", "catch", "char", "class", "const",
"continue", "debugger", "default", "delete", "do",
"double", "else", "enum", "eval", "export",
"extends", "false", "final", "finally", "float",
"for", "function", "goto", "if", "implements",
"import", "in", "instanceof", "int", "interface",
"let", "long", "native", "new", "null",
"package", "private", "protected", "public", "return",
"short", "static", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "true",
"try", "typeof", "var", "void", "volatile",
"while", "with", "yield",
"Array", "Date", "eval", "function", "hasOwnProperty",
"Infinity", "isFinite", "isNaN", "isPrototypeOf",
"Math", "NaN", "Number", "Object",
"prototype", "String", "toString", "undefined", "valueOf"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("string", "boolean", "number", "Array", "Object", "Date", "File", "Blob")
);
instantiationTypes.put("array", "Array");
instantiationTypes.put("list", "Array");
instantiationTypes.put("map", "Object");
typeMapping.clear();
typeMapping.put("array", "Array");
typeMapping.put("map", "Object");
typeMapping.put("List", "Array");
typeMapping.put("boolean", "boolean");
typeMapping.put("string", "string");
typeMapping.put("int", "number");
typeMapping.put("float", "number");
typeMapping.put("number", "number");
typeMapping.put("DateTime", "Date");
typeMapping.put("date", "Date");
typeMapping.put("long", "number");
typeMapping.put("short", "number");
typeMapping.put("char", "string");
typeMapping.put("double", "number");
typeMapping.put("object", "Object");
typeMapping.put("integer", "number");
// file, binary not supported in JS client right now, using String as a workaround
typeMapping.put("file", "string");
typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
defaultIncludes = new HashSet<String>(languageSpecificPrimitives);
outputFolder = "generated-code/javascript-flowtyped";
embeddedTemplateDir = templateDir = "Javascript-Flowtyped";
this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package"));
this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package"));
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties());
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("index.mustache", "src", "index.js"));
supportingFiles.add(new SupportingFile("api.mustache", "src", "api.js"));
supportingFiles.add(new SupportingFile("configuration.mustache", "src", "configuration.js"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
addNpmPackageGeneration();
}
@Override
public String getTypeDeclaration(Schema p) {
Schema inner;
if (ModelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
return "any";
} else if (ModelUtils.isBinarySchema(p)) {
return "any";
} else {
return super.getTypeDeclaration(p);
}
}
private void addNpmPackageGeneration() {
if (additionalProperties.containsKey(NPM_NAME)) {
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
}
if (additionalProperties.containsKey(NPM_VERSION)) {
this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
}
if (additionalProperties.containsKey(SNAPSHOT) && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) {
this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date()));
}
additionalProperties.put(NPM_VERSION, npmVersion);
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("flowconfig.mustache", "", ".flowconfig"));
supportingFiles.add(new SupportingFile("babelrc", "", ".babelrc"));
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
super.preprocessOpenAPI(openAPI);
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
if (StringUtils.isBlank(npmName) && info.getTitle() != null) {
// when projectName is not specified, generate it from info.title
npmName = sanitizeName(dashize(info.getTitle()));
}
if (StringUtils.isBlank(npmVersion)) {
// when projectVersion is not specified, use info.version
npmVersion = escapeUnsafeCharacters(escapeQuotationMark(info.getVersion()));
}
}
// default values
if (StringUtils.isBlank(npmName)) {
npmName = "openapi-js-client";
}
if (StringUtils.isBlank(npmVersion)) {
npmVersion = "1.0.0";
}
additionalProperties.put(NPM_NAME, npmName);
additionalProperties.put(NPM_VERSION, npmVersion);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
List<Object> models = (List<Object>) postProcessModelsEnum(objs).get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
// name enum with model name, e.g. StatusEnum => Pet.StatusEnum
for (CodegenProperty var : cm.vars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + "" + var.enumName);
}
}
if (cm.parent != null) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + "" + var.enumName);
}
}
}
}
return objs;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String getName() {
return "javascript-flowtyped";
}
@Override
public String getHelp() {
return "Generates a Javascript client library (beta) using Flow types and Fetch API.";
}
public String getNpmName() {
return npmName;
}
public void setNpmName(String npmName) {
this.npmName = npmName;
}
public String getNpmVersion() {
return npmVersion;
}
public void setNpmVersion(String npmVersion) {
this.npmVersion = npmVersion;
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
}

View File

@ -229,7 +229,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen {
.build();
if (objs.containsKey("lambda")) {
LOGGER.warn("An property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
LOGGER.warn("A property named 'lambda' already exists. Mustache lambdas renamed from 'lambda' to '_lambda'. " +
"You'll likely need to use a custom template, " +
"see https://github.com/swagger-api/swagger-codegen#modifying-the-client-library-format. "); // TODO: update the URL
objs.put("_lambda", lambdas);

View File

@ -18,22 +18,31 @@
package org.openapitools.codegen.languages;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.v3.oas.models.media.*;
import java.io.File;
import java.util.Arrays;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.Comparator;
import java.util.Collections;
public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(PhpSlimServerCodegen.class);
protected String invokerPackage;
protected String srcBasePath = "lib";
protected String groupId = "org.openapitools";
@ -112,6 +121,7 @@ public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfi
supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json"));
supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', File.separatorChar), "index.php"));
supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', File.separatorChar), ".htaccess"));
supportingFiles.add(new SupportingFile(".gitignore", packagePath.replace('/', File.separatorChar), ".gitignore"));
}
@Override
@ -232,9 +242,36 @@ public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toModelName(String name) {
// remove [
name = name.replaceAll("\\]", "");
// Note: backslash ("\\") is allowed for e.g. "\\DateTime"
name = name.replaceAll("[^\\w\\\\]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");
// model name cannot use reserved keyword
if (isReservedWord(name)) {
escapeReservedWord(name); // e.g. return => _return
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (name.matches("^\\d.*")) {
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
// add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime)
if (!name.matches("^\\\\.*")) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
}
// camelize the model name
@ -248,6 +285,22 @@ public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfi
return toModelName(name);
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true));
operationId = "call_" + operationId;
}
return camelize(sanitizeName(operationId), true);
}
public String toPackagePath(String packageName, String basePath) {
packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (basePath != null && basePath.length() > 0) {
@ -292,4 +345,44 @@ public class PhpSlimServerCodegen extends DefaultCodegen implements CodegenConfi
return input.replace("*/", "");
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
if (op.hasProduces) {
// need to escape */* values because they breakes current mustaches
List<Map<String, String>> c = op.produces;
for (Map<String, String> mediaType : c) {
if ("*/*".equals(mediaType.get("mediaType"))) {
mediaType.put("mediaType", "*_/_*");
}
}
}
}
return objs;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Map<String, Object> apiInfo = (Map<String, Object>) objs.get("apiInfo");
List<HashMap<String, Object>> apiList = (List<HashMap<String, Object>>) apiInfo.get("apis");
for (HashMap<String, Object> api : apiList) {
HashMap<String, Object> operations = (HashMap<String, Object>) api.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
// Sort operations to avoid static routes shadowing
// ref: https://github.com/nikic/FastRoute/blob/master/src/DataGenerator/RegexBasedAbstract.php#L92-L101
Collections.sort(operationList, new Comparator<CodegenOperation>() {
@Override
public int compare(CodegenOperation one, CodegenOperation another) {
if (one.getHasPathParams() && !another.getHasPathParams()) return 1;
if (!one.getHasPathParams() && another.getHasPathParams()) return -1;
return 0;
}
});
}
return objs;
}
}

View File

@ -63,7 +63,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
outputFolder = "generated-code/scala-akka";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
embeddedTemplateDir = templateDir = "akka-scala";
embeddedTemplateDir = templateDir = "scala-akka-client";
apiPackage = mainPackage + ".api";
modelPackage = mainPackage + ".model";
invokerPackage = mainPackage + ".core";

View File

@ -43,7 +43,7 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code
outputFolder = "generated-code/scala-http-client";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
embeddedTemplateDir = templateDir = "scala";
embeddedTemplateDir = templateDir = "scala-httpclient";
apiPackage = "org.openapitools.client.api";
modelPackage = "org.openapitools.client.model";

View File

@ -43,11 +43,14 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
public static final String TAGGED_UNIONS = "taggedUnions";
public static final String NG_VERSION = "ngVersion";
public static final String PROVIDED_IN_ROOT ="providedInRoot";
public static final String SERVICE_SUFFIX = "serviceSuffix";
public static final String SERVICE_FILE_SUFFIX = "serviceFileSuffix";
protected String npmName = null;
protected String npmVersion = "1.0.0";
protected String npmRepository = null;
protected String serviceSuffix = "Service";
protected String serviceFileSuffix = ".service";
private boolean taggedUnions = false;
@ -81,6 +84,8 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
"Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0).",
SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular. Default is '4.3'"));
this.cliOptions.add(new CliOption(SERVICE_SUFFIX, "The suffix of the generated service. Default is 'Service'."));
this.cliOptions.add(new CliOption(SERVICE_FILE_SUFFIX, "The suffix of the file of the generated service (service<suffix>.ts). Default is '.service'."));
}
@Override
@ -159,6 +164,12 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
if (!ngVersion.atLeast("4.3.0")) {
supportingFiles.add(new SupportingFile("rxjs-operators.mustache", getIndexDirectory(), "rxjs-operators.ts"));
}
if (additionalProperties.containsKey(SERVICE_SUFFIX)) {
serviceSuffix = additionalProperties.get(SERVICE_SUFFIX).toString();
}
if (additionalProperties.containsKey(SERVICE_FILE_SUFFIX)) {
serviceFileSuffix = additionalProperties.get(SERVICE_FILE_SUFFIX).toString();
}
}
private void addNpmPackageGeneration(SemVer ngVersion) {
@ -418,7 +429,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
if (name.length() == 0) {
return "DefaultService";
}
return initialCaps(name) + "Service";
return initialCaps(name) + serviceSuffix;
}
@Override
@ -426,7 +437,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
if (name.length() == 0) {
return "default.service";
}
return camelize(name, true) + ".service";
return camelize(name, true) + serviceFileSuffix;
}
@Override
@ -469,7 +480,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
}
private String getApiFilenameFromClassname(String classname) {
String name = classname.substring(0, classname.length() - "Service".length());
String name = classname.substring(0, classname.length() - serviceSuffix.length());
return toApiFilename(name);
}

View File

@ -90,6 +90,7 @@ public class ModelUtils {
/**
* Return the list of all schemas in the 'components/schemas' section used in the openAPI specification
*
* @param openAPI specification
* @return schemas a list of used schemas
*/
@ -108,6 +109,7 @@ public class ModelUtils {
/**
* Return the list of unused schemas in the 'components/schemas' section of an openAPI specification
*
* @param openAPI specification
* @return schemas a list of unused schemas
*/
@ -127,6 +129,7 @@ public class ModelUtils {
/**
* Return the list of schemas in the 'components/schemas' used only in a 'application/x-www-form-urlencoded' or 'multipart/form-data' mime time
*
* @param openAPI specification
* @return schemas a list of schemas
*/
@ -478,6 +481,7 @@ public class ModelUtils {
/**
* If a Schema contains a reference to an other Schema with '$ref', returns the referenced Schema if it is found or the actual Schema in the other cases.
*
* @param openAPI specification being checked
* @param schema potentially containing a '$ref'
* @return schema without '$ref'
@ -510,6 +514,7 @@ public class ModelUtils {
/**
* If a RequestBody contains a reference to an other RequestBody with '$ref', returns the referenced RequestBody if it is found or the actual RequestBody in the other cases.
*
* @param openAPI specification being checked
* @param requestBody potentially containing a '$ref'
* @return requestBody without '$ref'
@ -538,6 +543,7 @@ public class ModelUtils {
/**
* If a ApiResponse contains a reference to an other ApiResponse with '$ref', returns the referenced ApiResponse if it is found or the actual ApiResponse in the other cases.
*
* @param openAPI specification being checked
* @param apiResponse potentially containing a '$ref'
* @return apiResponse without '$ref'
@ -566,6 +572,7 @@ public class ModelUtils {
/**
* If a Parameter contains a reference to an other Parameter with '$ref', returns the referenced Parameter if it is found or the actual Parameter in the other cases.
*
* @param openAPI specification being checked
* @param parameter potentially containing a '$ref'
* @return parameter without '$ref'
@ -594,6 +601,7 @@ public class ModelUtils {
/**
* Return the first defined Schema for a RequestBody
*
* @param requestBody request body of the operation
* @return firstSchema
*/
@ -603,6 +611,7 @@ public class ModelUtils {
/**
* Return the first defined Schema for a ApiResponse
*
* @param response api response of the operation
* @return firstSchema
*/
@ -620,4 +629,32 @@ public class ModelUtils {
MediaType mediaType = content.values().iterator().next();
return mediaType.getSchema();
}
/**
* Get the actual schema from aliases. If the provided schema is not an alias, the schema itself will be returned.
*
* @param allSchemas all schemas
* @param schema schema (alias or direct reference)
* @return actual schema
*/
public static Schema unaliasSchema(Map<String, Schema> allSchemas, Schema schema) {
if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) {
Schema ref = allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()));
if (ref == null) {
LOGGER.warn("{} is not defined", schema.get$ref());
return schema;
} else if (isObjectSchema(ref)) { // model
return schema;
} else if (isStringSchema(ref) && (ref.getEnum() != null && !ref.getEnum().isEmpty())) {
// top-level enum class
return schema;
} else if (isMapSchema(ref) || isArraySchema(ref)) { // map/array def should be created as models
return schema;
} else {
return unaliasSchema(allSchemas, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())));
}
}
return schema;
}
}

View File

@ -39,7 +39,7 @@ public class URLPathUtils {
LOGGER.warn("Server information seems not defined in the spec. Default to {}.", LOCAL_HOST);
return getDefaultUrl();
}
// TOOD need a way to obtain all server URLs
// TODO need a way to obtain all server URLs
final Server server = servers.get(0);
String url = sanitizeUrl(server.getUrl());

View File

@ -18,7 +18,7 @@ run the following command:
gprbuild -p -P{{projectName}}
```
After the build is successfull, you will get the server binary
After the build is successful, you will get the server binary
in bin/{{packageName}}-server and you can start it as follows:
```
./bin/{{packageName}}-server

View File

@ -7,7 +7,7 @@ expanded class
feature -- Access
from_json (a_val:STRING; a_type: TYPE [detachable ANY] ): detachable ANY
-- Deserialize a a json representation `a_val' to an object
-- Deserialize a json representation `a_val' to an object
-- of type `a_type'
local
conv_from: JSON_BASIC_REFLECTOR_DESERIALIZER

View File

@ -915,7 +915,7 @@ public class ApiClient {
* @param <T> Type
* @param response Response
* @param returnType Return type
* @throws ApiException If the response has a unsuccessful status code or
* @throws ApiException If the response has an unsuccessful status code or
* fail to deserialize the response body
* @return Type
*/

View File

@ -12,7 +12,7 @@ This is an example of building a OpenAPI-enabled server in Java using the Spring
The underlying library integrating OpenAPI to SpringBoot is [springfox](https://github.com/springfox/springfox)
{{/useSpringfox}}
Start your server as an simple java application
Start your server as a simple java application
{{^reactive}}
You can view the api documentation in swagger-ui by pointing to

View File

@ -0,0 +1,41 @@
## {{npmName}}@{{npmVersion}}
This generator creates Flow typed JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
Environment
* Node.js
* Webpack
* Browserify
Language level
* ES6
Module system
* ES6 module system
### Building
To build an compile the flow typed sources to javascript use:
```
npm install
npm run build
```
### Publishing
First build the package then run ```npm publish```
### Consuming
navigate to the folder of your consuming project and run one of the following commands.
_published:_
```
npm install {{npmName}}@{{npmVersion}} --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save

View File

@ -0,0 +1,266 @@
// @flow
/* eslint-disable no-use-before-define */
{{>licenseInfo}}
import * as url from "url";
import * as portableFetch from "portable-fetch";
import { Configuration } from "./configuration";
const BASE_PATH: string = "{{{basePath}}}".replace(/\/+$/, "");
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
*/
export type FetchAPI = {
(url: string, init?: any): Promise<Response>;
}
/**
*
* @export
*/
export type FetchArgs = {
url: string;
options: {};
}
/**
*
* @export
*/
export type RequestOptions = {
headers?: {};
query?: {};
body?: string | FormData;
}
/**
* * @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name:string = "RequiredError"
constructor(field: string, msg?: string) {
super(msg);
}
}
{{#models}}
{{#model}}{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>modelGeneric}}{{/isEnum}}{{/model}}
{{/models}}
{{#apiInfo}}{{#apis}}{{#operations}}
/**
* {{classname}} - fetch parameter creator{{#description}}
* {{&description}}{{/description}}
* @export
*/
export const {{classname}}FetchParamCreator = function (configuration?: Configuration) {
return {
{{#operation}}
/**
* {{&notes}}
{{#summary}}
* @summary {{&summary}}
{{/summary}}
* @throws {RequiredError}
*/
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: RequestOptions): FetchArgs {
{{#allParams}}
{{#required}}
// verify required parameter '{{paramName}}' is not null or undefined
if ({{paramName}} === null || {{paramName}} === undefined) {
throw new RequiredError('{{paramName}}','Required parameter {{paramName}} was null or undefined when calling {{nickname}}.');
}
{{/required}}
{{/allParams}}
const localVarPath = `{{{path}}}`{{#pathParams}}
.replace(`{${"{{baseName}}"}}`, encodeURIComponent(String({{paramName}}))){{/pathParams}};
const localVarUrlObj = url.parse(localVarPath, true);
const localVarRequestOptions: RequestOptions = Object.assign({}, { method: '{{httpMethod}}' }, options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
{{#hasFormParams}}
const localVarFormParams = new FormData();
{{/hasFormParams}}
{{#authMethods}}
// authentication {{name}} required
{{#isApiKey}}
{{#isKeyInHeader}}
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? configuration.apiKey("{{keyParamName}}")
: configuration.apiKey;
localVarHeaderParameter["{{keyParamName}}"] = localVarApiKeyValue;
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? configuration.apiKey("{{keyParamName}}")
: configuration.apiKey;
localVarQueryParameter["{{keyParamName}}"] = localVarApiKeyValue;
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{#isBasic}}
// http basic authentication required
if (configuration && (configuration.username || configuration.password)) {
localVarHeaderParameter["Authorization"] = "Basic " + btoa(configuration.username + ":" + configuration.password);
}
{{/isBasic}}
{{#isOAuth}}
// oauth required
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}])
: configuration.accessToken;
localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
{{/isOAuth}}
{{/authMethods}}
{{#queryParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}
localVarQueryParameter['{{baseName}}'] = {{paramName}};
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarQueryParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]);
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
{{#isDateTime}}
localVarQueryParameter['{{baseName}}'] = (({{paramName}}:any):Date).toISOString();
{{/isDateTime}}
{{^isDateTime}}
{{#isDate}}
localVarQueryParameter['{{baseName}}'] = (({{paramName}}:any):Date).toISOString();
{{/isDate}}
{{^isDate}}
localVarQueryParameter['{{baseName}}'] = (({{paramName}}:any):string);
{{/isDate}}
{{/isDateTime}}
}
{{/isListContainer}}
{{/queryParams}}
{{#headerParams}}
{{#isListContainer}}
if ({{paramName}}) {
localVarHeaderParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]);
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined && {{paramName}} !== null) {
localVarHeaderParameter['{{baseName}}'] = (({{paramName}}:any):string);
}
{{/isListContainer}}
{{/headerParams}}
{{#formParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}
{{paramName}}.forEach((element) => {
localVarFormParams.append('{{baseName}}', element);
})
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
localVarFormParams.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]));
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
localVarFormParams.set('{{baseName}}', (({{paramName}}:any):string));
}
{{/isListContainer}}
{{/formParams}}
{{#bodyParam}}
{{^consumes}}
localVarHeaderParameter['Content-Type'] = 'application/json';
{{/consumes}}
{{#consumes.0}}
localVarHeaderParameter['Content-Type'] = '{{{mediaType}}}';
{{/consumes.0}}
{{/bodyParam}}
localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query);
// fix override query string Detail: https://stackoverflow.com/a/7517673/1077943
delete localVarUrlObj.search;
localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers);
{{#hasFormParams}}
localVarRequestOptions.body = localVarFormParams;
{{/hasFormParams}}
{{#bodyParam}}
const needsSerialization = (typeof {{paramName}} !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json';
localVarRequestOptions.body = needsSerialization ? JSON.stringify({{paramName}} || {}) : ((({{paramName}}:any):string) || "");
{{/bodyParam}}
return {
url: url.format(localVarUrlObj),
options: localVarRequestOptions,
};
},
{{/operation}}
}
};
export type {{classname}}Type = { {{#operation}}
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}>,
{{/operation}}
}
/**
* {{classname}} - factory function to inject configuration {{#description}}
* {{{description}}}{{/description}}
* @export
*/
export const {{classname}} = function(configuration?: Configuration, fetch: FetchAPI = portableFetch): {{classname}}Type {
const basePath: string = (configuration && configuration.basePath) || BASE_PATH;
return {
{{#operation}}
/**
* {{&notes}}
{{#summary}}
* @summary {{&summary}}
{{/summary}}
* @throws {RequiredError}
*/
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions = {}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> {
const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options);
return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response{{#returnType}}.json(){{/returnType}};
} else {
throw response;
}
});
},
{{/operation}}
}
};
{{/operations}}{{/apis}}{{/apiInfo}}
export type ApiTypes = { {{#apiInfo}}{{#apis}}{{#operations}}
{{classname}}: {{classname}}Type,
{{/operations}}{{/apis}}{{/apiInfo}} }

View File

@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["transform-flow-strip-types"]
}

View File

@ -0,0 +1,65 @@
// @flow
{{>licenseInfo}}
export type ConfigurationParameters = {
apiKey?: string | (name: string) => string;
username?: string;
password?: string;
accessToken?: string | (name: string, scopes?: string[]) => string;
basePath?: string;
}
export class Configuration {
/**
* parameter for apiKey security
* @param name security name
* @memberof Configuration
*/
apiKey: string | (name: string) => string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
username: string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
password: string;
/**
* parameter for oauth2 security
* @param name security name
* @param scopes oauth2 scope
* @memberof Configuration
*/
accessToken: string | ((name: string, scopes?: string[]) => string);
/**
* override base path
*
* @type {string}
* @memberof Configuration
*/
basePath: string;
constructor(param: ConfigurationParameters = {}) {
if (param.apiKey) {
this.apiKey = param.apiKey;
}
if (param.username) {
this.username = param.username;
}
if (param.password) {
this.password = param.password;
}
if (param.accessToken) {
this.accessToken = param.accessToken;
}
if (param.basePath) {
this.basePath = param.basePath;
}
}
}

View File

@ -0,0 +1,11 @@
[ignore]
[include]
[libs]
[lints]
[options]
[strict]

View File

@ -0,0 +1 @@
node_modules

View File

@ -0,0 +1,5 @@
// @flow
{{>licenseInfo}}
export * from "./api";
export * from "./configuration";

View File

@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/

View File

@ -0,0 +1,6 @@
/**
* {{{description}}}
* @export
* @enum {string}
*/
export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}};

View File

@ -0,0 +1,27 @@
{{#hasEnums}}
{{#vars}}
{{#isEnum}}
export type {{classname}}{{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}};
{{/isEnum}}
{{/vars}}
{{/hasEnums}}
/**
* {{{description}}}
* @export
*/
export type {{classname}} = {
{{#additionalPropertiesType}}
[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};
{{/additionalPropertiesType}}
{{#vars}}
/**
* {{{description}}}
* @type {{=<% %>=}}{<%&datatype%>}<%={{ }}=%>
* @memberof {{classname}}
*/
{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}

View File

@ -0,0 +1,36 @@
{
"name": "{{npmName}}",
"version": "{{npmVersion}}",
"description": "swagger client for {{npmName}}",
"author": "Swagger Codegen Contributors",
"keywords": [
"fetch",
"flow",
"swagger-client",
"{{npmName}}"
],
"license": "Unlicense",
"main": "./lib/index.js",
"scripts": {
"build": "npm run build:clean && npm run build:lib && npm run build:flow",
"build:clean": "rimraf lib",
"build:lib": "node_modules/.bin/babel -d lib src --ignore '**/__tests__/**'",
"build:flow": "flow-copy-source -v -i '**/__tests__/**' src lib"
},
"dependencies": {
"portable-fetch": "^3.0.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-react-app": "^3.1.1",
"flow-copy-source": "^1.3.0",
"rimraf": "^2.6.2"
}{{#npmRepository}},{{/npmRepository}}
{{#npmRepository}}
"publishConfig":{
"registry":"{{npmRepository}}"
}
{{/npmRepository}}
}

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