mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-07 19:08:52 +00:00
Merge pull request #6075 from swagger-api/2.3.0
Merge 2.3.0 into master
This commit is contained in:
commit
c66a0aaa07
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,3 +1,4 @@
|
||||
.vscode
|
||||
*.iml
|
||||
out/
|
||||
*.ipr
|
||||
@ -73,6 +74,7 @@ samples/client/petstore/java/okhttp-gson/build/
|
||||
samples/client/petstore/java/feign/build/
|
||||
samples/client/petstore/java/retrofit/build/
|
||||
samples/client/petstore/java/retrofit2/build/
|
||||
samples/client/petstore/java/retrofit2/hello.txt
|
||||
samples/client/petstore/java/retrofit2rx/build/
|
||||
samples/client/petstore/java/default/build/
|
||||
samples/client/petstore/scala/build/
|
||||
|
57
.travis.objc_swift_test.yml
Normal file
57
.travis.objc_swift_test.yml
Normal file
@ -0,0 +1,57 @@
|
||||
sudo: required
|
||||
language: objective-c
|
||||
osx_image: xcode9
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.m2
|
||||
- $HOME/.gem
|
||||
- $HOME/.rvm
|
||||
- $HOME/.cocoapods
|
||||
- swagger-api/swagger-codegen/samples/client/petstore/objc/default/SwaggerClientTests/Pods
|
||||
- swagger-api/swagger-codegen/samples/client/petstore/objc/core-data/SwaggerClientTests/Pods
|
||||
- swagger-api/swagger-codegen/samples/client/petstore/swift/default/SwaggerClientTests/Pods
|
||||
- swagger-api/swagger-codegen/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods
|
||||
|
||||
services:
|
||||
- docker
|
||||
|
||||
addons:
|
||||
hosts:
|
||||
- petstore.swagger.io
|
||||
|
||||
before_install:
|
||||
- export SW=`pwd`
|
||||
# show host table to confirm petstore.swagger.io is mapped to localhost
|
||||
- cat /private/etc/hosts
|
||||
#- rvm install 2.2.2 > /dev/null 2>&1
|
||||
- rvm use 2.2.4
|
||||
- gem environment
|
||||
- gem install cocoapods -v 1.0.1 -N --no-ri --no-rdoc
|
||||
- gem install xcpretty -N --no-ri --no-rdoc
|
||||
- pod --version
|
||||
- pod setup --silent > /dev/null
|
||||
# xctool already pre-installed
|
||||
#- brew install xctool
|
||||
- git clone https://github.com/wing328/swagger-samples
|
||||
- cd swagger-samples/java/java-jersey-jaxrs && sudo mvn -q jetty:run &
|
||||
|
||||
install:
|
||||
|
||||
script:
|
||||
# test default objc client
|
||||
- cd $SW/samples/client/petstore/objc/default/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
|
||||
# test objc client with coredata
|
||||
- cd $SW/samples/client/petstore/objc/core-data/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
|
||||
- set -o pipefail
|
||||
# test swift client with promisekit
|
||||
- cd $SW/samples/client/petstore/swift/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
|
||||
# test default swift client
|
||||
- cd $SW/samples/client/petstore/swift/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
|
||||
# test swift3 client with promisekit
|
||||
- cd $SW/samples/client/petstore/swift3/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
|
||||
# test default swift3 client
|
||||
- cd $SW/samples/client/petstore/swift3/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty
|
||||
|
||||
env:
|
||||
- DOCKER_IMAGE_NAME=swaggerapi/swagger-generator
|
@ -104,7 +104,7 @@ script:
|
||||
|
||||
after_success:
|
||||
# push a snapshot version to maven repo
|
||||
- if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "master" ]; then
|
||||
- if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "2.3.0" ]; then
|
||||
mvn clean deploy --settings .travis/settings.xml;
|
||||
echo "Finished mvn clean deploy";
|
||||
echo "Finished mvn clean deploy for 2.3.0";
|
||||
fi;
|
||||
|
@ -26,6 +26,7 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver --additional-properties hideGenerationTimestamp=true -Dservice"
|
||||
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/go-server -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver --additional-properties hideGenerationTimestamp=true -Dservice"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,7 +26,7 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit -DhideGenerationTimestamp=true"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit -DhideGenerationTimestamp=true,dateLibrary=joda"
|
||||
|
||||
echo "Removing files and folders under samples/client/petstore/java/retrofit/src/main"
|
||||
rm -rf samples/client/petstore/java/retrofit/src/main
|
||||
|
@ -26,6 +26,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/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-annotated-base-path -DhideGenerationTimestamp=true,useAnnotatedBasePath=true"
|
||||
ags="$@ generate --artifact-id swagger-cxf-annotated-basepath -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-annotated-base-path -DhideGenerationTimestamp=true,useAnnotatedBasePath=true"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-non-spring-app -DhideGenerationTimestamp=true,generateNonSpringApplication=true"
|
||||
ags="$@ generate --artifact-id swagger-cxf-server-non-spring -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-non-spring-app -DhideGenerationTimestamp=true,generateNonSpringApplication=true"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs -Dservice"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/nodejs -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs -Dservice"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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/swagger-codegen/src/main/resources/typescript-angular2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-angular2 -o samples/client/petstore-security-test/typescript-angular2"
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-angular2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-angular -o samples/client/petstore-security-test/typescript-angular2"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -38,3 +38,7 @@ java $JAVA_OPTS -jar $executable $ags
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-rxswift.json -o samples/client/petstore/swift3/rxswift"
|
||||
echo "#### Petstore Swift API client (rxswift) ####"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-unwraprequired.json -o samples/client/petstore/swift3/unwraprequired"
|
||||
echo "#### Petstore Swift API client (unwraprequired) ####"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
7
bin/swift3-petstore-unwraprequired.json
Normal file
7
bin/swift3-petstore-unwraprequired.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"podSummary": "PetstoreClient",
|
||||
"podHomepage": "https://github.com/swagger-api/swagger-codegen",
|
||||
"podAuthors": "",
|
||||
"projectName": "PetstoreClient",
|
||||
"unwrapRequired": true
|
||||
}
|
31
bin/swift3-petstore-unwraprequired.sh
Executable file
31
bin/swift3-petstore-unwraprequired.sh
Executable file
@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
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/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn 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/swagger-codegen/src/main/resources/swift3 -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l swift3 -c ./bin/swift3-petstore-unwraprequired.json -o samples/client/petstore/swift3/unwraprequired"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular -o samples/client/petstore/typescript-angular"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angularjs -o samples/client/petstore/typescript-angular"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -28,13 +28,13 @@ fi
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
|
||||
echo "Typescript Petstore API client (default)"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular2/default --additional-properties ngVersion=2"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
echo "Typescript Petstore API client (npm setting)"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm --additional-properties ngVersion=2"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
||||
echo "Typescript Petstore API client (with interfaces generated)"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -o samples/client/petstore/typescript-angular2/with-interfaces -D withInterfaces=true"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular2/with-interfaces -D withInterfaces=true --additional-properties ngVersion=2"
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -o samples/client/petstore/typescript-angular2/with-interfaces -D withInterfaces=true"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular2/with-interfaces -D withInterfaces=true --additional-properties ngVersion=2"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm --additional-properties ngVersion=2"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -o samples/client/petstore/typescript-angular2/default --additional-properties ngVersion=2"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
31
bin/typescript-angular4-petstore-with-npm.sh
Executable file
31
bin/typescript-angular4-petstore-with-npm.sh
Executable file
@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
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/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-angular -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular4/npm --additional-properties ngVersion=4"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -26,6 +26,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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
||||
|
@ -5,6 +5,6 @@ If Not Exist %executable% (
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular -o samples\client\petstore\typescript-angular
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angularjs -o samples\client\petstore\typescript-angular
|
||||
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
||||
|
@ -1,18 +0,0 @@
|
||||
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
|
||||
|
||||
If Not Exist %executable% (
|
||||
mvn clean package
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
echo "Typescript Petstore API client (default)"
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular2 -o samples\client\petstore\typescript-angular2\default
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
||||
|
||||
echo "Typescript Petstore API client (with interfaces generated)"
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular2 -o samples\client\petstore\typescript-angular2\with-interfaces -D withInterfaces=true
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
||||
|
||||
echo "Typescript Petstore API client (npm setting)"
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular2 -c bin\typescript-petstore-npm.json -o samples\client\petstore\typescript-angular2\npm
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
10
bin/windows/typescript-angular2-interfaces.bat
Normal file
10
bin/windows/typescript-angular2-interfaces.bat
Normal file
@ -0,0 +1,10 @@
|
||||
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
|
||||
|
||||
If Not Exist %executable% (
|
||||
mvn clean package
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -c bin\typescript-petstore-npm.json -l typescript-angular -o samples\client\petstore\typescript-angular2\with-interfaces -D withInterfaces=true --additional-properties ngVersion=2
|
||||
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
3
bin/windows/typescript-angular2-petstore-all.bat
Executable file
3
bin/windows/typescript-angular2-petstore-all.bat
Executable file
@ -0,0 +1,3 @@
|
||||
call .\bin\windows\typescript-angular2-with-npm.bat
|
||||
call .\bin\windows\typescript-angular2-interfaces.bat
|
||||
call .\bin\windows\typescript-angular2.bat
|
@ -5,6 +5,6 @@ If Not Exist %executable% (
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -c bin\typescript-petstore-npm.json -l typescript-angular2 -o samples\client\petstore\typescript-angular2\npm
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -c bin\typescript-petstore-npm.json -l typescript-angular -o samples\client\petstore\typescript-angular2\npm --additional-properties ngVersion=2
|
||||
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
||||
|
@ -5,6 +5,6 @@ If Not Exist %executable% (
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular2 -o samples\client\petstore\typescript-angular2\default
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-angular -o samples\client\petstore\typescript-angular2\default --additional-properties ngVersion=2
|
||||
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
||||
|
10
bin/windows/typescript-angular4-with-npm.bat
Normal file
10
bin/windows/typescript-angular4-with-npm.bat
Normal file
@ -0,0 +1,10 @@
|
||||
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
|
||||
|
||||
If Not Exist %executable% (
|
||||
mvn clean package
|
||||
)
|
||||
|
||||
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
|
||||
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -c bin\typescript-petstore-npm.json -l typescript-angular -o samples\client\petstore\typescript-angular2\npm --additional-properties ngVersion=4
|
||||
|
||||
java %JAVA_OPTS% -jar %executable% %ags%
|
@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.2.3</version>
|
||||
<version>2.3.0-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.2.3</version>
|
||||
<version>2.3.0-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<artifactId>swagger-codegen-maven-plugin</artifactId>
|
||||
|
1
modules/swagger-codegen/.gitignore
vendored
1
modules/swagger-codegen/.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
/.settings/
|
||||
/test-output/
|
||||
/bin/
|
||||
|
@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
<version>2.2.3</version>
|
||||
<version>2.3.0-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -1,6 +1,7 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.models.ExternalDocs;
|
||||
import io.swagger.models.Tag;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
@ -28,14 +29,14 @@ public class CodegenOperation {
|
||||
public List<CodegenParameter> headerParams = new ArrayList<CodegenParameter>();
|
||||
public List<CodegenParameter> formParams = new ArrayList<CodegenParameter>();
|
||||
public List<CodegenSecurity> authMethods;
|
||||
public List<String> tags;
|
||||
public List<Tag> tags;
|
||||
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
|
||||
public Set<String> imports = new HashSet<String>();
|
||||
public List<Map<String, String>> examples;
|
||||
public ExternalDocs externalDocs;
|
||||
public Map<String, Object> vendorExtensions;
|
||||
public String nickname; // legacy support
|
||||
public String operationIdLowerCase; // for mardown documentation
|
||||
public String operationIdLowerCase; // for markdown documentation
|
||||
public String operationIdCamelCase; // for class names
|
||||
public String operationIdSnakeCase;
|
||||
|
||||
|
@ -2022,7 +2022,6 @@ public class DefaultCodegen {
|
||||
op.summary = escapeText(operation.getSummary());
|
||||
op.unescapedNotes = operation.getDescription();
|
||||
op.notes = escapeText(operation.getDescription());
|
||||
op.tags = operation.getTags();
|
||||
op.hasConsumes = false;
|
||||
op.hasProduces = false;
|
||||
|
||||
|
@ -776,11 +776,37 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
if (System.getProperty("debugOperations") != null) {
|
||||
LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n");
|
||||
}
|
||||
List<String> tags = operation.getTags();
|
||||
if (tags == null) {
|
||||
tags = new ArrayList<String>();
|
||||
tags.add("default");
|
||||
List<Tag> tags = new ArrayList<Tag>();
|
||||
|
||||
List<String> tagNames = operation.getTags();
|
||||
List<Tag> swaggerTags = swagger.getTags();
|
||||
if (tagNames != null) {
|
||||
if (swaggerTags == null) {
|
||||
for (String tagName : tagNames) {
|
||||
tags.add(new Tag().name(tagName));
|
||||
}
|
||||
} else {
|
||||
for (String tagName : tagNames) {
|
||||
boolean foundTag = false;
|
||||
for (Tag tag : swaggerTags) {
|
||||
if (tag.getName().equals(tagName)) {
|
||||
tags.add(tag);
|
||||
foundTag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundTag) {
|
||||
tags.add(new Tag().name(tagName));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tags.isEmpty()) {
|
||||
tags.add(new Tag().name("default"));
|
||||
}
|
||||
|
||||
/*
|
||||
build up a set of parameter "ids" defined at the operation level
|
||||
per the swagger 2.0 spec "A unique parameter is defined by a combination of a name and location"
|
||||
@ -803,12 +829,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
}
|
||||
}
|
||||
|
||||
for (String tag : tags) {
|
||||
for (Tag tag : tags) {
|
||||
try {
|
||||
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger);
|
||||
codegenOperation.tags = new ArrayList<String>();
|
||||
codegenOperation.tags.add(config.sanitizeTag(tag));
|
||||
config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, codegenOperation, operations);
|
||||
codegenOperation.tags = new ArrayList<Tag>(tags);
|
||||
config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations);
|
||||
|
||||
List<Map<String, List<String>>> securities = operation.getSecurity();
|
||||
if (securities == null && swagger.getSecurity() != null) {
|
||||
|
@ -1,39 +1,17 @@
|
||||
package io.swagger.codegen.examples;
|
||||
|
||||
import static io.swagger.models.properties.StringProperty.Format.URI;
|
||||
import static io.swagger.models.properties.StringProperty.Format.URL;
|
||||
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.ModelImpl;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BaseIntegerProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DecimalProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FileProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.ObjectProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.RefProperty;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
import io.swagger.models.properties.UUIDProperty;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.util.Json;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
import static io.swagger.models.properties.StringProperty.Format.URI;
|
||||
import static io.swagger.models.properties.StringProperty.Format.URL;
|
||||
|
||||
public class ExampleGenerator {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ExampleGenerator.class);
|
||||
@ -203,7 +181,7 @@ public class ExampleGenerator {
|
||||
|
||||
private Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
|
||||
if (processedModels.contains(name)) {
|
||||
return "";
|
||||
return model.getExample();
|
||||
}
|
||||
if (model instanceof ModelImpl) {
|
||||
processedModels.add(name);
|
||||
@ -221,6 +199,7 @@ public class ExampleGenerator {
|
||||
Property property = impl.getProperties().get(propertyName);
|
||||
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));
|
||||
}
|
||||
impl.setExample(values);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
@ -49,9 +49,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
public static final String WITH_XML = "withXml";
|
||||
public static final String SUPPORT_JAVA6 = "supportJava6";
|
||||
|
||||
protected String dateLibrary = "threetenbp";
|
||||
protected boolean java8Mode = false;
|
||||
protected boolean withXml = false;
|
||||
protected String dateLibrary = "joda";
|
||||
protected String invokerPackage = "io.swagger";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-java";
|
||||
@ -93,8 +93,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
setReservedWordsLowerCase(
|
||||
Arrays.asList(
|
||||
// used as internal variables, can collide with parameter names
|
||||
"localVarPath", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams",
|
||||
"localVarPostBody", "localVarAccepts", "localVarAccept", "localVarContentTypes",
|
||||
"localVarPath", "localVarQueryParams", "localVarCollectionQueryParams",
|
||||
"localVarHeaderParams", "localVarFormParams", "localVarPostBody",
|
||||
"localVarAccepts", "localVarAccept", "localVarContentTypes",
|
||||
"localVarContentType", "localVarAuthNames", "localReturnType",
|
||||
"ApiClient", "ApiException", "ApiResponse", "Configuration", "StringUtil",
|
||||
|
||||
@ -153,10 +154,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
|
||||
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use");
|
||||
Map<String, String> dateOptions = new HashMap<String, String>();
|
||||
dateOptions.put("java8", "Java 8 native - note: this also sets \"" + JAVA8_MODE + "\" to true");
|
||||
dateOptions.put("java8", "Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets \"" + JAVA8_MODE + "\" to true");
|
||||
dateOptions.put("threetenbp", "Backport of JSR310 (preferred for jdk < 1.8)");
|
||||
dateOptions.put("java8-localdatetime", "Java 8 using LocalDateTime (for legacy app only)");
|
||||
dateOptions.put("joda", "Joda");
|
||||
dateOptions.put("legacy", "Legacy java.util.Date");
|
||||
dateOptions.put("joda", "Joda (for legacy app only)");
|
||||
dateOptions.put("legacy", "Legacy java.util.Date (if you really have a good reason not to use threetenbp");
|
||||
dateLibrary.setEnum(dateOptions);
|
||||
cliOptions.add(dateLibrary);
|
||||
|
||||
@ -374,11 +376,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
// used later in recursive import in postProcessingModels
|
||||
importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator");
|
||||
|
||||
if(additionalProperties.containsKey(DATE_LIBRARY)) {
|
||||
setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString());
|
||||
additionalProperties.put(dateLibrary, "true");
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey(JAVA8_MODE)) {
|
||||
setJava8Mode(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString()));
|
||||
if ( java8Mode ) {
|
||||
@ -393,15 +390,26 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
|
||||
}
|
||||
}
|
||||
|
||||
if("joda".equals(dateLibrary)) {
|
||||
if (additionalProperties.containsKey(DATE_LIBRARY)) {
|
||||
setDateLibrary(additionalProperties.get("dateLibrary").toString());
|
||||
}
|
||||
|
||||
if ("threetenbp".equals(dateLibrary)) {
|
||||
additionalProperties.put("threetenbp", "true");
|
||||
additionalProperties.put("jsr310", "true");
|
||||
typeMapping.put("date", "LocalDate");
|
||||
typeMapping.put("DateTime", "OffsetDateTime");
|
||||
importMapping.put("LocalDate", "org.threeten.bp.LocalDate");
|
||||
importMapping.put("OffsetDateTime", "org.threeten.bp.OffsetDateTime");
|
||||
} else if ("joda".equals(dateLibrary)) {
|
||||
additionalProperties.put("joda", "true");
|
||||
typeMapping.put("date", "LocalDate");
|
||||
typeMapping.put("DateTime", "DateTime");
|
||||
|
||||
importMapping.put("LocalDate", "org.joda.time.LocalDate");
|
||||
importMapping.put("DateTime", "org.joda.time.DateTime");
|
||||
} else if (dateLibrary.startsWith("java8")) {
|
||||
additionalProperties.put("java8", "true");
|
||||
additionalProperties.put("jsr310", "true");
|
||||
typeMapping.put("date", "LocalDate");
|
||||
importMapping.put("LocalDate", "java.time.LocalDate");
|
||||
if ("java8-localdatetime".equals(dateLibrary)) {
|
||||
|
@ -3,10 +3,10 @@ package io.swagger.codegen.languages;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeSet;
|
||||
|
||||
@ -43,7 +43,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
// Typescript reserved words
|
||||
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "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", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(Arrays.asList(
|
||||
languageSpecificPrimitives = new HashSet<>(Arrays.asList(
|
||||
"string",
|
||||
"String",
|
||||
"boolean",
|
||||
@ -57,8 +57,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
"Date",
|
||||
"number",
|
||||
"any",
|
||||
"Error"
|
||||
));
|
||||
"File",
|
||||
"Error",
|
||||
"Map"
|
||||
));
|
||||
|
||||
languageGenericTypes = new HashSet<String>(Arrays.asList(
|
||||
"Array"
|
||||
@ -82,12 +84,15 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
typeMapping.put("object", "any");
|
||||
typeMapping.put("integer", "number");
|
||||
typeMapping.put("Map", "any");
|
||||
typeMapping.put("date", "string");
|
||||
typeMapping.put("DateTime", "Date");
|
||||
//TODO binary should be mapped to byte array
|
||||
// mapped to String as a workaround
|
||||
typeMapping.put("binary", "string");
|
||||
typeMapping.put("ByteArray", "string");
|
||||
typeMapping.put("UUID", "string");
|
||||
typeMapping.put("File", "any");
|
||||
typeMapping.put("Error", "Error");
|
||||
|
||||
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
|
||||
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
|
||||
@ -114,7 +119,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
public String escapeReservedWord(String name) {
|
||||
if(this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
@ -188,6 +193,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
|
||||
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
|
||||
return modelName;
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
return camelize(name);
|
||||
|
@ -1,28 +0,0 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class AspNet5ServerCodegen extends AspNetCoreServerCodegen {
|
||||
|
||||
@SuppressWarnings("hiding")
|
||||
protected Logger LOGGER = LoggerFactory.getLogger(AspNet5ServerCodegen.class);
|
||||
|
||||
public AspNet5ServerCodegen() {
|
||||
super();
|
||||
|
||||
embeddedTemplateDir = templateDir = "aspnetcore";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "aspnet5";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
LOGGER.warn("aspnet5 is deprecated. Please use aspnetcore.");
|
||||
}
|
||||
}
|
@ -114,6 +114,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
|
||||
supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder, "project.json"));
|
||||
supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));
|
||||
supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs"));
|
||||
supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs"));
|
||||
supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config"));
|
||||
|
||||
supportingFiles.add(new SupportingFile("Project.xproj.mustache", packageFolder, this.packageName + ".xproj"));
|
||||
|
@ -212,6 +212,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
|
||||
additionalProperties.remove("supportsAsync");
|
||||
}
|
||||
additionalProperties.put("validatable", false);
|
||||
additionalProperties.put("net35", true);
|
||||
} else if (NETSTANDARD.equals(this.targetFramework)){
|
||||
setTargetFrameworkNuget("netstandard1.3");
|
||||
setSupportsAsync(Boolean.TRUE);
|
||||
@ -314,6 +315,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
|
||||
clientPackageDir, "ExceptionFactory.cs"));
|
||||
supportingFiles.add(new SupportingFile("SwaggerDateConverter.mustache",
|
||||
clientPackageDir, "SwaggerDateConverter.cs"));
|
||||
|
||||
if(Boolean.FALSE.equals(this.netStandard) && Boolean.FALSE.equals(this.netCoreProjectFileFlag)) {
|
||||
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
|
||||
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
|
||||
@ -326,6 +328,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
|
||||
supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder + File.separator, "project.json"));
|
||||
}
|
||||
|
||||
supportingFiles.add(new SupportingFile("IReadableConfiguration.mustache",
|
||||
clientPackageDir, "IReadableConfiguration.cs"));
|
||||
supportingFiles.add(new SupportingFile("GlobalConfiguration.mustache",
|
||||
clientPackageDir, "GlobalConfiguration.cs"));
|
||||
|
||||
// Only write out test related files if excludeTests is unset or explicitly set to false (see start of this method)
|
||||
if(Boolean.FALSE.equals(excludeTests)) {
|
||||
// shell script to run the nunit test
|
||||
|
@ -97,7 +97,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("boolean", "bool");
|
||||
typeMapping.put("string", "string");
|
||||
typeMapping.put("UUID", "string");
|
||||
typeMapping.put("date", "time.Time");
|
||||
typeMapping.put("date", "string");
|
||||
typeMapping.put("DateTime", "time.Time");
|
||||
typeMapping.put("password", "string");
|
||||
typeMapping.put("File", "*os.File");
|
||||
@ -151,7 +151,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
|
||||
|
||||
|
||||
additionalProperties.put("apiDocPath", apiDocPath);
|
||||
additionalProperties.put("modelDocPath", modelDocPath);
|
||||
|
||||
@ -180,10 +180,10 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
// - XName
|
||||
// - X_Name
|
||||
// ... or maybe a suffix?
|
||||
// - Name_ ... think this will work.
|
||||
// - Name_ ... think this will work.
|
||||
if(this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
}
|
||||
return camelize(name) + '_';
|
||||
}
|
||||
|
||||
@ -274,8 +274,6 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Overrides postProcessParameter to add a vendor extension "x-exportParamName".
|
||||
* This is useful when paramName starts with a lowercase letter, but we need that
|
||||
@ -303,7 +301,6 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
parameter.vendorExtensions.put("x-exportParamName", sb.toString());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String apiDocFileFolder() {
|
||||
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
|
||||
@ -406,9 +403,10 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
if (_import.startsWith(apiPackage()))
|
||||
iterator.remove();
|
||||
}
|
||||
// if the return type is not primitive, import encoding/json
|
||||
|
||||
// if their is a return type, import encoding/json
|
||||
for (CodegenOperation operation : operations) {
|
||||
if(operation.returnBaseType != null && needToImport(operation.returnBaseType)) {
|
||||
if(operation.returnBaseType != null ) {
|
||||
imports.add(createMapping("import", "encoding/json"));
|
||||
break; //just need to import once
|
||||
}
|
||||
@ -422,7 +420,6 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// recursively add import for mapping one type to multiple imports
|
||||
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
|
||||
if (recursiveImports == null)
|
||||
@ -468,7 +465,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
}
|
||||
|
||||
return objs;
|
||||
return postProcessModelsEnum(objs);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -502,4 +499,65 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
return customImport;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toEnumValue(String value, String datatype) {
|
||||
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
|
||||
return value;
|
||||
} else {
|
||||
return escapeText(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumDefaultValue(String value, String datatype) {
|
||||
return datatype + "_" + value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumVarName(String name, String datatype) {
|
||||
if (name.length() == 0) {
|
||||
return "EMPTY";
|
||||
}
|
||||
|
||||
// number
|
||||
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
|
||||
String varName = name;
|
||||
varName = varName.replaceAll("-", "MINUS_");
|
||||
varName = varName.replaceAll("\\+", "PLUS_");
|
||||
varName = varName.replaceAll("\\.", "_DOT_");
|
||||
return varName;
|
||||
}
|
||||
|
||||
// for symbol, e.g. $, #
|
||||
if (getSymbolName(name) != null) {
|
||||
return getSymbolName(name).toUpperCase();
|
||||
}
|
||||
|
||||
// string
|
||||
String enumName = sanitizeName(underscore(name).toUpperCase());
|
||||
enumName = enumName.replaceFirst("^_", "");
|
||||
enumName = enumName.replaceFirst("_$", "");
|
||||
|
||||
if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number
|
||||
return escapeReservedWord(enumName);
|
||||
} else {
|
||||
return enumName;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumName(CodegenProperty property) {
|
||||
String enumName = underscore(toModelName(property.name)).toUpperCase();
|
||||
|
||||
// remove [] for array or map of enum
|
||||
enumName = enumName.replace("[]", "");
|
||||
|
||||
if (enumName.matches("\\d.*")) { // starts with number
|
||||
return "_" + enumName;
|
||||
} else {
|
||||
return enumName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -11,6 +11,11 @@ import com.google.common.collect.Multimap;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.util.Yaml;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.parameters.Parameter;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -29,7 +34,7 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected int serverPort = 8080;
|
||||
protected String projectName = "swagger-server";
|
||||
protected String apiPath = "go";
|
||||
|
||||
|
||||
public GoServerCodegen() {
|
||||
super();
|
||||
|
||||
@ -64,6 +69,11 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
*/
|
||||
setReservedWordsLowerCase(
|
||||
Arrays.asList(
|
||||
// data type
|
||||
"string", "bool", "uint", "uint8", "uint16", "uint32", "uint64",
|
||||
"int", "int8", "int16", "int32", "int64", "float32", "float64",
|
||||
"complex64", "complex128", "rune", "byte", "uintptr",
|
||||
|
||||
"break", "default", "func", "interface", "select",
|
||||
"case", "defer", "go", "map", "struct",
|
||||
"chan", "else", "goto", "package", "switch",
|
||||
@ -109,7 +119,8 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("double", "float64");
|
||||
typeMapping.put("boolean", "bool");
|
||||
typeMapping.put("string", "string");
|
||||
typeMapping.put("date", "time.Time");
|
||||
typeMapping.put("UUID", "string");
|
||||
typeMapping.put("date", "string");
|
||||
typeMapping.put("DateTime", "time.Time");
|
||||
typeMapping.put("password", "string");
|
||||
typeMapping.put("File", "*os.File");
|
||||
@ -118,6 +129,7 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
// the correct solution is to use []byte
|
||||
typeMapping.put("binary", "string");
|
||||
typeMapping.put("ByteArray", "string");
|
||||
typeMapping.put("object", "interface{}");
|
||||
typeMapping.put("UUID", "string");
|
||||
|
||||
importMapping = new HashMap<String, String>();
|
||||
@ -149,8 +161,8 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
);
|
||||
supportingFiles.add(new SupportingFile("main.mustache", "", "main.go"));
|
||||
supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go"));
|
||||
supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go"));
|
||||
supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml"));
|
||||
supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go"));
|
||||
supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml"));
|
||||
writeOptional(outputFolder, new SupportingFile("README.mustache", apiPath, "README.md"));
|
||||
}
|
||||
|
||||
@ -211,7 +223,7 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String escapeReservedWord(String name) {
|
||||
if(this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
}
|
||||
return "_" + name; // add an underscore to the name
|
||||
}
|
||||
|
||||
@ -245,11 +257,11 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
if (!StringUtils.isEmpty(modelNamePrefix)) {
|
||||
name = modelNamePrefix + "_" + name;
|
||||
name = modelNamePrefix + name;
|
||||
}
|
||||
|
||||
if (!StringUtils.isEmpty(modelNameSuffix)) {
|
||||
name = name + "_" + modelNameSuffix;
|
||||
name = name + modelNameSuffix;
|
||||
}
|
||||
|
||||
name = sanitizeName(name);
|
||||
@ -260,7 +272,54 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
|
||||
}
|
||||
|
||||
return underscore(name);
|
||||
return camelize(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return "[]" + getTypeDeclaration(inner);
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner);
|
||||
}
|
||||
//return super.getTypeDeclaration(p);
|
||||
|
||||
// Not using the supertype invocation, because we want to UpperCamelize
|
||||
// the type.
|
||||
String swaggerType = getSwaggerType(p);
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
return typeMapping.get(swaggerType);
|
||||
}
|
||||
|
||||
if(typeMapping.containsValue(swaggerType)) {
|
||||
return swaggerType;
|
||||
}
|
||||
|
||||
if(languageSpecificPrimitives.contains(swaggerType)) {
|
||||
return swaggerType;
|
||||
}
|
||||
|
||||
return toModelName(swaggerType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
return (type);
|
||||
}
|
||||
else
|
||||
type = swaggerType;
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -283,4 +342,69 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumValue(String value, String datatype) {
|
||||
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
|
||||
return value;
|
||||
} else {
|
||||
return "\'" + escapeText(value) + "\'";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumDefaultValue(String value, String datatype) {
|
||||
return datatype + "_" + value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumVarName(String name, String datatype) {
|
||||
if (name.length() == 0) {
|
||||
return "EMPTY";
|
||||
}
|
||||
|
||||
// number
|
||||
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
|
||||
String varName = name;
|
||||
varName = varName.replaceAll("-", "MINUS_");
|
||||
varName = varName.replaceAll("\\+", "PLUS_");
|
||||
varName = varName.replaceAll("\\.", "_DOT_");
|
||||
return varName;
|
||||
}
|
||||
|
||||
// for symbol, e.g. $, #
|
||||
if (getSymbolName(name) != null) {
|
||||
return getSymbolName(name).toUpperCase();
|
||||
}
|
||||
|
||||
// string
|
||||
String enumName = sanitizeName(underscore(name).toUpperCase());
|
||||
enumName = enumName.replaceFirst("^_", "");
|
||||
enumName = enumName.replaceFirst("_$", "");
|
||||
|
||||
if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number
|
||||
return escapeReservedWord(enumName);
|
||||
} else {
|
||||
return enumName;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumName(CodegenProperty property) {
|
||||
String enumName = underscore(toModelName(property.name)).toUpperCase();
|
||||
|
||||
// remove [] for array or map of enum
|
||||
enumName = enumName.replace("[]", "");
|
||||
|
||||
if (enumName.matches("\\d.*")) { // starts with number
|
||||
return "_" + enumName;
|
||||
} else {
|
||||
return enumName;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
|
||||
// process enum in models
|
||||
return postProcessModelsEnum(objs);
|
||||
}
|
||||
}
|
||||
|
@ -202,6 +202,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
|
||||
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
|
||||
additionalProperties.put("gson", "true");
|
||||
if ("retrofit2".equals(getLibrary())) {
|
||||
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
|
||||
}
|
||||
} else if ("jersey2".equals(getLibrary()) || "resteasy".equals(getLibrary())) {
|
||||
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
|
||||
additionalProperties.put("jackson", "true");
|
||||
@ -243,6 +246,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen
|
||||
|
||||
if (additionalProperties.containsKey("jackson") ) {
|
||||
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
|
||||
if ("threetenbp".equals(dateLibrary)) {
|
||||
supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,16 +1,22 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.codegen.CodegenModel;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenProperty;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.util.Yaml;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
|
||||
|
||||
@ -24,7 +30,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
|
||||
sourceFolder = "src/gen/java";
|
||||
apiTestTemplateFiles.clear(); // TODO: add test template
|
||||
embeddedTemplateDir = templateDir = "JavaInflector";
|
||||
invokerPackage = "io.swagger.handler";
|
||||
invokerPackage = "io.swagger.controllers";
|
||||
artifactId = "swagger-inflector-server";
|
||||
dateLibrary = "legacy"; //TODO: add joda support
|
||||
|
||||
@ -35,7 +41,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
|
||||
apiDocTemplateFiles.remove("api_doc.mustache");
|
||||
|
||||
|
||||
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
|
||||
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.controllers");
|
||||
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");
|
||||
|
||||
additionalProperties.put("title", title);
|
||||
@ -173,6 +179,11 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
|
||||
return objs;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getOrGenerateOperationId(Operation operation, String path, String httpMethod) {
|
||||
return super.getOrGenerateOperationId(operation, path, httpMethod.toUpperCase());
|
||||
}
|
||||
|
||||
public String apiFilename(String templateName, String tag) {
|
||||
String result = super.apiFilename(templateName, tag);
|
||||
|
||||
@ -204,7 +215,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen {
|
||||
if (name.length() == 0) {
|
||||
return "DefaultController";
|
||||
}
|
||||
name = name.replaceAll("[^a-zA-Z0-9]+", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
||||
name = name.replaceAll("[^a-zA-Z0-9]+", "_");
|
||||
return camelize(name)+ "Controller";
|
||||
}
|
||||
}
|
||||
|
@ -96,7 +96,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
protected String modelDocPath = "docs/";
|
||||
protected String apiTestPath = "api/";
|
||||
protected String modelTestPath = "model/";
|
||||
protected boolean useES6 = false; // default is ES5
|
||||
protected boolean useES6 = true; // default is ES6
|
||||
|
||||
public JavascriptClientCodegen() {
|
||||
super();
|
||||
@ -269,7 +269,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
if (additionalProperties.containsKey(USE_ES6)) {
|
||||
setUseES6(convertPropertyToBooleanAndWriteBack(USE_ES6));
|
||||
} else {
|
||||
setUseES6(false);
|
||||
setUseES6(true); // default to ES6
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -19,11 +19,12 @@ import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class);
|
||||
|
||||
protected String implFolder = "service";
|
||||
public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions";
|
||||
public static final String EXPORTED_NAME = "exportedName";
|
||||
|
||||
@ -81,16 +82,19 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
*/
|
||||
additionalProperties.put("apiVersion", apiVersion);
|
||||
additionalProperties.put("serverPort", serverPort);
|
||||
additionalProperties.put("implFolder", implFolder);
|
||||
|
||||
supportingFiles.add(new SupportingFile("writer.mustache", ("utils").replace(".", "/"), "writer.js"));
|
||||
|
||||
cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS,
|
||||
"When specified, it will generate the code which runs within Google Cloud Functions "
|
||||
+ "instead of standalone Node.JS server. See "
|
||||
+ "https://cloud.google.com/functions/docs/quickstart for the details of how to "
|
||||
+ "deploy the generated code."));
|
||||
"When specified, it will generate the code which runs within Google Cloud Functions "
|
||||
+ "instead of standalone Node.JS server. See "
|
||||
+ "https://cloud.google.com/functions/docs/quickstart for the details of how to "
|
||||
+ "deploy the generated code."));
|
||||
cliOptions.add(new CliOption(EXPORTED_NAME,
|
||||
"When the generated code will be deployed to Google Cloud Functions, this option can be "
|
||||
+ "used to update the name of the exported function. By default, it refers to the "
|
||||
+ "basePath. This does not affect normal standalone nodejs server code."));
|
||||
"When the generated code will be deployed to Google Cloud Functions, this option can be "
|
||||
+ "used to update the name of the exported function. By default, it refers to the "
|
||||
+ "basePath. This does not affect normal standalone nodejs server code."));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -145,6 +149,23 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
return toApiName(name);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String apiFilename(String templateName, String tag) {
|
||||
String result = super.apiFilename(templateName, tag);
|
||||
|
||||
if ( templateName.equals("service.mustache") ) {
|
||||
String stringToMatch = File.separator + "controllers" + File.separator;
|
||||
String replacement = File.separator + implFolder + File.separator;
|
||||
result = result.replaceAll(Pattern.quote(stringToMatch), replacement);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String implFileFolder(String output) {
|
||||
return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
|
||||
* those terms here. This logic is only called if a variable matches the reserved words
|
||||
@ -259,7 +280,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) {
|
||||
setGoogleCloudFunctions(
|
||||
Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString()));
|
||||
Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString()));
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(EXPORTED_NAME)) {
|
||||
@ -276,8 +297,8 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
// "controller.js")
|
||||
// );
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache",
|
||||
"api",
|
||||
"swagger.yaml")
|
||||
"api",
|
||||
"swagger.yaml")
|
||||
);
|
||||
if (getGoogleCloudFunctions()) {
|
||||
writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js"));
|
||||
@ -326,14 +347,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
if (!host.endsWith(".cloudfunctions.net")) {
|
||||
LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL.");
|
||||
}
|
||||
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
|
||||
if (!additionalProperties.containsKey(EXPORTED_NAME)) {
|
||||
String basePath = swagger.getBasePath();
|
||||
if (basePath == null || basePath.equals("/")) {
|
||||
LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name");
|
||||
basePath = "/openapi";
|
||||
}
|
||||
additionalProperties.put(EXPORTED_NAME, basePath.substring(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// need vendor extensions for x-swagger-router-controller
|
||||
@ -361,7 +382,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
|
||||
Swagger swagger = (Swagger)objs.get("swagger");
|
||||
if(swagger != null) {
|
||||
@ -370,7 +391,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
module.addSerializer(Double.class, new JsonSerializer<Double>() {
|
||||
@Override
|
||||
public void serialize(Double val, JsonGenerator jgen,
|
||||
SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
jgen.writeNumber(new BigDecimal(val));
|
||||
}
|
||||
});
|
||||
|
@ -300,12 +300,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
// make test path available in mustache template
|
||||
additionalProperties.put("testBasePath", testBasePath);
|
||||
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php"));
|
||||
supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php"));
|
||||
supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php"));
|
||||
supportingFiles.add(new SupportingFile("Configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php"));
|
||||
supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php"));
|
||||
supportingFiles.add(new SupportingFile("HeaderSelector.mustache", toPackagePath(invokerPackage, srcBasePath), "HeaderSelector.php"));
|
||||
supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json"));
|
||||
supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md"));
|
||||
supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist"));
|
||||
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));
|
||||
|
@ -459,7 +459,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// e.g. PhoneNumberApi.rb => phone_number_api.rb
|
||||
// e.g. PhoneNumberApi.py => phone_number_api.py
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@ -649,6 +649,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
p.example = example;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String sanitizeTag(String tag) {
|
||||
return sanitizeName(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeQuotationMark(String input) {
|
||||
// remove ' to avoid code injection
|
||||
|
@ -257,7 +257,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
return PREFIX + initialCaps(name);
|
||||
return modelNamePrefix + initialCaps(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -372,7 +372,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
} else {
|
||||
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
return modelNamePrefix + Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -9,6 +9,7 @@ import io.swagger.codegen.SupportingFile;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
@ -20,6 +21,7 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-scala-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String clientName = "AsyncClient";
|
||||
|
||||
public ScalaClientCodegen() {
|
||||
super();
|
||||
@ -51,10 +53,13 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
additionalProperties.put("asyncHttpClient", asyncHttpClient);
|
||||
additionalProperties.put("authScheme", authScheme);
|
||||
additionalProperties.put("authPreemptive", authPreemptive);
|
||||
additionalProperties.put("clientName", clientName);
|
||||
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
|
||||
supportingFiles.add(new SupportingFile("client.mustache",
|
||||
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala"));
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
// gradle settings
|
||||
@ -75,8 +80,8 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
importMapping.remove("Set");
|
||||
importMapping.remove("Map");
|
||||
|
||||
importMapping.put("DateTime", "org.joda.time.DateTime");
|
||||
importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer");
|
||||
importMapping.put("Date", "java.util.Date");
|
||||
importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer");
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("enum", "NSString");
|
||||
@ -90,7 +95,6 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
typeMapping.put("byte", "Byte");
|
||||
typeMapping.put("short", "Short");
|
||||
typeMapping.put("char", "Char");
|
||||
typeMapping.put("long", "Long");
|
||||
typeMapping.put("double", "Double");
|
||||
typeMapping.put("object", "Any");
|
||||
typeMapping.put("file", "File");
|
||||
@ -98,6 +102,10 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
// mapped to String as a workaround
|
||||
typeMapping.put("binary", "String");
|
||||
typeMapping.put("ByteArray", "String");
|
||||
typeMapping.put("date-time", "Date");
|
||||
// typeMapping.put("date", "Date");
|
||||
// typeMapping.put("Date", "Date");
|
||||
typeMapping.put("DateTime", "Date");
|
||||
|
||||
instantiationTypes.put("array", "ListBuffer");
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
@ -108,7 +116,6 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
|
||||
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
|
||||
}
|
||||
@ -183,7 +190,7 @@ public class ScalaClientCodegen extends AbstractScalaCodegen implements CodegenC
|
||||
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a Scala client library.";
|
||||
return "Generates a Scala client library (beta).";
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -32,6 +32,7 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
public static final String SPRING_MVC_LIBRARY = "spring-mvc";
|
||||
public static final String SPRING_CLOUD_LIBRARY = "spring-cloud";
|
||||
public static final String IMPLICIT_HEADERS = "implicitHeaders";
|
||||
public static final String SWAGGER_DOCKET_CONFIG = "swaggerDocketConfig";
|
||||
|
||||
protected String title = "swagger-petstore";
|
||||
protected String configPackage = "io.swagger.configuration";
|
||||
@ -45,6 +46,7 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
protected boolean useTags = false;
|
||||
protected boolean useBeanValidation = true;
|
||||
protected boolean implicitHeaders = false;
|
||||
protected boolean swaggerDocketConfig = false;
|
||||
protected boolean useOptional = false;
|
||||
|
||||
public SpringCodegen() {
|
||||
@ -75,6 +77,7 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames"));
|
||||
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
|
||||
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Use of @ApiImplicitParams for headers."));
|
||||
cliOptions.add(CliOption.newBoolean(SWAGGER_DOCKET_CONFIG, "Generate Spring Swagger Docket configuration class."));
|
||||
cliOptions.add(CliOption.newBoolean(USE_OPTIONAL,
|
||||
"Use Optional container for optional parameters"));
|
||||
|
||||
@ -107,6 +110,19 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
|
||||
// Process java8 option before common java ones to change the default dateLibrary to java8.
|
||||
if (additionalProperties.containsKey(JAVA_8)) {
|
||||
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
|
||||
}
|
||||
if (this.java8) {
|
||||
additionalProperties.put("javaVersion", "1.8");
|
||||
additionalProperties.put("jdk8", "true");
|
||||
if (!additionalProperties.containsKey(DATE_LIBRARY)) {
|
||||
setDateLibrary("java8");
|
||||
}
|
||||
}
|
||||
|
||||
super.processOpts();
|
||||
|
||||
// clear model and api doc template as this codegen
|
||||
@ -171,6 +187,10 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
this.setImplicitHeaders(Boolean.valueOf(additionalProperties.get(IMPLICIT_HEADERS).toString()));
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(SWAGGER_DOCKET_CONFIG)) {
|
||||
this.setSwaggerDocketConfig(Boolean.valueOf(additionalProperties.get(SWAGGER_DOCKET_CONFIG).toString()));
|
||||
}
|
||||
|
||||
typeMapping.put("file", "Resource");
|
||||
importMapping.put("Resource", "org.springframework.core.io.Resource");
|
||||
|
||||
@ -178,15 +198,15 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
writePropertyBack(USE_OPTIONAL, useOptional);
|
||||
}
|
||||
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
|
||||
if (this.interfaceOnly && this.delegatePattern) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, INTERFACE_ONLY));
|
||||
}
|
||||
|
||||
if (!this.interfaceOnly) {
|
||||
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
|
||||
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
|
||||
|
||||
if (library.equals(DEFAULT_LIBRARY)) {
|
||||
supportingFiles.add(new SupportingFile("homeController.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
|
||||
@ -234,8 +254,20 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
|
||||
}
|
||||
} else if ( this.swaggerDocketConfig && !library.equals(SPRING_CLOUD_LIBRARY)) {
|
||||
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
|
||||
}
|
||||
|
||||
if ("threetenbp".equals(dateLibrary)) {
|
||||
supportingFiles.add(new SupportingFile("customInstantDeserializer.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "CustomInstantDeserializer.java"));
|
||||
if (library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_CLOUD_LIBRARY)) {
|
||||
supportingFiles.add(new SupportingFile("jacksonConfiguration.mustache",
|
||||
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java"));
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.delegatePattern && this.java8) {
|
||||
additionalProperties.put("jdk8-no-delegate", true);
|
||||
}
|
||||
@ -576,6 +608,10 @@ public class SpringCodegen extends AbstractJavaCodegen
|
||||
this.implicitHeaders = implicitHeaders;
|
||||
}
|
||||
|
||||
public void setSwaggerDocketConfig(boolean swaggerDocketConfig) {
|
||||
this.swaggerDocketConfig = swaggerDocketConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
|
||||
super.postProcessModelProperty(model, property);
|
||||
|
@ -132,8 +132,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("array", "Array");
|
||||
typeMapping.put("List", "Array");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
typeMapping.put("date", "Date");
|
||||
typeMapping.put("Date", "Date");
|
||||
typeMapping.put("date", "ISOFullDate");
|
||||
typeMapping.put("DateTime", "Date");
|
||||
typeMapping.put("boolean", "Bool");
|
||||
typeMapping.put("string", "String");
|
||||
|
@ -119,8 +119,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("array", "Array");
|
||||
typeMapping.put("List", "Array");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
typeMapping.put("date", "NSDate");
|
||||
typeMapping.put("Date", "NSDate");
|
||||
typeMapping.put("date", "ISOFullDate");
|
||||
typeMapping.put("Date", "ISOFullDate");
|
||||
typeMapping.put("DateTime", "NSDate");
|
||||
typeMapping.put("boolean", "Bool");
|
||||
typeMapping.put("string", "String");
|
||||
|
@ -25,17 +25,15 @@ import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected static String PREFIX = "Sami";
|
||||
protected Set<String> foundationClasses = new HashSet<String>();
|
||||
protected String sourceFolder = "client";
|
||||
protected Map<String, String> namespaces = new HashMap<String, String>();
|
||||
protected static String PREFIX = "ArtikCloud";
|
||||
protected String sourceFolder = "src";
|
||||
protected String documentationFolder = "doc";
|
||||
|
||||
public TizenClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/tizen";
|
||||
outputFolder = "";
|
||||
modelTemplateFiles.put("model-header.mustache", ".h");
|
||||
modelTemplateFiles.put("model-body.mustache", ".cpp");
|
||||
apiTemplateFiles.put("api-header.mustache", ".h");
|
||||
@ -47,71 +45,72 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
Arrays.asList(
|
||||
"bool",
|
||||
"int",
|
||||
"long")
|
||||
"long long",
|
||||
"double",
|
||||
"float")
|
||||
);
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"bool",
|
||||
"int",
|
||||
"long long",
|
||||
"double",
|
||||
"float",
|
||||
"std::string")
|
||||
);
|
||||
languageSpecificPrimitives = new HashSet<String>();
|
||||
|
||||
additionalProperties().put("prefix", PREFIX);
|
||||
|
||||
setReservedWordsLowerCase(
|
||||
// VERIFY
|
||||
Arrays.asList(
|
||||
"void", "char", "short", "int", "void", "char", "short", "int",
|
||||
"long", "float", "double", "signed", "unsigned", "id", "const",
|
||||
"volatile", "in", "out", "inout", "bycopy", "byref", "oneway",
|
||||
"self", "super"
|
||||
"alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept",
|
||||
"auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t",
|
||||
"class", "compl", "concept", "const", "constexpr", "const_cast", "continue", "decltype", "default",
|
||||
"delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
|
||||
"float", "for", "friend", "goto", "if", "inline", "int", "import", "long", "module", "mutable",
|
||||
"namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private",
|
||||
"protected", "public", "register", "reinterpret_cast", "requires", "return", "short", "signed",
|
||||
"sizeof", "static", "static_assert", "static_cast", "struct", "switch", "synchronized", "template",
|
||||
"this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union",
|
||||
"unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"
|
||||
));
|
||||
|
||||
super.typeMapping = new HashMap<String, String>();
|
||||
|
||||
typeMapping.put("Date", "DateTime");
|
||||
typeMapping.put("DateTime", "DateTime");
|
||||
typeMapping.put("string", "String");
|
||||
typeMapping.put("integer", "Integer");
|
||||
typeMapping.put("float", "Float");
|
||||
typeMapping.put("long", "Long");
|
||||
typeMapping.put("boolean", "Boolean");
|
||||
typeMapping.put("double", "Double");
|
||||
typeMapping.put("array", "IList");
|
||||
typeMapping.put("map", "HashMap");
|
||||
typeMapping.put("number", "Long");
|
||||
typeMapping.put("object", PREFIX + "Object");
|
||||
typeMapping.put("UUID", "String");
|
||||
//TODO binary should be mapped to byte array
|
||||
// mapped to String as a workaround
|
||||
typeMapping.put("binary", "String");
|
||||
//typeMapping.put("Date", "DateTime");
|
||||
//typeMapping.put("DateTime", "DateTime");
|
||||
typeMapping.put("string", "std::string");
|
||||
typeMapping.put("integer", "int");
|
||||
typeMapping.put("float", "float");
|
||||
typeMapping.put("long", "long long");
|
||||
typeMapping.put("boolean", "bool");
|
||||
typeMapping.put("double", "double");
|
||||
typeMapping.put("array", "std::list");
|
||||
typeMapping.put("map", "std::map");
|
||||
typeMapping.put("number", "long long");
|
||||
typeMapping.put("object", "std::string");
|
||||
typeMapping.put("binary", "std::string");
|
||||
typeMapping.put("password", "std::string");
|
||||
//TODO:Maybe use better formats for dateTime?
|
||||
typeMapping.put("file", "std::string");
|
||||
typeMapping.put("DateTime", "std::string");
|
||||
typeMapping.put("Date", "std::string");
|
||||
typeMapping.put("UUID", "std::string");
|
||||
|
||||
importMapping = new HashMap<String, String>();
|
||||
|
||||
namespaces = new HashMap<String, String>();
|
||||
namespaces.put("DateTime", "Tizen::Base::DateTime");
|
||||
namespaces.put("Integer", "Tizen::Base::Integer");
|
||||
namespaces.put("Long", "Tizen::Base::Long");
|
||||
namespaces.put("Boolean", "Tizen::Base::Boolean");
|
||||
namespaces.put("Float", "Tizen::Base::Float");
|
||||
namespaces.put("String", "Tizen::Base::String");
|
||||
namespaces.put("Double", "Tizen::Base::Double");
|
||||
namespaces.put("IList", "Tizen::Base::Collection::IList");
|
||||
namespaces.put("HashMap", "Tizen::Base::Collection::HashMap");
|
||||
namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList");
|
||||
namespaces.put("JsonNumber", "Tizen::Web::Json");
|
||||
namespaces.put("JsonString", "Tizen::Web::Json");
|
||||
|
||||
foundationClasses = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"Integer",
|
||||
"Float")
|
||||
);
|
||||
supportingFiles.clear();
|
||||
supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
|
||||
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
|
||||
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
|
||||
supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h"));
|
||||
supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp"));
|
||||
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
|
||||
supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h"));
|
||||
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp"));
|
||||
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, "Helpers.h"));
|
||||
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, "Helpers.cpp"));
|
||||
supportingFiles.add(new SupportingFile("netclient-header.mustache", sourceFolder, "NetClient.h"));
|
||||
supportingFiles.add(new SupportingFile("netclient-body.mustache", sourceFolder, "NetClient.cpp"));
|
||||
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, "Object.h"));
|
||||
supportingFiles.add(new SupportingFile("requestinfo.mustache", sourceFolder, "RequestInfo.h"));
|
||||
supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, "Error.h"));
|
||||
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, "Error.cpp"));
|
||||
supportingFiles.add(new SupportingFile("Doxyfile.mustache", documentationFolder, "Doxyfile"));
|
||||
supportingFiles.add(new SupportingFile("generateDocumentation.mustache", documentationFolder, "generateDocumentation.sh"));
|
||||
supportingFiles.add(new SupportingFile("doc-readme.mustache", documentationFolder, "README.md"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -142,10 +141,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(String name) {
|
||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
||||
if (languageSpecificPrimitives.contains(name)) {
|
||||
return name;
|
||||
} else {
|
||||
return name + "*";
|
||||
return name + "";
|
||||
}
|
||||
}
|
||||
|
||||
@ -155,7 +154,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
} else {
|
||||
@ -167,10 +166,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
|
||||
if (languageSpecificPrimitives.contains(swaggerType)) {
|
||||
return toModelName(swaggerType);
|
||||
} else {
|
||||
return swaggerType + "*";
|
||||
return swaggerType + "";
|
||||
}
|
||||
}
|
||||
|
||||
@ -178,48 +177,48 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String toModelName(String type) {
|
||||
if (typeMapping.keySet().contains(type) ||
|
||||
typeMapping.values().contains(type) ||
|
||||
foundationClasses.contains(type) ||
|
||||
importMapping.values().contains(type) ||
|
||||
defaultIncludes.contains(type) ||
|
||||
languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
} else {
|
||||
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
if (namespaces.containsKey(name)) {
|
||||
return "using " + namespaces.get(name) + ";";
|
||||
if (name.equals("std::string")) {
|
||||
return "#include <string>";
|
||||
} else if (name.equals("std::map")) {
|
||||
return "#include <map>";
|
||||
} else if (name.equals("std::list")) {
|
||||
return "#include <list>";
|
||||
}
|
||||
return "#include \"" + name + ".h\"";
|
||||
}
|
||||
|
||||
//Might not be needed
|
||||
@Override
|
||||
public String toDefaultValue(Property p) {
|
||||
if (p instanceof StringProperty) {
|
||||
return "new String()";
|
||||
return "std::string()";
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "new Boolean(false)";
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "new DateTime()";
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "new DateTime()";
|
||||
return "bool(false)";
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "new Double()";
|
||||
return "double(0)";
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "new Float()";
|
||||
return "float(0)";
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "new Integer()";
|
||||
return "int(0)";
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "new Long()";
|
||||
return "long(0)";
|
||||
} else if (p instanceof DecimalProperty) {
|
||||
return "new Long()";
|
||||
return "long(0)";
|
||||
} else if (p instanceof MapProperty) {
|
||||
return "new HashMap()";
|
||||
return "new std::map()";
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
return "new ArrayList()";
|
||||
return "new std::list()";
|
||||
}
|
||||
// else
|
||||
if (p instanceof RefProperty) {
|
||||
@ -229,6 +228,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
return "null";
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + File.separator + sourceFolder;
|
||||
@ -241,24 +241,27 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
return PREFIX + initialCaps(name);
|
||||
return initialCaps(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
return PREFIX + initialCaps(name) + "Api";
|
||||
return initialCaps(name) + "Manager";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
return PREFIX + initialCaps(name) + "Api";
|
||||
return initialCaps(name) + "Manager";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
String paramName = name.replaceAll("[^a-zA-Z0-9_]", "");
|
||||
paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
|
||||
return "p" + paramName;
|
||||
paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1);
|
||||
if (isReservedWord(paramName)) {
|
||||
return escapeReservedWord(paramName);
|
||||
}
|
||||
return "" + paramName;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -272,27 +275,17 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// throw exception if method name is empty
|
||||
if (StringUtils.isEmpty(operationId)) {
|
||||
if (operationId=="") {
|
||||
throw new RuntimeException("Empty method name (operationId) not allowed");
|
||||
}
|
||||
|
||||
// method name cannot use reserved keyword, e.g. return$
|
||||
if (isReservedWord(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
operationId = escapeReservedWord(operationId);
|
||||
}
|
||||
|
||||
// add_pet_by_id => addPetById
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeQuotationMark(String input) {
|
||||
// remove " to avoid code injection
|
||||
return input.replace("\"", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeUnsafeCharacters(String input) {
|
||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
||||
}
|
||||
}
|
||||
|
@ -2,9 +2,12 @@ package io.swagger.codegen.languages;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenModel;
|
||||
@ -27,10 +30,12 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
public static final String NPM_REPOSITORY = "npmRepository";
|
||||
public static final String SNAPSHOT = "snapshot";
|
||||
public static final String WITH_INTERFACES = "withInterfaces";
|
||||
public static final String NG_VERSION = "ngVersion";
|
||||
|
||||
protected String npmName = null;
|
||||
protected String npmVersion = "1.0.0";
|
||||
protected String npmRepository = null;
|
||||
protected String ngVersion = "4";
|
||||
|
||||
public TypeScriptAngular2ClientCodegen() {
|
||||
super();
|
||||
@ -38,8 +43,9 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
|
||||
embeddedTemplateDir = templateDir = "typescript-angular2";
|
||||
modelTemplateFiles.put("model.mustache", ".ts");
|
||||
apiTemplateFiles.put("api.mustache", ".ts");
|
||||
typeMapping.put("Date","Date");
|
||||
apiTemplateFiles.put("api.service.mustache", ".ts");
|
||||
languageSpecificPrimitives.add("Blob");
|
||||
typeMapping.put("file","Blob");
|
||||
apiPackage = "api";
|
||||
modelPackage = "model";
|
||||
|
||||
@ -49,6 +55,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
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", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular (2 or 4). Default is '4'"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -59,12 +66,12 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "typescript-angular2";
|
||||
return "typescript-angular";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHelp() {
|
||||
return "Generates a TypeScript Angular2 client library.";
|
||||
return "Generates a TypeScript Angular (2.x or 4.x) client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -73,6 +80,8 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
|
||||
supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
|
||||
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
|
||||
supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts"));
|
||||
supportingFiles.add(new SupportingFile("rxjs-operators.mustache", getIndexDirectory(), "rxjs-operators.ts"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
|
||||
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
|
||||
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
|
||||
@ -88,6 +97,23 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
apiTemplateFiles.put("apiInterface.mustache", "Interface.ts");
|
||||
}
|
||||
}
|
||||
|
||||
// determine NG version
|
||||
if (additionalProperties.containsKey(NG_VERSION)) {
|
||||
if ("2".equals(additionalProperties.get(NG_VERSION).toString())) {
|
||||
additionalProperties.put("isNg2x", true);
|
||||
setNgVersion("2");
|
||||
} else if ("4".equals(additionalProperties.get(NG_VERSION).toString())) {
|
||||
additionalProperties.put("isNg4x", true);
|
||||
setNgVersion("4");
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid ngVersion, which must be either '2' or '4'");
|
||||
}
|
||||
} else {
|
||||
// default to 4
|
||||
additionalProperties.put("isNg4x", true);
|
||||
setNgVersion("4");
|
||||
}
|
||||
}
|
||||
|
||||
private void addNpmPackageGeneration() {
|
||||
@ -120,6 +146,11 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
return indexPackage.replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDataTypeFile(final String dataType) {
|
||||
return dataType != null && dataType.equals("Blob");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
Property inner;
|
||||
@ -131,7 +162,9 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
MapProperty mp = (MapProperty)p;
|
||||
inner = mp.getAdditionalProperties();
|
||||
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
|
||||
} else if(p instanceof FileProperty || p instanceof ObjectProperty) {
|
||||
} else if(p instanceof FileProperty) {
|
||||
return "Blob";
|
||||
} else if(p instanceof ObjectProperty) {
|
||||
return "any";
|
||||
} else {
|
||||
return super.getTypeDeclaration(p);
|
||||
@ -144,19 +177,13 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
|
||||
return swaggerType;
|
||||
}
|
||||
return addModelPrefix(swaggerType);
|
||||
applyLocalTypeMapping(swaggerType);
|
||||
return swaggerType;
|
||||
}
|
||||
|
||||
private String addModelPrefix(String swaggerType) {
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
|
||||
if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) {
|
||||
type = "models." + swaggerType;
|
||||
private String applyLocalTypeMapping(String type) {
|
||||
if (typeMapping.containsKey(type)) {
|
||||
type = typeMapping.get(type);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
@ -177,12 +204,16 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
@Override
|
||||
public void postProcessParameter(CodegenParameter parameter) {
|
||||
super.postProcessParameter(parameter);
|
||||
parameter.dataType = addModelPrefix(parameter.dataType);
|
||||
parameter.dataType = applyLocalTypeMapping(parameter.dataType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> operations) {
|
||||
Map<String, Object> objs = (Map<String, Object>) operations.get("operations");
|
||||
|
||||
// Add filename information for api imports
|
||||
objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString()));
|
||||
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) objs.get("operation");
|
||||
for (CodegenOperation op : ops) {
|
||||
// Convert httpMethod to Angular's RequestMethod enum
|
||||
@ -217,9 +248,81 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
op.path = op.path.replaceAll("\\{(.*?)\\}", "\\$\\{$1\\}");
|
||||
}
|
||||
|
||||
// Add additional filename information for model imports in the services
|
||||
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
|
||||
for(Map<String, Object> im : imports) {
|
||||
im.put("filename", im.get("import"));
|
||||
im.put("classname", getModelnameFromModelFilename(im.get("filename").toString()));
|
||||
}
|
||||
|
||||
return operations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
|
||||
Map<String, Object> result = super.postProcessModels(objs);
|
||||
|
||||
// Add additional filename information for imports
|
||||
List<Object> models = (List<Object>) postProcessModelsEnum(result).get("models");
|
||||
for (Object _mo : models) {
|
||||
Map<String, Object> mo = (Map<String, Object>) _mo;
|
||||
CodegenModel cm = (CodegenModel) mo.get("model");
|
||||
mo.put("tsImports", toTsImports(cm.imports));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Map<String, String>> toTsImports(Set<String> imports) {
|
||||
List<Map<String, String>> tsImports = new ArrayList<>();
|
||||
for(String im : imports) {
|
||||
HashMap<String, String> tsImport = new HashMap<>();
|
||||
tsImport.put("classname", im);
|
||||
tsImport.put("filename", toModelFilename(im));
|
||||
tsImports.add(tsImport);
|
||||
}
|
||||
return tsImports;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if (name.length() == 0) {
|
||||
return "DefaultService";
|
||||
}
|
||||
return initialCaps(name) + "Service";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
if (name.length() == 0) {
|
||||
return "default.service";
|
||||
}
|
||||
return camelize(name, true) + ".service";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiImport(String name) {
|
||||
return apiPackage() + "/" + toApiFilename(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
return camelize(toModelName(name), true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
return modelPackage() + "/" + toModelFilename(name);
|
||||
}
|
||||
|
||||
public String getNgVersion() {
|
||||
return ngVersion;
|
||||
}
|
||||
|
||||
public void setNgVersion(String ngVersion) {
|
||||
this.ngVersion = ngVersion;
|
||||
}
|
||||
|
||||
public String getNpmName() {
|
||||
return npmName;
|
||||
}
|
||||
@ -244,4 +347,14 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
this.npmRepository = npmRepository;
|
||||
}
|
||||
|
||||
private String getApiFilenameFromClassname(String classname) {
|
||||
String name = classname.substring(0, classname.length() - "Service".length());
|
||||
return toApiFilename(name);
|
||||
}
|
||||
|
||||
private String getModelnameFromModelFilename(String filename) {
|
||||
String name = filename.substring((modelPackage() + "/").length());
|
||||
return camelize(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "typescript-angular";
|
||||
return "typescript-angularjs";
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -42,6 +42,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
|
||||
supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json"));
|
||||
supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json"));
|
||||
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
|
||||
|
||||
if(additionalProperties.containsKey(NPM_NAME)) {
|
||||
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
|
||||
|
@ -1,5 +1,9 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.CodegenModel;
|
||||
import io.swagger.codegen.CodegenParameter;
|
||||
import io.swagger.models.ModelImpl;
|
||||
import io.swagger.models.properties.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -9,7 +13,6 @@ import java.util.Date;
|
||||
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
|
||||
public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
|
||||
@ -19,6 +22,7 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg
|
||||
public static final String NPM_VERSION = "npmVersion";
|
||||
public static final String NPM_REPOSITORY = "npmRepository";
|
||||
public static final String SNAPSHOT = "snapshot";
|
||||
public static final String JQUERY_ALREADY_IMPORTED = "jqueryAlreadyImported";
|
||||
|
||||
protected String npmName = null;
|
||||
protected String npmVersion = "1.0.0";
|
||||
@ -26,6 +30,13 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg
|
||||
|
||||
public TypeScriptJqueryClientCodegen() {
|
||||
super();
|
||||
|
||||
modelTemplateFiles.put("model.mustache", ".ts");
|
||||
apiTemplateFiles.put("api.mustache", ".ts");
|
||||
typeMapping.put("Date", "Date");
|
||||
apiPackage = "api";
|
||||
modelPackage = "model";
|
||||
|
||||
outputFolder = "generated-code/typescript-jquery";
|
||||
embeddedTemplateDir = templateDir = "typescript-jquery";
|
||||
|
||||
@ -33,23 +44,75 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg
|
||||
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", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
this.cliOptions.add(new CliOption(JQUERY_ALREADY_IMPORTED, "When using this in legacy app using mix of typescript and javascript, this will only declare jquery and not import it", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
|
||||
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
|
||||
supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
|
||||
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
|
||||
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
|
||||
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
|
||||
|
||||
LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME));
|
||||
if(additionalProperties.containsKey(NPM_NAME)) {
|
||||
if (additionalProperties.containsKey(NPM_NAME)) {
|
||||
addNpmPackageGeneration();
|
||||
}
|
||||
}
|
||||
|
||||
private String getIndexDirectory() {
|
||||
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
|
||||
return indexPackage.replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
|
||||
return swaggerType;
|
||||
}
|
||||
return addModelPrefix(swaggerType);
|
||||
}
|
||||
|
||||
private String addModelPrefix(String swaggerType) {
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
|
||||
if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) {
|
||||
type = "models." + swaggerType;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private boolean isLanguagePrimitive(String type) {
|
||||
return languageSpecificPrimitives.contains(type);
|
||||
}
|
||||
|
||||
private boolean isLanguageGenericType(String type) {
|
||||
for (String genericType : languageGenericTypes) {
|
||||
if (type.startsWith(genericType + "<")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessParameter(CodegenParameter parameter) {
|
||||
super.postProcessParameter(parameter);
|
||||
parameter.dataType = addModelPrefix(parameter.dataType);
|
||||
}
|
||||
|
||||
private void addNpmPackageGeneration() {
|
||||
if(additionalProperties.containsKey(NPM_NAME)) {
|
||||
if (additionalProperties.containsKey(NPM_NAME)) {
|
||||
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
|
||||
}
|
||||
|
||||
@ -77,6 +140,12 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg
|
||||
return indexPackage.replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) {
|
||||
codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties());
|
||||
addImport(codegenModel, codegenModel.additionalPropertiesType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "typescript-jquery";
|
||||
|
@ -1,14 +1,21 @@
|
||||
{{>licenseInfo}}
|
||||
package {{invokerPackage}};
|
||||
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.*;
|
||||
|
||||
{{/threetenbp}}
|
||||
import com.fasterxml.jackson.annotation.*;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
{{#joda}}
|
||||
import com.fasterxml.jackson.datatype.joda.JodaModule;
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
import com.fasterxml.jackson.datatype.jsr310.*;
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
import com.fasterxml.jackson.datatype.joda.*;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
{{/threetenbp}}
|
||||
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
|
||||
|
||||
import com.sun.jersey.api.client.Client;
|
||||
@ -72,12 +79,19 @@ public class ApiClient {
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
||||
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
||||
{{#joda}}
|
||||
objectMapper.registerModule(new JodaModule());
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
objectMapper.registerModule(new JavaTimeModule());
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
objectMapper.registerModule(new JodaModule());
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
objectMapper.registerModule(module);
|
||||
{{/threetenbp}}
|
||||
objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());
|
||||
|
||||
dateFormat = ApiClient.buildDefaultDateFormat();
|
||||
@ -393,62 +407,71 @@ public class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Format to {@code Pair} objects.
|
||||
* @param collectionFormat Collection format
|
||||
* @param name Name
|
||||
* @param value Value
|
||||
* @return List of pair
|
||||
/**
|
||||
* Formats the specified query parameter to a list containing a single {@code Pair} object.
|
||||
*
|
||||
* Note that {@code value} must not be a collection.
|
||||
*
|
||||
* @param name The name of the parameter.
|
||||
* @param value The value of the parameter.
|
||||
* @return A list containing a single {@code Pair} object.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||
public List<Pair> parameterToPair(String name, Object value) {
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null) return params;
|
||||
if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params;
|
||||
|
||||
Collection<?> valueCollection;
|
||||
if (value instanceof Collection<?>) {
|
||||
valueCollection = (Collection<?>) value;
|
||||
} else {
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the specified collection query parameters to a list of {@code Pair} objects.
|
||||
*
|
||||
* Note that the values of each of the returned Pair objects are percent-encoded.
|
||||
*
|
||||
* @param collectionFormat The collection format of the parameter.
|
||||
* @param name The name of the parameter.
|
||||
* @param value The value of the parameter.
|
||||
* @return A list of {@code Pair} objects.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Collection value) {
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null) {
|
||||
return params;
|
||||
}
|
||||
|
||||
if (valueCollection.isEmpty()){
|
||||
return params;
|
||||
}
|
||||
|
||||
// get the collection format
|
||||
String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
|
||||
|
||||
// create the params based on the collection format
|
||||
if ("multi".equals(format)) {
|
||||
for (Object item : valueCollection) {
|
||||
params.add(new Pair(name, parameterToString(item)));
|
||||
if ("multi".equals(collectionFormat)) {
|
||||
for (Object item : value) {
|
||||
params.add(new Pair(name, escapeString(parameterToString(item))));
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
// collectionFormat is assumed to be "csv" by default
|
||||
String delimiter = ",";
|
||||
|
||||
if ("csv".equals(format)) {
|
||||
delimiter = ",";
|
||||
} else if ("ssv".equals(format)) {
|
||||
delimiter = " ";
|
||||
} else if ("tsv".equals(format)) {
|
||||
delimiter = "\t";
|
||||
} else if ("pipes".equals(format)) {
|
||||
delimiter = "|";
|
||||
// escape all delimiters except commas, which are URI reserved
|
||||
// characters
|
||||
if ("ssv".equals(collectionFormat)) {
|
||||
delimiter = escapeString(" ");
|
||||
} else if ("tsv".equals(collectionFormat)) {
|
||||
delimiter = escapeString("\t");
|
||||
} else if ("pipes".equals(collectionFormat)) {
|
||||
delimiter = escapeString("|");
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder() ;
|
||||
for (Object item : valueCollection) {
|
||||
for (Object item : value) {
|
||||
sb.append(delimiter);
|
||||
sb.append(parameterToString(item));
|
||||
sb.append(escapeString(parameterToString(item)));
|
||||
}
|
||||
|
||||
params.add(new Pair(name, sb.substring(1)));
|
||||
params.add(new Pair(name, sb.substring(delimiter.length())));
|
||||
|
||||
return params;
|
||||
}
|
||||
@ -564,9 +587,10 @@ public class ApiClient {
|
||||
*
|
||||
* @param path The sub path
|
||||
* @param queryParams The query parameters
|
||||
* @param collectionQueryParams The collection query parameters
|
||||
* @return The full URL
|
||||
*/
|
||||
private String buildUrl(String path, List<Pair> queryParams) {
|
||||
private String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams) {
|
||||
final StringBuilder url = new StringBuilder();
|
||||
url.append(basePath).append(path);
|
||||
|
||||
@ -587,17 +611,34 @@ public class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) {
|
||||
String prefix = url.toString().contains("?") ? "&" : "?";
|
||||
for (Pair param : collectionQueryParams) {
|
||||
if (param.getValue() != null) {
|
||||
if (prefix != null) {
|
||||
url.append(prefix);
|
||||
prefix = null;
|
||||
} else {
|
||||
url.append("&");
|
||||
}
|
||||
String value = parameterToString(param.getValue());
|
||||
// collection query parameter value already escaped as part of parameterToPairs
|
||||
url.append(escapeString(param.getName())).append("=").append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
|
||||
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
|
||||
if (body != null && !formParams.isEmpty()) {
|
||||
throw new ApiException(500, "Cannot have body and form params");
|
||||
}
|
||||
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
final String url = buildUrl(path, queryParams);
|
||||
final String url = buildUrl(path, queryParams, collectionQueryParams);
|
||||
Builder builder;
|
||||
if (accept == null) {
|
||||
builder = httpClient.resource(url).getRequestBuilder();
|
||||
@ -640,6 +681,7 @@ public class ApiClient {
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param collectionQueryParams The collection query parameters
|
||||
* @param body The request body object - if it is not binary, otherwise null
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
@ -650,9 +692,9 @@ public class ApiClient {
|
||||
* @return The response body in type of string
|
||||
* @throws ApiException API exception
|
||||
*/
|
||||
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
|
||||
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
|
||||
|
||||
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
|
||||
ClientResponse response = getAPIResponse(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, accept, contentType, authNames);
|
||||
|
||||
statusCode = response.getStatusInfo().getStatusCode();
|
||||
responseHeaders = response.getHeaders();
|
||||
|
@ -0,0 +1,232 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonTokenId;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.DateTimeUtils;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.function.Function;
|
||||
import org.threeten.bp.DateTimeException;
|
||||
import org.threeten.bp.Instant;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.ZoneId;
|
||||
import org.threeten.bp.ZonedDateTime;
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
import org.threeten.bp.temporal.Temporal;
|
||||
import org.threeten.bp.temporal.TemporalAccessor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
|
||||
* Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format.
|
||||
*
|
||||
* @author Nick Williams
|
||||
*/
|
||||
public class CustomInstantDeserializer<T extends Temporal>
|
||||
extends ThreeTenDateTimeDeserializerBase<T> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final CustomInstantDeserializer<Instant> INSTANT = new CustomInstantDeserializer<Instant>(
|
||||
Instant.class, DateTimeFormatter.ISO_INSTANT,
|
||||
new Function<TemporalAccessor, Instant>() {
|
||||
@Override
|
||||
public Instant apply(TemporalAccessor temporalAccessor) {
|
||||
return Instant.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, Instant>() {
|
||||
@Override
|
||||
public Instant apply(FromIntegerArguments a) {
|
||||
return Instant.ofEpochMilli(a.value);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, Instant>() {
|
||||
@Override
|
||||
public Instant apply(FromDecimalArguments a) {
|
||||
return Instant.ofEpochSecond(a.integer, a.fraction);
|
||||
}
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
public static final CustomInstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new CustomInstantDeserializer<OffsetDateTime>(
|
||||
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
|
||||
new Function<TemporalAccessor, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(TemporalAccessor temporalAccessor) {
|
||||
return OffsetDateTime.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(FromIntegerArguments a) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(FromDecimalArguments a) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
|
||||
}
|
||||
},
|
||||
new BiFunction<OffsetDateTime, ZoneId, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(OffsetDateTime d, ZoneId z) {
|
||||
return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime()));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public static final CustomInstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new CustomInstantDeserializer<ZonedDateTime>(
|
||||
ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
|
||||
new Function<TemporalAccessor, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(TemporalAccessor temporalAccessor) {
|
||||
return ZonedDateTime.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(FromIntegerArguments a) {
|
||||
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(FromDecimalArguments a) {
|
||||
return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
|
||||
}
|
||||
},
|
||||
new BiFunction<ZonedDateTime, ZoneId, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) {
|
||||
return zonedDateTime.withZoneSameInstant(zoneId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
protected final Function<FromIntegerArguments, T> fromMilliseconds;
|
||||
|
||||
protected final Function<FromDecimalArguments, T> fromNanoseconds;
|
||||
|
||||
protected final Function<TemporalAccessor, T> parsedToValue;
|
||||
|
||||
protected final BiFunction<T, ZoneId, T> adjust;
|
||||
|
||||
protected CustomInstantDeserializer(Class<T> supportedType,
|
||||
DateTimeFormatter parser,
|
||||
Function<TemporalAccessor, T> parsedToValue,
|
||||
Function<FromIntegerArguments, T> fromMilliseconds,
|
||||
Function<FromDecimalArguments, T> fromNanoseconds,
|
||||
BiFunction<T, ZoneId, T> adjust) {
|
||||
super(supportedType, parser);
|
||||
this.parsedToValue = parsedToValue;
|
||||
this.fromMilliseconds = fromMilliseconds;
|
||||
this.fromNanoseconds = fromNanoseconds;
|
||||
this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
|
||||
@Override
|
||||
public T apply(T t, ZoneId zoneId) {
|
||||
return t;
|
||||
}
|
||||
} : adjust;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected CustomInstantDeserializer(CustomInstantDeserializer<T> base, DateTimeFormatter f) {
|
||||
super((Class<T>) base.handledType(), f);
|
||||
parsedToValue = base.parsedToValue;
|
||||
fromMilliseconds = base.fromMilliseconds;
|
||||
fromNanoseconds = base.fromNanoseconds;
|
||||
adjust = base.adjust;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
|
||||
if (dtf == _formatter) {
|
||||
return this;
|
||||
}
|
||||
return new CustomInstantDeserializer<T>(this, dtf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
|
||||
//string values have to be adjusted to the configured TZ.
|
||||
switch (parser.getCurrentTokenId()) {
|
||||
case JsonTokenId.ID_NUMBER_FLOAT: {
|
||||
BigDecimal value = parser.getDecimalValue();
|
||||
long seconds = value.longValue();
|
||||
int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds);
|
||||
return fromNanoseconds.apply(new FromDecimalArguments(
|
||||
seconds, nanoseconds, getZone(context)));
|
||||
}
|
||||
|
||||
case JsonTokenId.ID_NUMBER_INT: {
|
||||
long timestamp = parser.getLongValue();
|
||||
if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
|
||||
return this.fromNanoseconds.apply(new FromDecimalArguments(
|
||||
timestamp, 0, this.getZone(context)
|
||||
));
|
||||
}
|
||||
return this.fromMilliseconds.apply(new FromIntegerArguments(
|
||||
timestamp, this.getZone(context)
|
||||
));
|
||||
}
|
||||
|
||||
case JsonTokenId.ID_STRING: {
|
||||
String string = parser.getText().trim();
|
||||
if (string.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
if (string.endsWith("+0000")) {
|
||||
string = string.substring(0, string.length() - 5) + "Z";
|
||||
}
|
||||
T value;
|
||||
try {
|
||||
TemporalAccessor acc = _formatter.parse(string);
|
||||
value = parsedToValue.apply(acc);
|
||||
if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) {
|
||||
return adjust.apply(value, this.getZone(context));
|
||||
}
|
||||
} catch (DateTimeException e) {
|
||||
throw _peelDTE(e);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw context.mappingException("Expected type float, integer, or string.");
|
||||
}
|
||||
|
||||
private ZoneId getZone(DeserializationContext context) {
|
||||
// Instants are always in UTC, so don't waste compute cycles
|
||||
return (_valueClass == Instant.class) ? null : DateTimeUtils.timeZoneToZoneId(context.getTimeZone());
|
||||
}
|
||||
|
||||
private static class FromIntegerArguments {
|
||||
public final long value;
|
||||
public final ZoneId zoneId;
|
||||
|
||||
private FromIntegerArguments(long value, ZoneId zoneId) {
|
||||
this.value = value;
|
||||
this.zoneId = zoneId;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FromDecimalArguments {
|
||||
public final long integer;
|
||||
public final int fraction;
|
||||
public final ZoneId zoneId;
|
||||
|
||||
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
|
||||
this.integer = integer;
|
||||
this.fraction = fraction;
|
||||
this.zoneId = zoneId;
|
||||
}
|
||||
}
|
||||
}
|
@ -67,11 +67,12 @@ public class {{classname}} {
|
||||
|
||||
// query params
|
||||
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
|
||||
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
|
||||
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
|
||||
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
|
||||
|
||||
{{#queryParams}}
|
||||
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
|
||||
{{localVariablePrefix}}{{#collectionFormat}}localVarCollectionQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{{collectionFormat}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));
|
||||
{{/queryParams}}
|
||||
|
||||
{{#headerParams}}if ({{paramName}} != null)
|
||||
@ -96,9 +97,9 @@ public class {{classname}} {
|
||||
|
||||
{{#returnType}}
|
||||
GenericType<{{{returnType}}}> {{localVariablePrefix}}localVarReturnType = new GenericType<{{{returnType}}}>() {};
|
||||
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, {{localVariablePrefix}}localVarReturnType);
|
||||
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarCollectionQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, {{localVariablePrefix}}localVarReturnType);
|
||||
{{/returnType}}{{^returnType}}
|
||||
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, null);
|
||||
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarCollectionQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, null);
|
||||
{{/returnType}}
|
||||
}
|
||||
{{/operation}}
|
||||
|
@ -107,7 +107,7 @@ if(hasProperty('target') && target == 'android') {
|
||||
|
||||
ext {
|
||||
swagger_annotations_version = "1.5.15"
|
||||
jackson_version = "2.8.9"
|
||||
jackson_version = "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
|
||||
jersey_version = "1.19.4"
|
||||
jodatime_version = "2.9.9"
|
||||
junit_version = "4.12"
|
||||
@ -121,12 +121,16 @@ dependencies {
|
||||
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
|
||||
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
|
||||
{{#joda}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version",
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version",
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_version",
|
||||
{{/threetenbp}}
|
||||
{{^java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
|
||||
compile "joda-time:joda-time:$jodatime_version"
|
||||
compile "com.brsanthu:migbase64:2.2"
|
||||
{{/java8}}
|
||||
testCompile "junit:junit:$junit_version"
|
||||
|
@ -5,16 +5,22 @@ import java.util.Map;
|
||||
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.*;
|
||||
{{/threetenbp}}
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
import com.fasterxml.jackson.datatype.joda.JodaModule;
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
{{/threetenbp}}
|
||||
|
||||
import feign.Feign;
|
||||
import feign.RequestInterceptor;
|
||||
@ -149,12 +155,19 @@ public class ApiClient {
|
||||
objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.setDateFormat(new RFC3339DateFormat());
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
objectMapper.registerModule(new JodaModule());
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
objectMapper.registerModule(new JavaTimeModule());
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
objectMapper.registerModule(module);
|
||||
{{/threetenbp}}
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
|
@ -102,6 +102,9 @@ if(hasProperty('target') && target == 'android') {
|
||||
ext {
|
||||
swagger_annotations_version = "1.5.9"
|
||||
jackson_version = "2.8.7"
|
||||
{{#threetenbp}}
|
||||
threepane_version = "2.6.4"
|
||||
{{/threetenbp}}
|
||||
feign_version = "9.4.0"
|
||||
feign_form_version = "2.1.0"
|
||||
junit_version = "4.12"
|
||||
@ -117,7 +120,15 @@ dependencies {
|
||||
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}:$jackson_version"
|
||||
{{#joda}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threepane_version"
|
||||
{{/threetenbp}}
|
||||
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
|
||||
compile "com.brsanthu:migbase64:2.2"
|
||||
testCompile "junit:junit:$junit_version"
|
||||
|
@ -222,11 +222,27 @@
|
||||
</dependency>
|
||||
|
||||
{{/withXml}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}</artifactId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>${jackson-threetenbp-version}</version>
|
||||
</dependency>
|
||||
{{/threetenbp}}
|
||||
<dependency>
|
||||
<groupId>org.apache.oltu.oauth2</groupId>
|
||||
<artifactId>org.apache.oltu.oauth2.client</artifactId>
|
||||
@ -261,6 +277,9 @@
|
||||
<feign-version>9.4.0</feign-version>
|
||||
<feign-form-version>2.1.0</feign-form-version>
|
||||
<jackson-version>2.8.9</jackson-version>
|
||||
{{#threetenbp}}
|
||||
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
|
||||
{{/threetenbp}}
|
||||
<junit-version>4.12</junit-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<oltu-version>1.0.1</oltu-version>
|
||||
|
@ -1,13 +1,19 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.*;
|
||||
{{/threetenbp}}
|
||||
import com.fasterxml.jackson.annotation.*;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
{{#java8}}
|
||||
import com.fasterxml.jackson.datatype.jsr310.*;
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
import com.fasterxml.jackson.datatype.joda.*;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
{{/java8}}
|
||||
{{#joda}}
|
||||
import com.fasterxml.jackson.datatype.joda.JodaModule;
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
{{/threetenbp}}
|
||||
|
||||
import java.text.DateFormat;
|
||||
|
||||
@ -29,9 +35,16 @@ public class JSON implements ContextResolver<ObjectMapper> {
|
||||
{{#java8}}
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
mapper.registerModule(new JodaModule());
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
mapper.registerModule(module);
|
||||
{{/threetenbp}}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -108,9 +108,6 @@ ext {
|
||||
swagger_annotations_version = "1.5.15"
|
||||
jackson_version = "2.8.9"
|
||||
jersey_version = "2.25.1"
|
||||
{{^java8}}
|
||||
jodatime_version = "2.9.9"
|
||||
{{/java8}}
|
||||
{{#supportJava6}}
|
||||
commons_io_version=2.5
|
||||
commons_lang3_version=3.6
|
||||
@ -126,17 +123,21 @@ dependencies {
|
||||
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
|
||||
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
|
||||
{{#joda}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version",
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
|
||||
compile "joda-time:joda-time:$jodatime_version"
|
||||
compile "com.brsanthu:migbase64:2.2"
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version",
|
||||
{{/java8}}
|
||||
{{#supportJava6}}
|
||||
compile "commons-io:commons-io:$commons_io_version"
|
||||
compile "org.apache.commons:commons-lang3:$commons_lang3_version"
|
||||
{{/supportJava6}}
|
||||
{{#threetenbp}}
|
||||
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_version",
|
||||
{{/threetenbp}}
|
||||
{{^java8}}
|
||||
compile "com.brsanthu:migbase64:2.2"
|
||||
{{/java8}}
|
||||
testCompile "junit:junit:$junit_version"
|
||||
}
|
||||
|
@ -13,17 +13,21 @@ lazy val root = (project in file(".")).
|
||||
"org.glassfish.jersey.core" % "jersey-client" % "2.25.1",
|
||||
"org.glassfish.jersey.media" % "jersey-media-multipart" % "2.25.1",
|
||||
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.25.1",
|
||||
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.9",
|
||||
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.9",
|
||||
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9",
|
||||
"com.fasterxml.jackson.core" % "jackson-core" % "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}" % "compile",
|
||||
"com.fasterxml.jackson.core" % "jackson-annotations" % "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}" % "compile",
|
||||
"com.fasterxml.jackson.core" % "jackson-databind" % "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}" % "compile",
|
||||
{{#joda}}
|
||||
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.8.9" % "compile",
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.8.9",
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.8.9",
|
||||
"joda-time" % "joda-time" % "2.9.9",
|
||||
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.8.9" % "compile",
|
||||
{{/java8}}
|
||||
{{#threetenbp}}
|
||||
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
|
||||
{{/threetenbp}}
|
||||
{{^java8}}
|
||||
"com.brsanthu" % "migbase64" % "2.2",
|
||||
{{/java8}}
|
||||
{{#supportJava6}}
|
||||
"org.apache.commons" % "commons-lang3" % "3.6",
|
||||
"commons-io" % "commons-io" % "2.5",
|
||||
|
@ -232,6 +232,13 @@
|
||||
</dependency>
|
||||
|
||||
{{/withXml}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
@ -239,18 +246,14 @@
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${jodatime-version}</version>
|
||||
</dependency>
|
||||
|
||||
{{/threetenbp}}
|
||||
{{^java8}}
|
||||
<!-- Base64 encoding that works in both JVM and Android -->
|
||||
<dependency>
|
||||
<groupId>com.brsanthu</groupId>
|
||||
@ -258,21 +261,18 @@
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
|
||||
{{#supportJava6}}
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons_lang3_version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons_io_version}</version>
|
||||
</dependency>
|
||||
{{/supportJava6}}
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
@ -284,14 +284,11 @@
|
||||
<properties>
|
||||
<swagger-core-version>1.5.15</swagger-core-version>
|
||||
<jersey-version>2.25.1</jersey-version>
|
||||
<jackson-version>2.8.9</jackson-version>
|
||||
{{^java8}}
|
||||
<jodatime-version>2.9.9</jodatime-version>
|
||||
{{/java8}}
|
||||
{{#supportJava6}}
|
||||
<commons_io_version>2.5</commons_io_version>
|
||||
<commons_lang3_version>3.6</commons_lang3_version>
|
||||
{{/supportJava6}}
|
||||
<jackson-version>{{^threetenbp}}2.7.5{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}</jackson-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
</properties>
|
||||
|
@ -2,43 +2,31 @@
|
||||
|
||||
package {{invokerPackage}};
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
import com.squareup.okhttp.Callback;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.Response;
|
||||
import com.squareup.okhttp.RequestBody;
|
||||
import com.squareup.okhttp.FormEncodingBuilder;
|
||||
import com.squareup.okhttp.MultipartBuilder;
|
||||
import com.squareup.okhttp.MediaType;
|
||||
import com.squareup.okhttp.Headers;
|
||||
import com.squareup.okhttp.*;
|
||||
import com.squareup.okhttp.internal.http.HttpMethod;
|
||||
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
|
||||
import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;
|
||||
import okio.BufferedSink;
|
||||
import okio.Okio;
|
||||
{{#joda}}
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDate;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.LocalDate;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
{{/threetenbp}}
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.SecureRandom;
|
||||
@ -46,22 +34,17 @@ import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.text.ParseException;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
import okio.BufferedSink;
|
||||
import okio.Okio;
|
||||
{{#java8}}
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
{{/java8}}
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import {{invokerPackage}}.auth.Authentication;
|
||||
import {{invokerPackage}}.auth.HttpBasicAuth;
|
||||
@ -69,40 +52,8 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||
import {{invokerPackage}}.auth.OAuth;
|
||||
|
||||
public class ApiClient {
|
||||
public static final double JAVA_VERSION;
|
||||
public static final boolean IS_ANDROID;
|
||||
public static final int ANDROID_SDK_VERSION;
|
||||
|
||||
static {
|
||||
JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version"));
|
||||
boolean isAndroid;
|
||||
try {
|
||||
Class.forName("android.app.Activity");
|
||||
isAndroid = true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
isAndroid = false;
|
||||
}
|
||||
IS_ANDROID = isAndroid;
|
||||
int sdkVersion = 0;
|
||||
if (IS_ANDROID) {
|
||||
try {
|
||||
sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null));
|
||||
} catch (Exception e2) { }
|
||||
}
|
||||
}
|
||||
ANDROID_SDK_VERSION = sdkVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* The datetime format to be used when <code>lenientDatetimeFormat</code> is enabled.
|
||||
*/
|
||||
public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
|
||||
|
||||
private String basePath = "{{{basePath}}}";
|
||||
private boolean lenientOnJson = false;
|
||||
private boolean debugging = false;
|
||||
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||
private String tempFolderPath = null;
|
||||
@ -136,20 +87,7 @@ public class ApiClient {
|
||||
|
||||
verifyingSsl = true;
|
||||
|
||||
json = new JSON(this);
|
||||
|
||||
/*
|
||||
* Use RFC3339 format for date and datetime.
|
||||
* See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
|
||||
*/
|
||||
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
|
||||
// Always use UTC as the default time zone when dealing with date (without time).
|
||||
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
initDatetimeFormat();
|
||||
|
||||
// Be lenient on datetime formats when parsing datetime from string.
|
||||
// See <code>parseDatetime</code>.
|
||||
this.lenientDatetimeFormat = true;
|
||||
json = new JSON();
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
|
||||
@ -290,138 +228,42 @@ public class ApiClient {
|
||||
}
|
||||
|
||||
public ApiClient setDateFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
this.dateLength = this.dateFormat.format(new Date()).length();
|
||||
this.json.setDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public DateFormat getDatetimeFormat() {
|
||||
return datetimeFormat;
|
||||
}
|
||||
|
||||
public ApiClient setDatetimeFormat(DateFormat datetimeFormat) {
|
||||
this.datetimeFormat = datetimeFormat;
|
||||
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
|
||||
this.json.setSqlDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to allow various ISO 8601 datetime formats when parsing a datetime string.
|
||||
* @see #parseDatetime(String)
|
||||
* @return True if lenientDatetimeFormat flag is set to true
|
||||
*/
|
||||
public boolean isLenientDatetimeFormat() {
|
||||
return lenientDatetimeFormat;
|
||||
}
|
||||
|
||||
public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) {
|
||||
this.lenientDatetimeFormat = lenientDatetimeFormat;
|
||||
{{#joda}}
|
||||
public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setDateTimeFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given date string into Date object.
|
||||
* The default <code>dateFormat</code> supports these ISO 8601 date formats:
|
||||
* 2015-08-16
|
||||
* 2015-8-16
|
||||
* @param str String to be parsed
|
||||
* @return Date
|
||||
*/
|
||||
public Date parseDate(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
return dateFormat.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setLocalDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given datetime string into Date object.
|
||||
* When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported:
|
||||
* 2015-08-16T08:20:05Z
|
||||
* 2015-8-16T8:20:05Z
|
||||
* 2015-08-16T08:20:05+00:00
|
||||
* 2015-08-16T08:20:05+0000
|
||||
* 2015-08-16T08:20:05.376Z
|
||||
* 2015-08-16T08:20:05.376+00:00
|
||||
* 2015-08-16T08:20:05.376+00
|
||||
* Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
|
||||
* these formats:
|
||||
* Z (same with +0000)
|
||||
* +08:00 (same with +0800)
|
||||
* -02 (same with -0200)
|
||||
* -0200
|
||||
* @see <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>
|
||||
* @param str Date time string to be parsed
|
||||
* @return Date representation of the string
|
||||
*/
|
||||
public Date parseDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
|
||||
DateFormat format;
|
||||
if (lenientDatetimeFormat) {
|
||||
/*
|
||||
* When lenientDatetimeFormat is enabled, normalize the date string
|
||||
* into <code>LENIENT_DATETIME_FORMAT</code> to support various formats
|
||||
* defined by ISO 8601.
|
||||
*/
|
||||
// normalize time zone
|
||||
// trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("[zZ]\\z", "+0000");
|
||||
// remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
|
||||
// expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2})\\z", "$100");
|
||||
// add milliseconds when missing
|
||||
// 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
|
||||
str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
|
||||
format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT);
|
||||
} else {
|
||||
format = this.datetimeFormat;
|
||||
}
|
||||
|
||||
try {
|
||||
return format.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setOffsetDateTimeFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
/*
|
||||
* Parse date or date time in string format into Date object.
|
||||
*
|
||||
* @param str Date time string to be parsed
|
||||
* @return Date representation of the string
|
||||
*/
|
||||
public Date parseDateOrDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
else if (str.length() <= dateLength)
|
||||
return parseDate(str);
|
||||
else
|
||||
return parseDatetime(str);
|
||||
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setLocalDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string (Date format).
|
||||
*
|
||||
* @param date Date object
|
||||
* @return Formatted date in string representation
|
||||
*/
|
||||
public String formatDate(Date date) {
|
||||
return dateFormat.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string (Datetime format).
|
||||
*
|
||||
* @param date Date object
|
||||
* @return Formatted datetime in string representation
|
||||
*/
|
||||
public String formatDatetime(Date date) {
|
||||
return datetimeFormat.format(date);
|
||||
{{/jsr310}}
|
||||
public ApiClient setLenientOnJson(boolean lenientOnJson) {
|
||||
this.json.setLenientOnJson(lenientOnJson);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -541,26 +383,6 @@ public class ApiClient {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)">setLenient</a>
|
||||
*
|
||||
* @return True if lenientOnJson is enabled, false otherwise.
|
||||
*/
|
||||
public boolean isLenientOnJson() {
|
||||
return lenientOnJson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set LenientOnJson
|
||||
*
|
||||
* @param lenient True to enable lenientOnJson
|
||||
* @return ApiClient
|
||||
*/
|
||||
public ApiClient setLenientOnJson(boolean lenient) {
|
||||
this.lenientOnJson = lenient;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that whether debugging is enabled for this API client.
|
||||
*
|
||||
@ -644,8 +466,10 @@ public class ApiClient {
|
||||
public String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDatetime((Date) param);
|
||||
} else if (param instanceof Date {{#joda}}|| param instanceof DateTime || param instanceof LocalDate{{/joda}}{{#jsr310}}|| param instanceof OffsetDateTime || param instanceof LocalDate{{/jsr310}}) {
|
||||
//Serialize to json string and remove the " enclosing characters
|
||||
String jsonStr = json.serialize(param);
|
||||
return jsonStr.substring(1, jsonStr.length() - 1);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (Object o : (Collection)param) {
|
||||
@ -661,62 +485,70 @@ public class ApiClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* Format to {@code Pair} objects.
|
||||
* Formats the specified query parameter to a list containing a single {@code Pair} object.
|
||||
*
|
||||
* @param collectionFormat collection format (e.g. csv, tsv)
|
||||
* @param name Name
|
||||
* @param value Value
|
||||
* @return A list of Pair objects
|
||||
* Note that {@code value} must not be a collection.
|
||||
*
|
||||
* @param name The name of the parameter.
|
||||
* @param value The value of the parameter.
|
||||
* @return A list containing a single {@code Pair} object.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||
public List<Pair> parameterToPair(String name, Object value) {
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null) return params;
|
||||
if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params;
|
||||
|
||||
Collection valueCollection = null;
|
||||
if (value instanceof Collection) {
|
||||
valueCollection = (Collection) value;
|
||||
} else {
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the specified collection query parameters to a list of {@code Pair} objects.
|
||||
*
|
||||
* Note that the values of each of the returned Pair objects are percent-encoded.
|
||||
*
|
||||
* @param collectionFormat The collection format of the parameter.
|
||||
* @param name The name of the parameter.
|
||||
* @param value The value of the parameter.
|
||||
* @return A list of {@code Pair} objects.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Collection value) {
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null || value.isEmpty()) {
|
||||
return params;
|
||||
}
|
||||
|
||||
if (valueCollection.isEmpty()){
|
||||
return params;
|
||||
}
|
||||
|
||||
// get the collection format
|
||||
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
|
||||
|
||||
// create the params based on the collection format
|
||||
if (collectionFormat.equals("multi")) {
|
||||
for (Object item : valueCollection) {
|
||||
params.add(new Pair(name, parameterToString(item)));
|
||||
if ("multi".equals(collectionFormat)) {
|
||||
for (Object item : value) {
|
||||
params.add(new Pair(name, escapeString(parameterToString(item))));
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
// collectionFormat is assumed to be "csv" by default
|
||||
String delimiter = ",";
|
||||
|
||||
if (collectionFormat.equals("csv")) {
|
||||
delimiter = ",";
|
||||
} else if (collectionFormat.equals("ssv")) {
|
||||
delimiter = " ";
|
||||
} else if (collectionFormat.equals("tsv")) {
|
||||
delimiter = "\t";
|
||||
} else if (collectionFormat.equals("pipes")) {
|
||||
delimiter = "|";
|
||||
// escape all delimiters except commas, which are URI reserved
|
||||
// characters
|
||||
if ("ssv".equals(collectionFormat)) {
|
||||
delimiter = escapeString(" ");
|
||||
} else if ("tsv".equals(collectionFormat)) {
|
||||
delimiter = escapeString("\t");
|
||||
} else if ("pipes".equals(collectionFormat)) {
|
||||
delimiter = escapeString("|");
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder() ;
|
||||
for (Object item : valueCollection) {
|
||||
for (Object item : value) {
|
||||
sb.append(delimiter);
|
||||
sb.append(parameterToString(item));
|
||||
sb.append(escapeString(parameterToString(item)));
|
||||
}
|
||||
|
||||
params.add(new Pair(name, sb.substring(1)));
|
||||
params.add(new Pair(name, sb.substring(delimiter.length())));
|
||||
|
||||
return params;
|
||||
}
|
||||
@ -1076,6 +908,7 @@ public class ApiClient {
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param collectionQueryParams The collection query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
@ -1084,8 +917,8 @@ public class ApiClient {
|
||||
* @return The HTTP call
|
||||
* @throws ApiException If fail to serialize the request body object
|
||||
*/
|
||||
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
|
||||
Request request = buildRequest(path, method, queryParams, body, headerParams, formParams, authNames, progressRequestListener);
|
||||
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
|
||||
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, authNames, progressRequestListener);
|
||||
|
||||
return httpClient.newCall(request);
|
||||
}
|
||||
@ -1096,6 +929,7 @@ public class ApiClient {
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param collectionQueryParams The collection query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
@ -1104,10 +938,10 @@ public class ApiClient {
|
||||
* @return The HTTP request
|
||||
* @throws ApiException If fail to serialize the request body object
|
||||
*/
|
||||
public Request buildRequest(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
|
||||
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
final String url = buildUrl(path, queryParams);
|
||||
final String url = buildUrl(path, queryParams, collectionQueryParams);
|
||||
final Request.Builder reqBuilder = new Request.Builder().url(url);
|
||||
processHeaderParams(headerParams, reqBuilder);
|
||||
|
||||
@ -1153,9 +987,10 @@ public class ApiClient {
|
||||
*
|
||||
* @param path The sub path
|
||||
* @param queryParams The query parameters
|
||||
* @param collectionQueryParams The collection query parameters
|
||||
* @return The full URL
|
||||
*/
|
||||
public String buildUrl(String path, List<Pair> queryParams) {
|
||||
public String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams) {
|
||||
final StringBuilder url = new StringBuilder();
|
||||
url.append(basePath).append(path);
|
||||
|
||||
@ -1176,6 +1011,23 @@ public class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) {
|
||||
String prefix = url.toString().contains("?") ? "&" : "?";
|
||||
for (Pair param : collectionQueryParams) {
|
||||
if (param.getValue() != null) {
|
||||
if (prefix != null) {
|
||||
url.append(prefix);
|
||||
prefix = null;
|
||||
} else {
|
||||
url.append("&");
|
||||
}
|
||||
String value = parameterToString(param.getValue());
|
||||
// collection query parameter value already escaped as part of parameterToPairs
|
||||
url.append(escapeString(param.getName())).append("=").append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
@ -1263,31 +1115,6 @@ public class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize datetime format according to the current environment, e.g. Java 1.7 and Android.
|
||||
*/
|
||||
private void initDatetimeFormat() {
|
||||
String formatWithTimeZone = null;
|
||||
if (IS_ANDROID) {
|
||||
if (ANDROID_SDK_VERSION >= 18) {
|
||||
// The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18)
|
||||
formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
|
||||
}
|
||||
} else if (JAVA_VERSION >= 1.7) {
|
||||
// The time zone format "XXX" is available since Java 1.7
|
||||
formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
|
||||
}
|
||||
if (formatWithTimeZone != null) {
|
||||
this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone);
|
||||
// NOTE: Use the system's default time zone (mainly for datetime formatting).
|
||||
} else {
|
||||
// Use a common format that works across all systems.
|
||||
this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
// Always use the UTC time zone as we are using a constant trailing "Z" here.
|
||||
this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply SSL related settings to httpClient according to the current values of
|
||||
* verifyingSsl and sslCaCert.
|
||||
|
@ -4,55 +4,62 @@ package {{invokerPackage}};
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.internal.bind.util.ISO8601Utils;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDate;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.LocalDate;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
{{/threetenbp}}
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.ParsePosition;
|
||||
{{#java8}}
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
{{/java8}}
|
||||
import java.util.Date;
|
||||
|
||||
public class JSON {
|
||||
private ApiClient apiClient;
|
||||
private Gson gson;
|
||||
private boolean isLenientOnJson = false;
|
||||
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
|
||||
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
|
||||
{{#joda}}
|
||||
private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter();
|
||||
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
|
||||
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
|
||||
{{/jsr310}}
|
||||
|
||||
/**
|
||||
* JSON constructor.
|
||||
*
|
||||
* @param apiClient An instance of ApiClient
|
||||
*/
|
||||
public JSON(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
public JSON() {
|
||||
gson = new GsonBuilder()
|
||||
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
|
||||
{{^java8}}
|
||||
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
|
||||
{{/java8}}
|
||||
{{#java8}}
|
||||
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
|
||||
{{/java8}}
|
||||
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
|
||||
.registerTypeAdapter(Date.class, dateTypeAdapter)
|
||||
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
|
||||
{{#joda}}
|
||||
.registerTypeAdapter(DateTime.class, dateTimeTypeAdapter)
|
||||
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
|
||||
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
|
||||
{{/jsr310}}
|
||||
.create();
|
||||
}
|
||||
|
||||
@ -69,9 +76,16 @@ public class JSON {
|
||||
* Set Gson.
|
||||
*
|
||||
* @param gson Gson
|
||||
* @return JSON
|
||||
*/
|
||||
public void setGson(Gson gson) {
|
||||
public JSON setGson(Gson gson) {
|
||||
this.gson = gson;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setLenientOnJson(boolean lenientOnJson) {
|
||||
isLenientOnJson = lenientOnJson;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -87,15 +101,15 @@ public class JSON {
|
||||
/**
|
||||
* Deserialize the given JSON string to Java object.
|
||||
*
|
||||
* @param <T> Type
|
||||
* @param body The JSON string
|
||||
* @param <T> Type
|
||||
* @param body The JSON string
|
||||
* @param returnType The type to deserialize into
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T deserialize(String body, Type returnType) {
|
||||
try {
|
||||
if (apiClient.isLenientOnJson()) {
|
||||
if (isLenientOnJson) {
|
||||
JsonReader jsonReader = new JsonReader(new StringReader(body));
|
||||
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
|
||||
jsonReader.setLenient(true);
|
||||
@ -105,187 +119,326 @@ public class JSON {
|
||||
}
|
||||
} catch (JsonParseException e) {
|
||||
// Fallback processing when failed to parse JSON form response body:
|
||||
// return the response body string directly for the String return type;
|
||||
// parse response body into date or datetime for the Date return type.
|
||||
// return the response body string directly for the String return type;
|
||||
if (returnType.equals(String.class))
|
||||
return (T) body;
|
||||
else if (returnType.equals(Date.class))
|
||||
return (T) apiClient.parseDateOrDatetime(body);
|
||||
else throw(e);
|
||||
else throw (e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
|
||||
private final ApiClient apiClient;
|
||||
|
||||
{{#joda}}
|
||||
/**
|
||||
* Constructor for DateAdapter
|
||||
*
|
||||
* @param apiClient Api client
|
||||
* Gson TypeAdapter for Joda DateTime type
|
||||
*/
|
||||
public DateAdapter(ApiClient apiClient) {
|
||||
super();
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
public static class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
|
||||
|
||||
/**
|
||||
* Serialize
|
||||
*
|
||||
* @param src Date
|
||||
* @param typeOfSrc Type
|
||||
* @param context Json Serialization Context
|
||||
* @return Json Element
|
||||
*/
|
||||
@Override
|
||||
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
if (src == null) {
|
||||
return JsonNull.INSTANCE;
|
||||
} else {
|
||||
return new JsonPrimitive(apiClient.formatDatetime(src));
|
||||
private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser();
|
||||
private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime();
|
||||
|
||||
public DateTimeTypeAdapter() {
|
||||
this(ISODateTimeFormat.dateTime().withOffsetParsed());
|
||||
}
|
||||
|
||||
public DateTimeTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, DateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(printFormatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return parseFormatter.parseDateTime(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize
|
||||
*
|
||||
* @param json Json element
|
||||
* @param date Type
|
||||
* @param context Json Serialization Context
|
||||
* @return Date
|
||||
* @throws JsonParseException if fail to parse
|
||||
* Gson TypeAdapter for Joda LocalDate type
|
||||
*/
|
||||
@Override
|
||||
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
|
||||
String str = json.getAsJsonPrimitive().getAsString();
|
||||
try {
|
||||
return apiClient.parseDateOrDatetime(str);
|
||||
} catch (RuntimeException e) {
|
||||
throw new JsonParseException(e);
|
||||
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public LocalDateTypeAdapter() {
|
||||
this(ISODateTimeFormat.date());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{{^java8}}
|
||||
/**
|
||||
* Gson TypeAdapter for Joda DateTime type
|
||||
*/
|
||||
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
|
||||
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser();
|
||||
private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime();
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, DateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(printFormatter.print(date));
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return formatter.parseLocalDate(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return parseFormatter.parseDateTime(date);
|
||||
}
|
||||
public JSON setDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
dateTimeTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for Joda LocalDate type
|
||||
*/
|
||||
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
localDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
/**
|
||||
* Gson TypeAdapter for JSR310 OffsetDateTime type
|
||||
*/
|
||||
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.print(date));
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public OffsetDateTimeTypeAdapter() {
|
||||
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
|
||||
}
|
||||
|
||||
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OffsetDateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
if (date.endsWith("+0000")) {
|
||||
date = date.substring(0, date.length()-5) + "Z";
|
||||
}
|
||||
return OffsetDateTime.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return formatter.parseLocalDate(date);
|
||||
/**
|
||||
* Gson TypeAdapter for JSR310 LocalDate type
|
||||
*/
|
||||
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public LocalDateTypeAdapter() {
|
||||
this(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
}
|
||||
}
|
||||
}
|
||||
{{/java8}}
|
||||
{{#java8}}
|
||||
/**
|
||||
* Gson TypeAdapter for jsr310 OffsetDateTime type
|
||||
*/
|
||||
class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
|
||||
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
|
||||
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return LocalDate.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OffsetDateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
if (date.endsWith("+0000")) {
|
||||
date = date.substring(0, date.length()-5) + "Z";
|
||||
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
offsetDateTimeTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
localDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{/jsr310}}
|
||||
/**
|
||||
* Gson TypeAdapter for java.sql.Date type
|
||||
* If the dateFormat is null, a simple "yyyy-MM-dd" format will be used
|
||||
* (more efficient than SimpleDateFormat).
|
||||
*/
|
||||
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
|
||||
|
||||
private DateFormat dateFormat;
|
||||
|
||||
public SqlDateTypeAdapter() {
|
||||
}
|
||||
|
||||
public SqlDateTypeAdapter(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
public void setFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, java.sql.Date date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
String value;
|
||||
if (dateFormat != null) {
|
||||
value = dateFormat.format(date);
|
||||
} else {
|
||||
value = date.toString();
|
||||
}
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
return OffsetDateTime.parse(date, formatter);
|
||||
@Override
|
||||
public java.sql.Date read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
try {
|
||||
if (dateFormat != null) {
|
||||
return new java.sql.Date(dateFormat.parse(date).getTime());
|
||||
}
|
||||
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
|
||||
} catch (ParseException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for java.util.Date type
|
||||
* If the dateFormat is null, ISO8601Utils will be used.
|
||||
*/
|
||||
public static class DateTypeAdapter extends TypeAdapter<Date> {
|
||||
|
||||
private DateFormat dateFormat;
|
||||
|
||||
public DateTypeAdapter() {
|
||||
}
|
||||
|
||||
public DateTypeAdapter(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
public void setFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, Date date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
String value;
|
||||
if (dateFormat != null) {
|
||||
value = dateFormat.format(date);
|
||||
} else {
|
||||
value = ISO8601Utils.format(date, true);
|
||||
}
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date read(JsonReader in) throws IOException {
|
||||
try {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
try {
|
||||
if (dateFormat != null) {
|
||||
return dateFormat.parse(date);
|
||||
}
|
||||
return ISO8601Utils.parse(date, new ParsePosition(0));
|
||||
} catch (ParseException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSON setDateFormat(DateFormat dateFormat) {
|
||||
dateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setSqlDateFormat(DateFormat dateFormat) {
|
||||
sqlDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for jsr310 LocalDate type
|
||||
*/
|
||||
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return LocalDate.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
{{/java8}}
|
||||
|
@ -78,9 +78,10 @@ public class {{classname}} {
|
||||
String {{localVariablePrefix}}localVarPath = "{{{path}}}"{{#pathParams}}
|
||||
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
|
||||
|
||||
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
|
||||
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
|
||||
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
|
||||
if ({{paramName}} != null)
|
||||
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
|
||||
{{localVariablePrefix}}{{#collectionFormat}}localVarCollectionQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{{collectionFormat}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));{{/queryParams}}
|
||||
|
||||
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
|
||||
if ({{paramName}} != null)
|
||||
@ -115,7 +116,7 @@ public class {{classname}} {
|
||||
}
|
||||
|
||||
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
|
||||
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
|
||||
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarCollectionQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@ -225,4 +226,4 @@ public class {{classname}} {
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
{{/operations}}
|
@ -104,8 +104,11 @@ dependencies {
|
||||
compile 'com.squareup.okhttp:okhttp:2.7.5'
|
||||
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
|
||||
compile 'com.google.code.gson:gson:2.8.1'
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
compile 'joda-time:joda-time:2.9.9'
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
compile 'org.threeten:threetenbp:1.3.5'
|
||||
{{/threetenbp}}
|
||||
testCompile 'junit:junit:4.12'
|
||||
}
|
||||
|
@ -13,9 +13,12 @@ lazy val root = (project in file(".")).
|
||||
"com.squareup.okhttp" % "okhttp" % "2.7.5",
|
||||
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
|
||||
"com.google.code.gson" % "gson" % "2.8.1",
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
"joda-time" % "joda-time" % "2.9.9" % "compile",
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
"org.threeten" % "threetenbp" % "1.3.5" % "compile",
|
||||
{{/threetenbp}}
|
||||
"junit" % "junit" % "4.12" % "test",
|
||||
"com.novocode" % "junit-interface" % "0.10" % "test"
|
||||
)
|
||||
|
@ -189,13 +189,20 @@
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson-version}</version>
|
||||
</dependency>
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${jodatime-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>org.threeten</groupId>
|
||||
<artifactId>threetenbp</artifactId>
|
||||
<version>${threetenbp-version}</version>
|
||||
</dependency>
|
||||
{{/threetenbp}}
|
||||
{{#useBeanValidation}}
|
||||
<!-- Bean Validation API support -->
|
||||
<dependency>
|
||||
@ -242,7 +249,12 @@
|
||||
<swagger-core-version>1.5.15</swagger-core-version>
|
||||
<okhttp-version>2.7.5</okhttp-version>
|
||||
<gson-version>2.8.1</gson-version>
|
||||
{{#joda}}
|
||||
<jodatime-version>2.9.9</jodatime-version>
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<threetenbp-version>1.3.5</threetenbp-version>
|
||||
{{/threetenbp}}
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
@ -33,6 +33,13 @@ import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.*;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
{{/threetenbp}}
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
@ -312,6 +319,14 @@ public class ApiClient {
|
||||
*/
|
||||
public ApiClient setDateFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
{{#threetenbp}}
|
||||
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
|
||||
if(converter instanceof AbstractJackson2HttpMessageConverter){
|
||||
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
|
||||
mapper.setDateFormat(dateFormat);
|
||||
}
|
||||
}
|
||||
{{/threetenbp}}
|
||||
return this;
|
||||
}
|
||||
|
||||
@ -567,6 +582,18 @@ public class ApiClient {
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate(messageConverters);
|
||||
{{/withXml}}{{^withXml}}RestTemplate restTemplate = new RestTemplate();{{/withXml}}
|
||||
{{#threetenbp}}
|
||||
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
|
||||
if(converter instanceof AbstractJackson2HttpMessageConverter){
|
||||
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
mapper.registerModule(module);
|
||||
}
|
||||
}
|
||||
{{/threetenbp}}
|
||||
// This allows us to read the response more than once - Necessary for debugging.
|
||||
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
|
||||
return restTemplate;
|
||||
@ -640,4 +667,4 @@ public class ApiClient {
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -111,6 +111,9 @@ ext {
|
||||
spring_web_version = "4.3.9.RELEASE"
|
||||
jodatime_version = "2.9.9"
|
||||
junit_version = "4.12"
|
||||
{{#threetenbp}}
|
||||
jackson_threeten_version = "2.6.4"
|
||||
{{/threetenbp}}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@ -123,10 +126,13 @@ dependencies {
|
||||
{{#java8}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
|
||||
compile "joda-time:joda-time:$jodatime_version"
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version"
|
||||
{{/threetenbp}}
|
||||
{{#withXml}}
|
||||
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jackson_version"
|
||||
{{/withXml}}
|
||||
|
@ -235,7 +235,7 @@
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
@ -246,7 +246,14 @@
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${jodatime-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>${jackson-threetenbp-version}</version>
|
||||
</dependency>
|
||||
{{/threetenbp}}
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
@ -261,9 +268,12 @@
|
||||
<swagger-annotations-version>1.5.15</swagger-annotations-version>
|
||||
<spring-web-version>4.3.9.RELEASE</spring-web-version>
|
||||
<jackson-version>2.8.9</jackson-version>
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
<jodatime-version>2.9.9</jodatime-version>
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
|
||||
{{/threetenbp}}
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
</properties>
|
||||
|
@ -1,25 +1,19 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonParseException;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
|
||||
{{^java8}}
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDate;
|
||||
{{#joda}}
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
{{/java8}}
|
||||
{{#java8}}
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
{{/threetenbp}}
|
||||
import retrofit2.Converter;
|
||||
import retrofit2.Retrofit;
|
||||
{{#useRxJava}}
|
||||
@ -30,29 +24,28 @@ import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
|
||||
{{/useRxJava2}}
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
import retrofit2.converter.scalars.ScalarsConverterFactory;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
|
||||
import {{invokerPackage}}.auth.HttpBasicAuth;
|
||||
import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||
import {{invokerPackage}}.auth.OAuth;
|
||||
import {{invokerPackage}}.auth.OAuth.AccessTokenListener;
|
||||
import {{invokerPackage}}.auth.OAuthFlow;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.text.DateFormat;
|
||||
{{#java8}}
|
||||
import java.time.format.DateTimeFormatter;
|
||||
{{/java8}}
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ApiClient {
|
||||
|
||||
private Map<String, Interceptor> apiAuthorizations;
|
||||
private OkHttpClient.Builder okBuilder;
|
||||
private Retrofit.Builder adapterBuilder;
|
||||
private JSON json;
|
||||
|
||||
public ApiClient() {
|
||||
apiAuthorizations = new LinkedHashMap<String, Interceptor>();
|
||||
@ -65,18 +58,19 @@ public class ApiClient {
|
||||
{{#hasAuthMethods}}
|
||||
Interceptor auth;
|
||||
{{#authMethods}}if ("{{name}}".equals(authName)) {
|
||||
{{#isBasic}}
|
||||
{{#isBasic}}
|
||||
auth = new HttpBasicAuth();
|
||||
{{/isBasic}}
|
||||
{{#isApiKey}}
|
||||
{{/isBasic}}
|
||||
{{#isApiKey}}
|
||||
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");
|
||||
{{/isApiKey}}
|
||||
{{#isOAuth}}
|
||||
{{/isApiKey}}
|
||||
{{#isOAuth}}
|
||||
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");
|
||||
{{/isOAuth}}
|
||||
{{/isOAuth}}
|
||||
} else {{/authMethods}}{
|
||||
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
|
||||
}
|
||||
|
||||
addAuthorization(authName, auth);
|
||||
{{/hasAuthMethods}}
|
||||
{{^hasAuthMethods}}
|
||||
@ -132,21 +126,11 @@ public class ApiClient {
|
||||
}
|
||||
|
||||
public void createDefaultAdapter() {
|
||||
Gson gson = new GsonBuilder()
|
||||
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
|
||||
{{^java8}}
|
||||
.registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
|
||||
{{/java8}}
|
||||
{{#java8}}
|
||||
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
|
||||
{{/java8}}
|
||||
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
|
||||
.create();
|
||||
|
||||
json = new JSON();
|
||||
okBuilder = new OkHttpClient.Builder();
|
||||
|
||||
String baseUrl = "{{{basePath}}}";
|
||||
if(!baseUrl.endsWith("/"))
|
||||
if (!baseUrl.endsWith("/"))
|
||||
baseUrl = baseUrl + "/";
|
||||
|
||||
adapterBuilder = new Retrofit
|
||||
@ -154,12 +138,11 @@ public class ApiClient {
|
||||
.baseUrl(baseUrl)
|
||||
{{#useRxJava}}
|
||||
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
|
||||
{{/useRxJava}}
|
||||
{{#useRxJava2}}
|
||||
{{/useRxJava}}{{#useRxJava2}}
|
||||
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
|
||||
{{/useRxJava2}}
|
||||
.addConverterFactory(ScalarsConverterFactory.create())
|
||||
.addConverterFactory(GsonCustomConverterFactory.create(gson));
|
||||
.addConverterFactory(GsonCustomConverterFactory.create(json.getGson()));
|
||||
}
|
||||
|
||||
public <S> S createService(Class<S> serviceClass) {
|
||||
@ -167,41 +150,79 @@ public class ApiClient {
|
||||
.client(okBuilder.build())
|
||||
.build()
|
||||
.create(serviceClass);
|
||||
|
||||
}
|
||||
|
||||
public ApiClient setDateFormat(DateFormat dateFormat) {
|
||||
this.json.setDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
|
||||
this.json.setSqlDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{#joda}}
|
||||
public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setDateTimeFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setLocalDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setOffsetDateTimeFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
this.json.setLocalDateFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{/jsr310}}
|
||||
|
||||
/**
|
||||
* Helper method to configure the first api key found
|
||||
* @param apiKey API key
|
||||
* @return ApiClient
|
||||
*/
|
||||
private void setApiKey(String apiKey) {
|
||||
public ApiClient setApiKey(String apiKey) {
|
||||
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
|
||||
if (apiAuthorization instanceof ApiKeyAuth) {
|
||||
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
|
||||
keyAuth.setApiKey(apiKey);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to configure the username/password for basic auth or password oauth
|
||||
* @param username Username
|
||||
* @param password Password
|
||||
* @return ApiClient
|
||||
*/
|
||||
private void setCredentials(String username, String password) {
|
||||
public ApiClient setCredentials(String username, String password) {
|
||||
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
|
||||
if (apiAuthorization instanceof HttpBasicAuth) {
|
||||
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
|
||||
basicAuth.setCredentials(username, password);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
if (apiAuthorization instanceof OAuth) {
|
||||
OAuth oauth = (OAuth) apiAuthorization;
|
||||
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -235,15 +256,17 @@ public class ApiClient {
|
||||
/**
|
||||
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
|
||||
* @param accessToken Access token
|
||||
* @return ApiClient
|
||||
*/
|
||||
public void setAccessToken(String accessToken) {
|
||||
public ApiClient setAccessToken(String accessToken) {
|
||||
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
|
||||
if (apiAuthorization instanceof OAuth) {
|
||||
OAuth oauth = (OAuth) apiAuthorization;
|
||||
oauth.setAccessToken(accessToken);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -251,8 +274,9 @@ public class ApiClient {
|
||||
* @param clientId Client ID
|
||||
* @param clientSecret Client secret
|
||||
* @param redirectURI Redirect URI
|
||||
* @return ApiClient
|
||||
*/
|
||||
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
|
||||
public ApiClient configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
|
||||
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
|
||||
if (apiAuthorization instanceof OAuth) {
|
||||
OAuth oauth = (OAuth) apiAuthorization;
|
||||
@ -263,52 +287,59 @@ public class ApiClient {
|
||||
oauth.getAuthenticationRequestBuilder()
|
||||
.setClientId(clientId)
|
||||
.setRedirectURI(redirectURI);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a listener which is notified when a new access token is received.
|
||||
* @param accessTokenListener Access token listener
|
||||
* @return ApiClient
|
||||
*/
|
||||
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
|
||||
public ApiClient registerAccessTokenListener(AccessTokenListener accessTokenListener) {
|
||||
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
|
||||
if (apiAuthorization instanceof OAuth) {
|
||||
OAuth oauth = (OAuth) apiAuthorization;
|
||||
oauth.registerAccessTokenListener(accessTokenListener);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an authorization to be used by the client
|
||||
* @param authName Authentication name
|
||||
* @param authorization Authorization interceptor
|
||||
* @return ApiClient
|
||||
*/
|
||||
public void addAuthorization(String authName, Interceptor authorization) {
|
||||
public ApiClient addAuthorization(String authName, Interceptor authorization) {
|
||||
if (apiAuthorizations.containsKey(authName)) {
|
||||
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
|
||||
}
|
||||
apiAuthorizations.put(authName, authorization);
|
||||
okBuilder.addInterceptor(authorization);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<String, Interceptor> getApiAuthorizations() {
|
||||
return apiAuthorizations;
|
||||
}
|
||||
|
||||
public void setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
|
||||
public ApiClient setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
|
||||
this.apiAuthorizations = apiAuthorizations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Retrofit.Builder getAdapterBuilder() {
|
||||
return adapterBuilder;
|
||||
}
|
||||
|
||||
public void setAdapterBuilder(Retrofit.Builder adapterBuilder) {
|
||||
public ApiClient setAdapterBuilder(Retrofit.Builder adapterBuilder) {
|
||||
this.adapterBuilder = adapterBuilder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OkHttpClient.Builder getOkBuilder() {
|
||||
@ -337,7 +368,6 @@ public class ApiClient {
|
||||
* expected type is String, then just return the body string.
|
||||
*/
|
||||
class GsonResponseBodyConverterToString<T> implements Converter<ResponseBody, T> {
|
||||
|
||||
private final Gson gson;
|
||||
private final Type type;
|
||||
|
||||
@ -357,8 +387,8 @@ class GsonResponseBodyConverterToString<T> implements Converter<ResponseBody, T>
|
||||
}
|
||||
}
|
||||
|
||||
class GsonCustomConverterFactory extends Converter.Factory {
|
||||
|
||||
class GsonCustomConverterFactory extends Converter.Factory
|
||||
{
|
||||
private final Gson gson;
|
||||
private final GsonConverterFactory gsonConverterFactory;
|
||||
|
||||
@ -386,126 +416,3 @@ class GsonCustomConverterFactory extends Converter.Factory {
|
||||
return gsonConverterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
|
||||
}
|
||||
}
|
||||
|
||||
{{^java8}}
|
||||
/**
|
||||
* Gson TypeAdapter for Joda DateTime type
|
||||
*/
|
||||
class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
|
||||
|
||||
private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser();
|
||||
private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime();
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, DateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(printFormatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return parseFormatter.parseDateTime(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for Joda LocalDate type
|
||||
*/
|
||||
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private final DateTimeFormatter formatter = ISODateTimeFormat.date();
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return formatter.parseLocalDate(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
{{/java8}}
|
||||
{{#java8}}
|
||||
/**
|
||||
* Gson TypeAdapter for jsr310 OffsetDateTime type
|
||||
*/
|
||||
class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
|
||||
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OffsetDateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
if (date.endsWith("+0000")) {
|
||||
date = date.substring(0, date.length()-5) + "Z";
|
||||
}
|
||||
return OffsetDateTime.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for jsr310 LocalDate type
|
||||
*/
|
||||
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return LocalDate.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
{{/java8}}
|
||||
|
@ -0,0 +1,399 @@
|
||||
{{>licenseInfo}}
|
||||
|
||||
package {{invokerPackage}};
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.internal.bind.util.ISO8601Utils;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
{{#joda}}
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDate;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.LocalDate;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
{{/threetenbp}}
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.ParsePosition;
|
||||
{{#java8}}
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
{{/java8}}
|
||||
import java.util.Date;
|
||||
|
||||
public class JSON {
|
||||
private Gson gson;
|
||||
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
|
||||
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
|
||||
{{#joda}}
|
||||
private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter();
|
||||
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
|
||||
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
|
||||
{{/jsr310}}
|
||||
|
||||
public JSON() {
|
||||
gson = new GsonBuilder()
|
||||
.registerTypeAdapter(Date.class, dateTypeAdapter)
|
||||
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
|
||||
{{#joda}}
|
||||
.registerTypeAdapter(DateTime.class, dateTimeTypeAdapter)
|
||||
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
|
||||
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
|
||||
{{/jsr310}}
|
||||
.create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Gson.
|
||||
*
|
||||
* @return Gson
|
||||
*/
|
||||
public Gson getGson() {
|
||||
return gson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Gson.
|
||||
*
|
||||
* @param gson Gson
|
||||
* @return JSON
|
||||
*/
|
||||
public JSON setGson(Gson gson) {
|
||||
this.gson = gson;
|
||||
return this;
|
||||
}
|
||||
|
||||
{{#joda}}
|
||||
/**
|
||||
* Gson TypeAdapter for Joda DateTime type
|
||||
*/
|
||||
public static class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public DateTimeTypeAdapter() {
|
||||
this(ISODateTimeFormat.dateTime().withOffsetParsed());
|
||||
}
|
||||
|
||||
public DateTimeTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, DateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return formatter.parseDateTime(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for Joda LocalDate type
|
||||
*/
|
||||
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public LocalDateTypeAdapter() {
|
||||
this(ISODateTimeFormat.date());
|
||||
}
|
||||
|
||||
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.print(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return formatter.parseLocalDate(date);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSON setDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
dateTimeTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
localDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{/joda}}
|
||||
{{#jsr310}}
|
||||
/**
|
||||
* Gson TypeAdapter for JSR310 OffsetDateTime type
|
||||
*/
|
||||
public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public OffsetDateTimeTypeAdapter() {
|
||||
this(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
|
||||
}
|
||||
|
||||
public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, OffsetDateTime date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OffsetDateTime read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
if (date.endsWith("+0000")) {
|
||||
date = date.substring(0, date.length()-5) + "Z";
|
||||
}
|
||||
return OffsetDateTime.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for JSR310 LocalDate type
|
||||
*/
|
||||
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
|
||||
|
||||
private DateTimeFormatter formatter;
|
||||
|
||||
public LocalDateTypeAdapter() {
|
||||
this(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
}
|
||||
|
||||
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
public void setFormat(DateTimeFormatter dateFormat) {
|
||||
this.formatter = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, LocalDate date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(formatter.format(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
return LocalDate.parse(date, formatter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
|
||||
offsetDateTimeTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
|
||||
localDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
{{/jsr310}}
|
||||
/**
|
||||
* Gson TypeAdapter for java.sql.Date type
|
||||
* If the dateFormat is null, a simple "yyyy-MM-dd" format will be used
|
||||
* (more efficient than SimpleDateFormat).
|
||||
*/
|
||||
public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> {
|
||||
|
||||
private DateFormat dateFormat;
|
||||
|
||||
public SqlDateTypeAdapter() {
|
||||
}
|
||||
|
||||
public SqlDateTypeAdapter(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
public void setFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, java.sql.Date date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
String value;
|
||||
if (dateFormat != null) {
|
||||
value = dateFormat.format(date);
|
||||
} else {
|
||||
value = date.toString();
|
||||
}
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.sql.Date read(JsonReader in) throws IOException {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
try {
|
||||
if (dateFormat != null) {
|
||||
return new java.sql.Date(dateFormat.parse(date).getTime());
|
||||
}
|
||||
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
|
||||
} catch (ParseException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gson TypeAdapter for java.util.Date type
|
||||
* If the dateFormat is null, ISO8601Utils will be used.
|
||||
*/
|
||||
public static class DateTypeAdapter extends TypeAdapter<Date> {
|
||||
|
||||
private DateFormat dateFormat;
|
||||
|
||||
public DateTypeAdapter() {
|
||||
}
|
||||
|
||||
public DateTypeAdapter(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
public void setFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, Date date) throws IOException {
|
||||
if (date == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
String value;
|
||||
if (dateFormat != null) {
|
||||
value = dateFormat.format(date);
|
||||
} else {
|
||||
value = ISO8601Utils.format(date, true);
|
||||
}
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date read(JsonReader in) throws IOException {
|
||||
try {
|
||||
switch (in.peek()) {
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
default:
|
||||
String date = in.nextString();
|
||||
try {
|
||||
if (dateFormat != null) {
|
||||
return dateFormat.parse(date);
|
||||
}
|
||||
return ISO8601Utils.parse(date, new ParsePosition(0));
|
||||
} catch (ParseException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSON setDateFormat(DateFormat dateFormat) {
|
||||
dateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON setSqlDateFormat(DateFormat dateFormat) {
|
||||
sqlDateTypeAdapter.setFormat(dateFormat);
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
@ -2,9 +2,15 @@ package {{package}};
|
||||
|
||||
import {{invokerPackage}}.CollectionFormats.*;
|
||||
|
||||
{{#useRxJava}}import rx.Observable;{{/useRxJava}}
|
||||
{{#useRxJava2}}import io.reactivex.Observable;{{/useRxJava2}}
|
||||
{{#doNotUseRx}}import retrofit2.Call;{{/doNotUseRx}}
|
||||
{{#useRxJava}}
|
||||
import rx.Observable;
|
||||
{{/useRxJava}}
|
||||
{{#useRxJava2}}
|
||||
import io.reactivex.Observable;
|
||||
{{/useRxJava2}}
|
||||
{{#doNotUseRx}}
|
||||
import retrofit2.Call;
|
||||
{{/doNotUseRx}}
|
||||
import retrofit2.http.*;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
|
@ -25,7 +25,8 @@ public class {{classname}}Test {
|
||||
api = new ApiClient().createService({{classname}}.class);
|
||||
}
|
||||
|
||||
{{#operations}}{{#operation}}
|
||||
{{#operations}}
|
||||
{{#operation}}
|
||||
/**
|
||||
* {{summary}}
|
||||
*
|
||||
@ -40,5 +41,6 @@ public class {{classname}}Test {
|
||||
|
||||
// TODO: test validations
|
||||
}
|
||||
{{/operation}}{{/operations}}
|
||||
{{/operation}}
|
||||
{{/operations}}
|
||||
}
|
||||
|
@ -117,9 +117,12 @@ ext {
|
||||
{{#useRxJava2}}
|
||||
rx_java_version = "2.1.1"
|
||||
{{/useRxJava2}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
jodatime_version = "2.9.9"
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
threetenbp_version = "1.3.5"
|
||||
{{/threetenbp}}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@ -136,9 +139,12 @@ dependencies {
|
||||
{{/useRxJava2}}
|
||||
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
|
||||
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
compile "joda-time:joda-time:$jodatime_version"
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
compile "org.threeten:threetenbp:$threetenbp_version"
|
||||
{{/threetenbp}}
|
||||
{{#usePlay24WS}}
|
||||
compile "com.typesafe.play:play-java-ws_2.11:$play_version"
|
||||
compile "com.squareup.retrofit2:converter-jackson:$retrofit_version"
|
||||
|
@ -25,7 +25,7 @@ lazy val root = (project in file(".")).
|
||||
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9" % "compile",
|
||||
{{/usePlay24WS}}
|
||||
{{#useRxJava}}
|
||||
"com.squareup.retrofit2" % "adapter-rxjava" % "{{^usePlay24WS}}2.2.0{{/usePlay24WS}}{{#usePlay24WS}}2.1.0{{/usePlay24WS}}" % "compile",
|
||||
"com.squareup.retrofit2" % "adapter-rxjava" % "{{^usePlay24WS}}2.3.0{{/usePlay24WS}}{{#usePlay24WS}}2.1.0{{/usePlay24WS}}" % "compile",
|
||||
"io.reactivex" % "rxjava" % "1.3.0" % "compile",
|
||||
{{/useRxJava}}
|
||||
{{#useRxJava2}}
|
||||
@ -34,9 +34,12 @@ lazy val root = (project in file(".")).
|
||||
{{/useRxJava2}}
|
||||
"io.swagger" % "swagger-annotations" % "1.5.15" % "compile",
|
||||
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
"joda-time" % "joda-time" % "2.9.9" % "compile",
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
"org.threeten" % "threetenbp" % "1.3.5" % "compile",
|
||||
{{/threetenbp}}
|
||||
"junit" % "junit" % "4.12" % "test",
|
||||
"com.novocode" % "junit-interface" % "0.11" % "test"
|
||||
)
|
||||
|
@ -194,13 +194,20 @@
|
||||
<artifactId>org.apache.oltu.oauth2.client</artifactId>
|
||||
<version>${oltu-version}</version>
|
||||
</dependency>
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${jodatime-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>org.threeten</groupId>
|
||||
<artifactId>threetenbp</artifactId>
|
||||
<version>${threetenbp-version}</version>
|
||||
</dependency>
|
||||
{{/threetenbp}}
|
||||
{{#useRxJava}}
|
||||
<dependency>
|
||||
<groupId>io.reactivex</groupId>
|
||||
@ -305,9 +312,12 @@
|
||||
{{#useRxJava2}}
|
||||
<rxjava-version>2.1.1</rxjava-version>
|
||||
{{/useRxJava2}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
<jodatime-version>2.9.9</jodatime-version>
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
<threetenbp-version>1.3.5</threetenbp-version>
|
||||
{{/threetenbp}}
|
||||
<oltu-version>1.0.1</oltu-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
</properties>
|
||||
|
@ -233,6 +233,13 @@
|
||||
</dependency>
|
||||
|
||||
{{/withXml}}
|
||||
{{#joda}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#java8}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
@ -240,18 +247,14 @@
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#threetenbp}}
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${jodatime-version}</version>
|
||||
</dependency>
|
||||
|
||||
{{/threetenbp}}
|
||||
{{^java8}}
|
||||
<!-- Base64 encoding that works in both JVM and Android -->
|
||||
<dependency>
|
||||
<groupId>com.brsanthu</groupId>
|
||||
@ -259,14 +262,12 @@
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
|
||||
{{#supportJava6}}
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons_lang3_version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
@ -282,7 +283,6 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
{{/useBeanValidation}}
|
||||
|
||||
{{#parcelableModel}}
|
||||
<!-- Needed for Parcelable support-->
|
||||
<dependency>
|
||||
@ -292,7 +292,6 @@
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
{{/parcelableModel}}
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
@ -305,14 +304,11 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<swagger-annotations-version>1.5.15</swagger-annotations-version>
|
||||
<jersey-version>1.19.4</jersey-version>
|
||||
<jackson-version>2.8.9</jackson-version>
|
||||
{{^java8}}
|
||||
<jodatime-version>2.9.9</jodatime-version>
|
||||
{{/java8}}
|
||||
{{#supportJava6}}
|
||||
<commons_io_version>2.5</commons_io_version>
|
||||
<commons_lang3_version>3.6</commons_lang3_version>
|
||||
{{/supportJava6}}
|
||||
<jackson-version>{{^threetenbp}}2.7.5{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}</jackson-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
</properties>
|
||||
|
@ -241,7 +241,7 @@
|
||||
<spring-version>4.3.9.RELEASE</spring-version>
|
||||
{{/generateSpringApplication}}
|
||||
{{#generateSpringBootApplication}}
|
||||
<spring.boot-version>1.4.7.RELEASE</spring.boot-version>
|
||||
<spring.boot-version>1.5.4.RELEASE</spring.boot-version>
|
||||
{{/generateSpringBootApplication}}
|
||||
<cxf-version>3.1.11</cxf-version>
|
||||
<jackson-jaxrs-version>2.8.9</jackson-jaxrs-version>
|
||||
|
@ -14,6 +14,7 @@ dependencies {
|
||||
providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final'
|
||||
providedCompile 'javax.annotation:javax.annotation-api:1.2'
|
||||
providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final'
|
||||
compile 'io.swagger:swagger-annotations:1.5.10'
|
||||
compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final'
|
||||
{{#joda}}
|
||||
compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.4.1'
|
||||
|
@ -49,6 +49,11 @@
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger-core-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
|
@ -21,6 +21,9 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
{{^useSpringCloudClient}}
|
||||
import java.io.IOException;
|
||||
{{/useSpringCloudClient}}
|
||||
|
||||
import java.util.List;
|
||||
{{#useOptional}}
|
||||
@ -48,20 +51,31 @@ public interface {{classname}} {
|
||||
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} })
|
||||
@ApiResponses(value = { {{#responses}}
|
||||
@ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{dataType}}}.class{{#containerType}}, responseContainer = "{{{containerType}}}"{{/containerType}}){{#hasMore}},{{/hasMore}}{{/responses}} })
|
||||
{{#implicitHeaders}}@ApiImplicitParams({
|
||||
{{#implicitHeaders}}
|
||||
@ApiImplicitParams({
|
||||
{{#headerParams}}{{>implicitHeader}}{{/headerParams}}
|
||||
}){{/implicitHeaders}}
|
||||
})
|
||||
{{/implicitHeaders}}
|
||||
@RequestMapping(value = "{{{path}}}",{{#singleContentTypes}}
|
||||
produces = "{{{vendorExtensions.x-accepts}}}",
|
||||
consumes = "{{{vendorExtensions.x-contentType}}}",{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}
|
||||
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
|
||||
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
|
||||
method = RequestMethod.{{httpMethod}})
|
||||
{{#useSpringCloudClient}}
|
||||
{{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} {
|
||||
// do some magic!
|
||||
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};
|
||||
}{{/jdk8}}
|
||||
|
||||
{{/useSpringCloudClient}}
|
||||
{{^useSpringCloudClient}}
|
||||
{{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}} @RequestHeader(value = "Accept", required = false) String accept) throws Exception{{^jdk8}};{{/jdk8}}{{#jdk8}} {
|
||||
// do some magic!
|
||||
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};
|
||||
}{{/jdk8}}
|
||||
|
||||
{{/useSpringCloudClient}}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -24,7 +24,12 @@ import java.util.Optional;
|
||||
{{/useOptional}}
|
||||
{{#async}}
|
||||
import java.util.concurrent.Callable;
|
||||
{{/async}}{{/jdk8-no-delegate}}
|
||||
{{/async}}
|
||||
{{/jdk8-no-delegate}}
|
||||
{{^useSpringCloudClient}}
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
{{/useSpringCloudClient}}
|
||||
{{#useBeanValidation}}
|
||||
import javax.validation.constraints.*;
|
||||
import javax.validation.Valid;
|
||||
@ -33,27 +38,72 @@ import javax.validation.Valid;
|
||||
@Controller
|
||||
{{#operations}}
|
||||
public class {{classname}}Controller implements {{classname}} {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public {{classname}}Controller(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
{{#isDelegate}}
|
||||
private final {{classname}}Delegate delegate;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public {{classname}}Controller({{classname}}Delegate delegate) {
|
||||
this.delegate = delegate;
|
||||
}{{/isDelegate}}
|
||||
}
|
||||
|
||||
{{^jdk8-no-delegate}}{{#operation}}
|
||||
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
|
||||
{{/hasMore}}{{/allParams}}) {
|
||||
// do some magic!{{^isDelegate}}{{^async}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}}
|
||||
{{/isDelegate}}
|
||||
{{^jdk8-no-delegate}}
|
||||
{{#operation}}
|
||||
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},
|
||||
{{/allParams}}@RequestHeader(value = "Accept", required = false) String accept) throws Exception {
|
||||
// do some magic!
|
||||
{{#useSpringCloudClient}}
|
||||
{{^isDelegate}}
|
||||
{{^async}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
{{/async}}
|
||||
{{#async}}
|
||||
return new Callable<ResponseEntity<{{>returnTypes}}>>() {
|
||||
@Override
|
||||
public ResponseEntity<{{>returnTypes}}> call() throws Exception {
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
}
|
||||
};{{/async}}{{/isDelegate}}{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/isDelegate}}
|
||||
};
|
||||
{{/async}}
|
||||
{{/isDelegate}}
|
||||
{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{/isDelegate}}
|
||||
{{/useSpringCloudClient}}
|
||||
{{^useSpringCloudClient}}
|
||||
{{^isDelegate}}
|
||||
{{^async}}
|
||||
{{#examples}}
|
||||
|
||||
if (accept != null && accept.contains("{{{contentType}}}")) {
|
||||
return new ResponseEntity<{{>returnTypes}}>(objectMapper.readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.OK);
|
||||
}
|
||||
|
||||
{{/examples}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
{{/async}}
|
||||
{{#async}}
|
||||
return new Callable<ResponseEntity<{{>returnTypes}}>>() {
|
||||
@Override
|
||||
public ResponseEntity<{{>returnTypes}}> call() throws Exception {
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
}
|
||||
};
|
||||
{{/async}}
|
||||
{{/isDelegate}}
|
||||
{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{/isDelegate}}
|
||||
{{/useSpringCloudClient}}
|
||||
}
|
||||
{{/operation}}{{/jdk8-no-delegate}}
|
||||
|
||||
{{/operation}}
|
||||
{{/jdk8-no-delegate}}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -0,0 +1,232 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonTokenId;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.DateTimeUtils;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction;
|
||||
import com.fasterxml.jackson.datatype.threetenbp.function.Function;
|
||||
import org.threeten.bp.DateTimeException;
|
||||
import org.threeten.bp.Instant;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.ZoneId;
|
||||
import org.threeten.bp.ZonedDateTime;
|
||||
import org.threeten.bp.format.DateTimeFormatter;
|
||||
import org.threeten.bp.temporal.Temporal;
|
||||
import org.threeten.bp.temporal.TemporalAccessor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
|
||||
* Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format.
|
||||
*
|
||||
* @author Nick Williams
|
||||
*/
|
||||
public class CustomInstantDeserializer<T extends Temporal>
|
||||
extends ThreeTenDateTimeDeserializerBase<T> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final CustomInstantDeserializer<Instant> INSTANT = new CustomInstantDeserializer<Instant>(
|
||||
Instant.class, DateTimeFormatter.ISO_INSTANT,
|
||||
new Function<TemporalAccessor, Instant>() {
|
||||
@Override
|
||||
public Instant apply(TemporalAccessor temporalAccessor) {
|
||||
return Instant.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, Instant>() {
|
||||
@Override
|
||||
public Instant apply(FromIntegerArguments a) {
|
||||
return Instant.ofEpochMilli(a.value);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, Instant>() {
|
||||
@Override
|
||||
public Instant apply(FromDecimalArguments a) {
|
||||
return Instant.ofEpochSecond(a.integer, a.fraction);
|
||||
}
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
public static final CustomInstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new CustomInstantDeserializer<OffsetDateTime>(
|
||||
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
|
||||
new Function<TemporalAccessor, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(TemporalAccessor temporalAccessor) {
|
||||
return OffsetDateTime.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(FromIntegerArguments a) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(FromDecimalArguments a) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
|
||||
}
|
||||
},
|
||||
new BiFunction<OffsetDateTime, ZoneId, OffsetDateTime>() {
|
||||
@Override
|
||||
public OffsetDateTime apply(OffsetDateTime d, ZoneId z) {
|
||||
return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime()));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
public static final CustomInstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new CustomInstantDeserializer<ZonedDateTime>(
|
||||
ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
|
||||
new Function<TemporalAccessor, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(TemporalAccessor temporalAccessor) {
|
||||
return ZonedDateTime.from(temporalAccessor);
|
||||
}
|
||||
},
|
||||
new Function<FromIntegerArguments, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(FromIntegerArguments a) {
|
||||
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
|
||||
}
|
||||
},
|
||||
new Function<FromDecimalArguments, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(FromDecimalArguments a) {
|
||||
return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
|
||||
}
|
||||
},
|
||||
new BiFunction<ZonedDateTime, ZoneId, ZonedDateTime>() {
|
||||
@Override
|
||||
public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) {
|
||||
return zonedDateTime.withZoneSameInstant(zoneId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
protected final Function<FromIntegerArguments, T> fromMilliseconds;
|
||||
|
||||
protected final Function<FromDecimalArguments, T> fromNanoseconds;
|
||||
|
||||
protected final Function<TemporalAccessor, T> parsedToValue;
|
||||
|
||||
protected final BiFunction<T, ZoneId, T> adjust;
|
||||
|
||||
protected CustomInstantDeserializer(Class<T> supportedType,
|
||||
DateTimeFormatter parser,
|
||||
Function<TemporalAccessor, T> parsedToValue,
|
||||
Function<FromIntegerArguments, T> fromMilliseconds,
|
||||
Function<FromDecimalArguments, T> fromNanoseconds,
|
||||
BiFunction<T, ZoneId, T> adjust) {
|
||||
super(supportedType, parser);
|
||||
this.parsedToValue = parsedToValue;
|
||||
this.fromMilliseconds = fromMilliseconds;
|
||||
this.fromNanoseconds = fromNanoseconds;
|
||||
this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
|
||||
@Override
|
||||
public T apply(T t, ZoneId zoneId) {
|
||||
return t;
|
||||
}
|
||||
} : adjust;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected CustomInstantDeserializer(CustomInstantDeserializer<T> base, DateTimeFormatter f) {
|
||||
super((Class<T>) base.handledType(), f);
|
||||
parsedToValue = base.parsedToValue;
|
||||
fromMilliseconds = base.fromMilliseconds;
|
||||
fromNanoseconds = base.fromNanoseconds;
|
||||
adjust = base.adjust;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
|
||||
if (dtf == _formatter) {
|
||||
return this;
|
||||
}
|
||||
return new CustomInstantDeserializer<T>(this, dtf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
|
||||
//string values have to be adjusted to the configured TZ.
|
||||
switch (parser.getCurrentTokenId()) {
|
||||
case JsonTokenId.ID_NUMBER_FLOAT: {
|
||||
BigDecimal value = parser.getDecimalValue();
|
||||
long seconds = value.longValue();
|
||||
int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds);
|
||||
return fromNanoseconds.apply(new FromDecimalArguments(
|
||||
seconds, nanoseconds, getZone(context)));
|
||||
}
|
||||
|
||||
case JsonTokenId.ID_NUMBER_INT: {
|
||||
long timestamp = parser.getLongValue();
|
||||
if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
|
||||
return this.fromNanoseconds.apply(new FromDecimalArguments(
|
||||
timestamp, 0, this.getZone(context)
|
||||
));
|
||||
}
|
||||
return this.fromMilliseconds.apply(new FromIntegerArguments(
|
||||
timestamp, this.getZone(context)
|
||||
));
|
||||
}
|
||||
|
||||
case JsonTokenId.ID_STRING: {
|
||||
String string = parser.getText().trim();
|
||||
if (string.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
if (string.endsWith("+0000")) {
|
||||
string = string.substring(0, string.length() - 5) + "Z";
|
||||
}
|
||||
T value;
|
||||
try {
|
||||
TemporalAccessor acc = _formatter.parse(string);
|
||||
value = parsedToValue.apply(acc);
|
||||
if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) {
|
||||
return adjust.apply(value, this.getZone(context));
|
||||
}
|
||||
} catch (DateTimeException e) {
|
||||
throw _peelDTE(e);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw context.mappingException("Expected type float, integer, or string.");
|
||||
}
|
||||
|
||||
private ZoneId getZone(DeserializationContext context) {
|
||||
// Instants are always in UTC, so don't waste compute cycles
|
||||
return (_valueClass == Instant.class) ? null : DateTimeUtils.timeZoneToZoneId(context.getTimeZone());
|
||||
}
|
||||
|
||||
private static class FromIntegerArguments {
|
||||
public final long value;
|
||||
public final ZoneId zoneId;
|
||||
|
||||
private FromIntegerArguments(long value, ZoneId zoneId) {
|
||||
this.value = value;
|
||||
this.zoneId = zoneId;
|
||||
}
|
||||
}
|
||||
|
||||
private static class FromDecimalArguments {
|
||||
public final long integer;
|
||||
public final int fraction;
|
||||
public final ZoneId zoneId;
|
||||
|
||||
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
|
||||
this.integer = integer;
|
||||
this.fraction = fraction;
|
||||
this.zoneId = zoneId;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.threeten.bp.Instant;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.ZonedDateTime;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ThreeTenModule.class)
|
||||
ThreeTenModule threeTenModule() {
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
return module;
|
||||
}
|
||||
}
|
@ -9,12 +9,12 @@
|
||||
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
<springfox-version>2.6.1</springfox-version>
|
||||
<springfox-version>2.7.0</springfox-version>
|
||||
</properties>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.7.RELEASE</version>
|
||||
<version>1.5.4.RELEASE</version>
|
||||
</parent>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
@ -71,17 +71,21 @@
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>2.6.4</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/threetenbp}}
|
||||
{{#useBeanValidation}}
|
||||
<!-- Bean Validation API support -->
|
||||
<dependency>
|
||||
|
@ -0,0 +1,23 @@
|
||||
package {{configPackage}};
|
||||
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.threeten.bp.Instant;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.ZonedDateTime;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ThreeTenModule.class)
|
||||
ThreeTenModule threeTenModule() {
|
||||
ThreeTenModule module = new ThreeTenModule();
|
||||
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
|
||||
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
|
||||
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
|
||||
return module;
|
||||
}
|
||||
}
|
@ -14,7 +14,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.7.RELEASE</version>
|
||||
<version>1.5.4.RELEASE</version>
|
||||
</parent>
|
||||
<build>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
@ -25,7 +25,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-parent</artifactId>
|
||||
<version>Camden.SR1</version>
|
||||
<version>Dalston.SR1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@ -66,17 +66,21 @@
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>2.6.4</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/threetenbp}}
|
||||
{{#useBeanValidation}}
|
||||
<!-- Bean Validation API support -->
|
||||
<dependency>
|
||||
|
@ -93,13 +93,18 @@
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${springfox-version}</version>
|
||||
</dependency>
|
||||
|
||||
{{#withXml}}
|
||||
|
||||
<!-- XML processing: Jackson -->
|
||||
@ -111,24 +116,29 @@
|
||||
|
||||
{{/withXml}}
|
||||
{{#java8}}
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson-version}</version>
|
||||
</dependency>
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>2.9.4</version>
|
||||
<groupId>com.github.joschi.jackson</groupId>
|
||||
<artifactId>jackson-datatype-threetenbp</artifactId>
|
||||
<version>${jackson-threetenbp-version}</version>
|
||||
</dependency>
|
||||
{{/java8}}
|
||||
{{/threetenbp}}
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
@ -159,8 +169,9 @@
|
||||
<slf4j-version>1.7.21</slf4j-version>
|
||||
<junit-version>4.12</junit-version>
|
||||
<servlet-api-version>2.5</servlet-api-version>
|
||||
<springfox-version>2.4.0</springfox-version>
|
||||
<springfox-version>2.7.0</springfox-version>
|
||||
<jackson-version>2.8.9</jackson-version>
|
||||
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
|
||||
<spring-version>4.3.9.RELEASE</spring-version>
|
||||
</properties>
|
||||
</project>
|
||||
|
@ -2,6 +2,9 @@ package {{configPackage}};
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
{{#threetenbp}}
|
||||
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
|
||||
{{/threetenbp}}
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
@ -13,6 +16,11 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
{{#threetenbp}}
|
||||
import org.threeten.bp.Instant;
|
||||
import org.threeten.bp.OffsetDateTime;
|
||||
import org.threeten.bp.ZonedDateTime;
|
||||
{{/threetenbp}}
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
import java.util.List;
|
||||
|
@ -36,10 +36,14 @@ public class SwaggerDocumentationConfig {
|
||||
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
|
||||
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
|
||||
{{/java8}}
|
||||
{{^java8}}
|
||||
{{#joda}}
|
||||
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
|
||||
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
|
||||
{{/java8}}
|
||||
{{/joda}}
|
||||
{{#threetenbp}}
|
||||
.directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class)
|
||||
.directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class)
|
||||
{{/threetenbp}}
|
||||
.apiInfo(apiInfo());
|
||||
}
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user