diff --git a/bin/configs/scala-legacy.yaml b/bin/configs/scala-legacy.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c9c1865bc03de45c5e4246a75f613d0fa12b0c9 --- /dev/null +++ b/bin/configs/scala-legacy.yaml @@ -0,0 +1,9 @@ +# This is for generating scala legacy client +generatorName: scala-httpclient-deprecated +outputDir: samples/client/petstore/scala-httpclient-deprecated +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/scala-httpclient +additionalProperties: + apiPackage: org.openapitools.example.api + invokerPackage: org.openapitools.example.invoker + artifactId: scala-legacy-petstore \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java index 7ceb98d917e13e0e6560f048e7a7459b6d2a9fd6..d210d0b9871ce211e52224f27844a6b576c00486 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java @@ -164,6 +164,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); } + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java index 517d0e8c58a6c300d06bb1b51ef6758c7a4bf3df..de88700730824f5df75b766d9565c09c839a7ffa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java @@ -105,27 +105,6 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code 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 - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); - // gradleWrapper files - supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); - supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); - supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); - supportingFiles.add(new SupportingFile("gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); - - supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - importMapping.remove("List"); importMapping.remove("Set"); importMapping.remove("Map"); @@ -163,6 +142,27 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code LOGGER.warn("IMPORTANT: This generator (scala-http-client-deprecated) is no longer actively maintained and will be deprecated. " + "PLease use 'scala-akka' generator instead."); super.processOpts(); + + 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 + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); + // gradleWrapper files + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); + + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } @Override diff --git a/samples/client/petstore/scala-httpclient-deprecated/.gitignore b/samples/client/petstore/scala-httpclient-deprecated/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ad2b0d3ecd853547cb7e873920a2cecd53d658fc --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.gitignore @@ -0,0 +1,22 @@ +# scala specific +*.class +*.log + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet + +# IntelliJ specific +.idea +*.iml diff --git a/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator-ignore b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator-ignore new file mode 100644 index 0000000000000000000000000000000000000000..7484ee590a3894506cf063799b885428f95a71be --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/FILES b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/FILES new file mode 100644 index 0000000000000000000000000000000000000000..77e4ca71c11401846ba5a9d0a79a3dbe6d3cf2b9 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +build.gradle +build.sbt +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/scala/org/openapitools/client/model/ApiResponse.scala +src/main/scala/org/openapitools/client/model/Category.scala +src/main/scala/org/openapitools/client/model/Order.scala +src/main/scala/org/openapitools/client/model/Pet.scala +src/main/scala/org/openapitools/client/model/Tag.scala +src/main/scala/org/openapitools/client/model/User.scala +src/main/scala/org/openapitools/example/api/PetApi.scala +src/main/scala/org/openapitools/example/api/StoreApi.scala +src/main/scala/org/openapitools/example/api/UserApi.scala +src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala +src/main/scala/org/openapitools/example/invoker/AsyncClient.scala diff --git a/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..6555596f931149bc73ff7b8c2d0ab3985c120e26 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/build.gradle b/samples/client/petstore/scala-httpclient-deprecated/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..d05105184ff6794fa8155c390444433f081cbbad --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/build.gradle @@ -0,0 +1,127 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'scala-legacy-petstore' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" + swagger_async_httpclient_version = "0.3.5" +} + +repositories { + mavenLocal() + maven { url "https://repo1.maven.org/maven2" } +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" + compile "com.wordnik.swagger:swagger-async-httpclient_2.10:$swagger_async_httpclient_version" +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/build.sbt b/samples/client/petstore/scala-httpclient-deprecated/build.sbt new file mode 100644 index 0000000000000000000000000000000000000000..0565bb12ae1976cd3ae7e59855412d784795165a --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/build.sbt @@ -0,0 +1,32 @@ +version := "1.0.0" +name := "scala-legacy-petstore" +organization := "org.openapitools" +scalaVersion := "2.11.12" + +libraryDependencies ++= Seq( + "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9", + "com.sun.jersey" % "jersey-core" % "1.19.4", + "com.sun.jersey" % "jersey-client" % "1.19.4", + "com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4", + "org.jfarcand" % "jersey-ahc-client" % "1.0.5", + "io.swagger" % "swagger-core" % "1.5.8", + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "org.scalatest" %% "scalatest" % "3.0.4" % "test", + "junit" % "junit" % "4.13" % "test", + "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" +) + +resolvers ++= Seq( + Resolver.mavenLocal +) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false + diff --git a/samples/client/petstore/scala-httpclient-deprecated/git_push.sh b/samples/client/petstore/scala-httpclient-deprecated/git_push.sh new file mode 100644 index 0000000000000000000000000000000000000000..ced3be2b0c7b2349ff06d18da19d4b31435c9fa6 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradle.properties b/samples/client/petstore/scala-httpclient-deprecated/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..05644f0754af4d99d53558a2a52cc3233f7ed9d6 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..87b738cbd051603d91cc39de6cb000dd98fe6b02 Binary files /dev/null and b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e496c054f693cca670789c1926101f53152dd1a3 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradlew b/samples/client/petstore/scala-httpclient-deprecated/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..af6708ff229fda75da4f7cc4da4747217bac4d53 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat b/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..f9553162f122c71b34635112e717c3e733b5b212 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/scala-httpclient-deprecated/pom.xml b/samples/client/petstore/scala-httpclient-deprecated/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..26ed58c1b596406d2b12f99e4654b24d7681d22c --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/pom.xml @@ -0,0 +1,255 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.openapitools</groupId> + <artifactId>scala-legacy-petstore</artifactId> + <packaging>jar</packaging> + <name>scala-legacy-petstore</name> + <version>1.0.0</version> + + <pluginRepositories> + <pluginRepository> + <id>maven-mongodb-plugin-repo</id> + <name>maven mongodb plugin repository</name> + <!-- TODO: this URL does not exist. --> + <url>https://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url> + <layout>default</layout> + </pluginRepository> + </pluginRepositories> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-enforcer-plugin</artifactId> + <version>3.0.0-M1</version> + <executions> + <execution> + <id>enforce-maven</id> + <goals> + <goal>enforce</goal> + </goals> + <configuration> + <rules> + <requireMavenVersion> + <version>2.2.0</version> + </requireMavenVersion> + </rules> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.12</version> + <configuration> + <systemProperties> + <property> + <name>loggerPath</name> + <value>conf/log4j.properties</value> + </property> + </systemProperties> + <argLine>-Xms512m -Xmx1500m</argLine> + <parallel>methods</parallel> + <forkMode>pertest</forkMode> + </configuration> + </plugin> + <plugin> + <artifactId>maven-dependency-plugin</artifactId> + <executions> + <execution> + <phase>package</phase> + <goals> + <goal>copy-dependencies</goal> + </goals> + <configuration> + <outputDirectory>${project.build.directory}/lib</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> + + <!-- attach test jar --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <version>2.2</version> + <executions> + <execution> + <goals> + <goal>jar</goal> + <goal>test-jar</goal> + </goals> + </execution> + </executions> + <configuration> + </configuration> + </plugin> + + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <version>1.9.1</version> + <executions> + <execution> + <id>add_sources</id> + <phase>generate-sources</phase> + <goals> + <goal>add-source</goal> + </goals> + <configuration> + <sources> + <source> + src/main/java</source> + </sources> + </configuration> + </execution> + <execution> + <id>add_test_sources</id> + <phase>generate-test-sources</phase> + <goals> + <goal>add-test-source</goal> + </goals> + <configuration> + <sources> + <source> + src/test/java</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.6.1</version> + <configuration> + <source>1.7</source> + <target>1.7</target> + </configuration> + </plugin> + <plugin> + <groupId>net.alchim31.maven</groupId> + <artifactId>scala-maven-plugin</artifactId> + <version>${scala-maven-plugin-version}</version> + <executions> + <execution> + <id>scala-compile-first</id> + <phase>process-resources</phase> + <goals> + <goal>add-source</goal> + <goal>compile</goal> + </goals> + </execution> + <execution> + <id>scala-test-compile</id> + <phase>process-test-resources</phase> + <goals> + <goal>testCompile</goal> + </goals> + </execution> + </executions> + <configuration> + <jvmArgs> + <jvmArg>-Xms128m</jvmArg> + <jvmArg>-Xmx1500m</jvmArg> + </jvmArgs> + </configuration> + </plugin> + </plugins> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.scala-tools</groupId> + <artifactId>maven-scala-plugin</artifactId> + <configuration> + <scalaVersion>${scala-version}</scalaVersion> + </configuration> + </plugin> + </plugins> + </reporting> + <dependencies> + <dependency> + <groupId>com.fasterxml.jackson.module</groupId> + <artifactId>jackson-module-scala_2.11</artifactId> + <version>${jackson-version}</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.datatype</groupId> + <artifactId>jackson-datatype-joda</artifactId> + <version>${jackson-version}</version> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + <version>${jersey-version}</version> + </dependency> + <dependency> + <groupId>com.sun.jersey.contribs</groupId> + <artifactId>jersey-multipart</artifactId> + <version>${jersey-version}</version> + </dependency> + <dependency> + <groupId>org.jfarcand</groupId> + <artifactId>jersey-ahc-client</artifactId> + <version>${jersey-async-version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.scala-lang</groupId> + <artifactId>scala-library</artifactId> + <version>${scala-version}</version> + </dependency> + <dependency> + <groupId>io.swagger</groupId> + <artifactId>swagger-core</artifactId> + <version>${swagger-core-version}</version> + </dependency> + <dependency> + <groupId>org.scalatest</groupId> + <artifactId>scalatest_2.11</artifactId> + <version>${scala-test-version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>${junit-version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>joda-time</groupId> + <artifactId>joda-time</artifactId> + <version>${joda-time-version}</version> + </dependency> + <dependency> + <groupId>org.joda</groupId> + <artifactId>joda-convert</artifactId> + <version>${joda-version}</version> + </dependency> + <dependency> + <groupId>com.wordnik.swagger</groupId> + <artifactId>swagger-async-httpclient_2.11</artifactId> + <version>${async-httpclient-version}</version> + </dependency> + </dependencies> + <properties> + <scala-version>2.11.12</scala-version> + <joda-version>1.9.2</joda-version> + <joda-time-version>2.9.9</joda-time-version> + <jersey-version>1.19.4</jersey-version> + <swagger-core-version>1.5.18</swagger-core-version> + <jersey-async-version>1.0.5</jersey-async-version> + <maven-plugin.version>1.0.0</maven-plugin.version> + <jackson-version>2.9.9</jackson-version> + + <junit-version>4.13</junit-version> + <scala-maven-plugin-version>3.1.5</scala-maven-plugin-version> + <scala-test-version>3.0.4</scala-test-version> + <async-httpclient-version>0.3.5</async-httpclient-version> + + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + </properties> +</project> diff --git a/samples/client/petstore/scala-httpclient-deprecated/project/build.properties b/samples/client/petstore/scala-httpclient-deprecated/project/build.properties new file mode 100644 index 0000000000000000000000000000000000000000..c0bab04941d74f9690e3610772090bfa4af33c37 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.2.8 diff --git a/samples/client/petstore/scala-httpclient-deprecated/settings.gradle b/samples/client/petstore/scala-httpclient-deprecated/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..526dd2d0ab46e69ab646a4b0c25561fdfd4ac182 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "scala-legacy-petstore" \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/ApiResponse.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/ApiResponse.scala new file mode 100644 index 0000000000000000000000000000000000000000..be74123132941deea8bf94b74e2f4fe035754b49 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/ApiResponse.scala @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + + +case class ApiResponse ( + code: Option[Integer] = None, + `type`: Option[String] = None, + message: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Category.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Category.scala new file mode 100644 index 0000000000000000000000000000000000000000..be3307b8f8ee980157d9230c5aeb017b2e0dc181 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Category.scala @@ -0,0 +1,20 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + + +case class Category ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala new file mode 100644 index 0000000000000000000000000000000000000000..d0ca63b5091fe88c409b3306092ea36854b44423 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala @@ -0,0 +1,26 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + +import java.util.Date + +case class Order ( + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Integer] = None, + shipDate: Option[Date] = None, + // Order Status + status: Option[String] = None, + complete: Option[Boolean] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala new file mode 100644 index 0000000000000000000000000000000000000000..2de76ae35888eec8c6b7046851ac3818a9264c94 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala @@ -0,0 +1,25 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + + +case class Pet ( + id: Option[Long] = None, + category: Option[Category] = None, + name: String, + photoUrls: List[String], + tags: Option[List[Tag]] = None, + // pet status in the store + status: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Tag.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Tag.scala new file mode 100644 index 0000000000000000000000000000000000000000..6fbabf7ed63061564fce80da0d051064aae0ab9c --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Tag.scala @@ -0,0 +1,20 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + + +case class Tag ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/User.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/User.scala new file mode 100644 index 0000000000000000000000000000000000000000..fc24b101e8bad412eb30fe5dab5e61457b99253c --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/User.scala @@ -0,0 +1,27 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model + + +case class User ( + id: Option[Long] = None, + username: Option[String] = None, + firstName: Option[String] = None, + lastName: Option[String] = None, + email: Option[String] = None, + password: Option[String] = None, + phone: Option[String] = None, + // User Status + userStatus: Option[Integer] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala new file mode 100644 index 0000000000000000000000000000000000000000..bb58587307eeb1556825e390568c2914d3b6867c --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala @@ -0,0 +1,476 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.ApiResponse +import java.io.File +import org.openapitools.client.model.Pet +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class PetApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new PetApiAsyncHelper(client, config) + + /** + * Add a new pet to the store + * + * + * @param pet Pet object that needs to be added to the store + * @return Pet + */ + def addPet(pet: Pet): Option[Pet] = { + val await = Try(Await.result(addPetAsync(pet), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Add a new pet to the store asynchronously + * + * + * @param pet Pet object that needs to be added to the store + * @return Future(Pet) + */ + def addPetAsync(pet: Pet): Future[Pet] = { + helper.addPet(pet) + } + + /** + * Deletes a pet + * + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + */ + def deletePet(petId: Long, apiKey: Option[String] = None) = { + val await = Try(Await.result(deletePetAsync(petId, apiKey), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Deletes a pet asynchronously + * + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return Future(void) + */ + def deletePetAsync(petId: Long, apiKey: Option[String] = None) = { + helper.deletePet(petId, apiKey) + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * + * @param status Status values that need to be considered for filter + * @return List[Pet] + */ + def findPetsByStatus(status: List[String]): Option[List[Pet]] = { + val await = Try(Await.result(findPetsByStatusAsync(status), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Finds Pets by status asynchronously + * Multiple status values can be provided with comma separated strings + * + * @param status Status values that need to be considered for filter + * @return Future(List[Pet]) + */ + def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = { + helper.findPetsByStatus(status) + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @param tags Tags to filter by + * @return List[Pet] + */ + def findPetsByTags(tags: List[String]): Option[List[Pet]] = { + val await = Try(Await.result(findPetsByTagsAsync(tags), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Finds Pets by tags asynchronously + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @param tags Tags to filter by + * @return Future(List[Pet]) + */ + def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = { + helper.findPetsByTags(tags) + } + + /** + * Find pet by ID + * Returns a single pet + * + * @param petId ID of pet to return + * @return Pet + */ + def getPetById(petId: Long): Option[Pet] = { + val await = Try(Await.result(getPetByIdAsync(petId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Find pet by ID asynchronously + * Returns a single pet + * + * @param petId ID of pet to return + * @return Future(Pet) + */ + def getPetByIdAsync(petId: Long): Future[Pet] = { + helper.getPetById(petId) + } + + /** + * Update an existing pet + * + * + * @param pet Pet object that needs to be added to the store + * @return Pet + */ + def updatePet(pet: Pet): Option[Pet] = { + val await = Try(Await.result(updatePetAsync(pet), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Update an existing pet asynchronously + * + * + * @param pet Pet object that needs to be added to the store + * @return Future(Pet) + */ + def updatePetAsync(pet: Pet): Future[Pet] = { + helper.updatePet(pet) + } + + /** + * Updates a pet in the store with form data + * + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return void + */ + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = { + val await = Try(Await.result(updatePetWithFormAsync(petId, name, status), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Updates a pet in the store with form data asynchronously + * + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return Future(void) + */ + def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = { + helper.updatePetWithForm(petId, name, status) + } + + /** + * uploads an image + * + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse + */ + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = { + val await = Try(Await.result(uploadFileAsync(petId, additionalMetadata, file), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * uploads an image asynchronously + * + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return Future(ApiResponse) + */ + def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = { + helper.uploadFile(petId, additionalMetadata, file) + } + +} + +class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def addPet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->addPet") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(pet)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def deletePet(petId: Long, + apiKey: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + apiKey match { + case Some(param) => headerParams += "api_key" -> param.toString + case _ => headerParams + } + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByStatus")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus") + queryParams += "status" -> status.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByTags")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags") + queryParams += "tags" -> tags.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updatePet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->updatePet") + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(pet)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updatePetWithForm(petId: Long, + name: Option[String] = None, + status: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def uploadFile(petId: Long, + additionalMetadata: Option[String] = None, + file: Option[File] = None + )(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = { + // create path and map variables + val path = (addFmt("/pet/{petId}/uploadImage") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala new file mode 100644 index 0000000000000000000000000000000000000000..949585575e9e7ca6789c83b3e3627ed5b7de345a --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala @@ -0,0 +1,265 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.Order +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class StoreApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new StoreApiAsyncHelper(client, config) + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @param orderId ID of the order that needs to be deleted + * @return void + */ + def deleteOrder(orderId: String) = { + val await = Try(Await.result(deleteOrderAsync(orderId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Delete purchase order by ID asynchronously + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @param orderId ID of the order that needs to be deleted + * @return Future(void) + */ + def deleteOrderAsync(orderId: String) = { + helper.deleteOrder(orderId) + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * + * @return Map[String, Integer] + */ + def getInventory(): Option[Map[String, Integer]] = { + val await = Try(Await.result(getInventoryAsync(), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Returns pet inventories by status asynchronously + * Returns a map of status codes to quantities + * + * @return Future(Map[String, Integer]) + */ + def getInventoryAsync(): Future[Map[String, Integer]] = { + helper.getInventory() + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + def getOrderById(orderId: Long): Option[Order] = { + val await = Try(Await.result(getOrderByIdAsync(orderId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Find purchase order by ID asynchronously + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched + * @return Future(Order) + */ + def getOrderByIdAsync(orderId: Long): Future[Order] = { + helper.getOrderById(orderId) + } + + /** + * Place an order for a pet + * + * + * @param order order placed for purchasing the pet + * @return Order + */ + def placeOrder(order: Order): Option[Order] = { + val await = Try(Await.result(placeOrderAsync(order), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Place an order for a pet asynchronously + * + * + * @param order order placed for purchasing the pet + * @return Future(Order) + */ + def placeOrderAsync(order: Order): Future[Order] = { + helper.placeOrder(order) + } + +} + +class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder") + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { + // create path and map variables + val path = (addFmt("/store/inventory")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def placeOrder(order: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (order == null) throw new Exception("Missing required parameter 'order' when calling StoreApi->placeOrder") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(order)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala new file mode 100644 index 0000000000000000000000000000000000000000..d39a90e574158d9ae5aa1eea7e2d6aafc1588045 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala @@ -0,0 +1,465 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.User +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class UserApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new UserApiAsyncHelper(client, config) + + /** + * Create user + * This can only be done by the logged in user. + * + * @param user Created user object + * @return void + */ + def createUser(user: User) = { + val await = Try(Await.result(createUserAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Create user asynchronously + * This can only be done by the logged in user. + * + * @param user Created user object + * @return Future(void) + */ + def createUserAsync(user: User) = { + helper.createUser(user) + } + + /** + * Creates list of users with given input array + * + * + * @param user List of user object + * @return void + */ + def createUsersWithArrayInput(user: List[User]) = { + val await = Try(Await.result(createUsersWithArrayInputAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Creates list of users with given input array asynchronously + * + * + * @param user List of user object + * @return Future(void) + */ + def createUsersWithArrayInputAsync(user: List[User]) = { + helper.createUsersWithArrayInput(user) + } + + /** + * Creates list of users with given input array + * + * + * @param user List of user object + * @return void + */ + def createUsersWithListInput(user: List[User]) = { + val await = Try(Await.result(createUsersWithListInputAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Creates list of users with given input array asynchronously + * + * + * @param user List of user object + * @return Future(void) + */ + def createUsersWithListInputAsync(user: List[User]) = { + helper.createUsersWithListInput(user) + } + + /** + * Delete user + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted + * @return void + */ + def deleteUser(username: String) = { + val await = Try(Await.result(deleteUserAsync(username), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Delete user asynchronously + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted + * @return Future(void) + */ + def deleteUserAsync(username: String) = { + helper.deleteUser(username) + } + + /** + * Get user by user name + * + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + def getUserByName(username: String): Option[User] = { + val await = Try(Await.result(getUserByNameAsync(username), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Get user by user name asynchronously + * + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Future(User) + */ + def getUserByNameAsync(username: String): Future[User] = { + helper.getUserByName(username) + } + + /** + * Logs user into the system + * + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + def loginUser(username: String, password: String): Option[String] = { + val await = Try(Await.result(loginUserAsync(username, password), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Logs user into the system asynchronously + * + * + * @param username The user name for login + * @param password The password for login in clear text + * @return Future(String) + */ + def loginUserAsync(username: String, password: String): Future[String] = { + helper.loginUser(username, password) + } + + /** + * Logs out current logged in user session + * + * + * @return void + */ + def logoutUser() = { + val await = Try(Await.result(logoutUserAsync(), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Logs out current logged in user session asynchronously + * + * + * @return Future(void) + */ + def logoutUserAsync() = { + helper.logoutUser() + } + + /** + * Updated user + * This can only be done by the logged in user. + * + * @param username name that need to be deleted + * @param user Updated user object + * @return void + */ + def updateUser(username: String, user: User) = { + val await = Try(Await.result(updateUserAsync(username, user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Updated user asynchronously + * This can only be done by the logged in user. + * + * @param username name that need to be deleted + * @param user Updated user object + * @return Future(void) + */ + def updateUserAsync(username: String, user: User) = { + helper.updateUser(username, user) + } + +} + +class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def createUser(user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUser") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def createUsersWithArrayInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithArray")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithArrayInput") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def createUsersWithListInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithList")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithListInput") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser") + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName") + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def loginUser(username: String, + password: String)(implicit reader: ClientResponseReader[String]): Future[String] = { + // create path and map variables + val path = (addFmt("/user/login")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser") + + if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser") + + queryParams += "username" -> username.toString + queryParams += "password" -> password.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/logout")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updateUser(username: String, + user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser") + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->updateUser") + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala new file mode 100644 index 0000000000000000000000000000000000000000..f04c9fa6a1e6b36980afce68d185a2775ca30e2f --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala @@ -0,0 +1,237 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.example.invoker + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.core.util.MultivaluedMapImpl +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import java.util.UUID +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper: ObjectMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()) + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(), + hostMap: mutable.HashMap[String, Client] = mutable.HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false +) { + + var defaultHeaders: mutable.HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + def escape(values: List[String]): String = { + values.map(escape).mkString(",") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + def escape(value: UUID): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) { + s.substring(1, s.length - 1) + } else { + s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => + val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + case "list" => + val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + case _ => + json match { + case e: String if "\"\"" == e => null + case _ => mapper.readValue(json, cls) + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else { + null + } + } + + def invokeApi( + host: String, + path: String, + method: String, + queryParams: Map[String, String], + formParams: Map[String, String], + body: AnyRef, + headerParams: Map[String, String], + contentType: String +): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.foreach(p => { + if (!headerParams.contains(p._1) && p._2 != null) { + builder.header(p._1, p._2) + } + }) + var formData: MultivaluedMapImpl = null + if (contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.foreach(p => formData.add(p._1, p._2)) + } + + val response: ClientResponse = method match { + case "GET" => builder.get(classOf[ClientResponse]) + case "POST" => + if (formData != null && formData.size() > 0) { + builder.post(classOf[ClientResponse], formData) + } else if (body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } else { + if (body == null) { + builder.post(classOf[ClientResponse], serialize(body)) + } else { + builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => + if (formData != null) { + builder.post(classOf[ClientResponse], formData) + } else if (body == null) { + builder.put(classOf[ClientResponse], null) + } else { + builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => builder.delete(classOf[ClientResponse]) + case "PATCH" => + if(formData != null) { + builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData) + } else if(body == null) { + builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null) + } else { + builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + case _ => null + } + response.getStatusInfo.getStatusCode match { + case 204 => "" + case code: Int if Range(200, 299).contains(code) => + if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "" + } + case _ => + val entity = if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "no data" + } + throw new ApiException(response.getStatusInfo.getStatusCode, entity) + } + } + + def getClient(host: String): Client = { + if (hostMap.contains(host)) { + hostMap(host) + } else { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + + def newClient(host: String): Client = if (asyncHttpClient) { + import com.ning.http.client.Realm + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config + .getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } else { + Client.create() + } +} + +object ApiInvoker extends ApiInvoker( + mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = mutable.HashMap(), + hostMap = mutable.HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false +) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala new file mode 100644 index 0000000000000000000000000000000000000000..60e423b51cbb665291c80da92da00c2039b5d88e --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala @@ -0,0 +1,20 @@ +package org.openapitools.example.invoker + +import org.openapitools.example.api._ + +import com.wordnik.swagger.client._ + +import java.io.Closeable + +class AsyncClient(config: SwaggerConfig) extends Closeable { + lazy val locator: ServiceLocator = config.locator + lazy val name: String = config.name + + private[this] val client = transportClient + + protected def transportClient: TransportClient = new RestClient(config) + + def close() { + client.close() + } +}