diff --git a/.gitignore b/.gitignore
index 940794e60f..565e7ae9fb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -286,3 +286,7 @@ __pycache__/
*.btm.cs
*.odx.cs
*.xsd.cs
+
+package-lock.json
+*.class
+test/*/target/
\ No newline at end of file
diff --git a/.gulp/common.iced b/.gulp/common.iced
new file mode 100644
index 0000000000..a5265ce837
--- /dev/null
+++ b/.gulp/common.iced
@@ -0,0 +1,489 @@
+through = require 'through2'
+util = require 'util'
+
+
+# place an object into global namespace
+global['Import'] = (object) ->
+ for key, value of object
+ global[key] = value
+
+Import
+ # require into the global namespace (modulename = module)
+ Install: (modulename, module) ->
+ global[modulename] = require module or modulename
+
+ # require a gulp-Plugin into the global namespace
+ Plugin: () ->
+ Install module,"gulp-#{module}" for module in arguments
+
+ # require a module, placing exports into global namespace
+ Include: () ->
+ Import require module for module in arguments
+
+ Tasks: () ->
+ require "#{__dirname}/#{module}" for module in arguments
+
+###############################################
+# force-global a bunch of stuff.
+require 'shelljs/global'
+Install 'marked'
+Install 'vinyl'
+Install 'os'
+Install 'path'
+Install 'fs'
+Install 'gulp'
+Install 'util'
+Install 'moment'
+Install 'chalk'
+Install 'yargs'
+Install 'semver'
+
+Install 'eol', 'gulp-line-ending-corrector'
+Install 'through', 'through2-parallel'
+Install 'run', 'run-sequence'
+
+# do a bit of monkeypatching
+_gulpStart = gulp.Gulp::start
+_runTask = gulp.Gulp::_runTask
+
+gulp.Gulp::start = (taskName) ->
+ @currentStartTaskName = taskName
+ _gulpStart.apply this, arguments
+ return
+
+gulp.Gulp::_runTask = (task) ->
+ @currentRunTaskName = task.name
+ _runTask.apply this, arguments
+ return
+
+# echo 'this.currentStartTaskName: ' + this.currentStartTaskName
+# echo 'this.currentRunTaskName: ' + this.currentRunTaskName
+
+# bring some gulp-Plugins along
+# Plugin 'filter',
+# 'zip'
+ #'unzip'
+ #'rename'
+
+# force this into global namespace
+global['argv'] = yargs.argv
+
+fs = require('fs')
+path = require('path')
+
+concurrency = 0
+queue = []
+global.completed = []
+vfs = require('vinyl-fs');
+
+module.exports =
+ # lets us just handle each item in a stream easily.
+ foreach: (delegate) ->
+ through.obj { concurrency: threshold }, ( each, enc, done ) ->
+ delegate each, done, this
+
+ count: (result,passthru) =>
+ foreach (each,done) =>
+ result++
+ done null
+
+ hashCode: (s) ->
+ (s.split('').reduce ((a, b) ->
+ a = (a << 5) - a + b.charCodeAt(0)
+ a & a
+ ), 0 ) .toString(16)
+
+ toArray: (result,passthru) =>
+ foreach (each,done) =>
+ result.push(each)
+ if passthru
+ done null, each
+ else
+ done null
+
+ showFiles: () ->
+ foreach (each,done) ->
+ echo info each.path
+ done null, each
+
+ onlyFiles: () ->
+ foreach (each,done) ->
+ return done null, each if fs.statSync(each.path).isFile()
+ done null
+
+ source: (globs, options ) ->
+ options = options or { }
+ options.follow = true
+ vfs.src( globs, options)
+
+ watchFiles: (src,tasks) ->
+ return gulp.watch( src,tasks)
+
+ destination: (globs, options ) ->
+ gulp.dest( globs, options)
+
+ later: (fn) ->
+ setTimeout fn, 10
+
+ mklink: (link,target) ->
+ # unlink link
+ if ! test "-d", link
+ fs.symlinkSync target, link, "junction"
+
+ unlink: (link) ->
+ if test "-d", link
+ fs.unlinkSync link
+
+ erase: (file) ->
+ if test "-f", file
+ fs.unlinkSync file
+
+ task: (name, description, deps, fn) ->
+ throw "Invalid task name " if typeof name isnt 'string'
+ throw "Invalid task description #{name} " if typeof description isnt 'string'
+
+ if typeof deps == 'function'
+ fn = deps
+ deps = []
+
+ # chain the task if it's a repeat
+ if name of gulp.tasks
+ prev = gulp.tasks[name]
+
+ # reset the name of this task to be a 'child'' task
+ name = "#{name}/#{description}"
+ description = ''
+
+ # add this task as a dependency of the original task.
+ prev.dep.unshift name
+
+ # add the new task.
+ # gulp.task name, deps, fn
+ skip = (name.startsWith "init") or (name.startsWith "npm-install") or (name.startsWith "clean") or (name is "copy-dts-files") or (name.startsWith "nuke") or (name.startsWith "reset") or (name.startsWith "autorest") or description.endsWith("!")
+
+ description = '' if description = '!'
+
+ if !skip
+ deps.unshift "init"
+
+ if fn.length # see if the task function has arguments (betcha never saw that before!)
+ gulp.task name, deps, (done)->
+ if not global.completed[name]
+ #echo warning "Running task #{name} #{typeof done}"
+ global.completed[name] = true
+ return fn(done)
+ #echo warning "Skipping completed task #{name}"
+ return done()
+ else
+ gulp.task name, deps, ()->
+ if not global.completed[name]
+ #echo warning "Running task #{name}"
+ global.completed[name] = true
+ return fn()
+ #echo warning "Skipping completed task #{name}"
+ return null
+
+
+ # set the description
+ gulp.tasks[name].description = description
+
+ return
+
+ where: (predicate) ->
+ foreach (each,done) ->
+ #return done null if each?
+ return done null, each if predicate each
+ done null
+
+ splitPath: (path) ->
+ s = path.match /^(.+)[\\\/]([^\/]+)$/ or [path, '',path]
+ f = s[2].match(/^(.*)([\\.].*)$/ ) or [s[2],s[2],'']
+ d = (path.match /^(.:)[\\\/]?(.*)$/ ) or ['','',path]
+ return {
+ fullname : path
+ folder : s[1]
+ filename : s[2]
+ basename : f[1]
+ extension : f[2]
+ drive: d[1] or ''
+ folders: (d[2].split /[\\\/]/ )or path
+ }
+
+ folder: (path) ->
+ return '' if not path
+ return (splitPath path).folder
+
+ split: (path) ->
+ return '' if not path
+ return (splitPath path).folders
+
+ filename: (path) ->
+ return '' if not path
+ p = splitPath path
+ return p.filename
+
+ extension: (path) ->
+ return '' if not path
+ p = splitPath path
+ return p.extension
+
+ basename: (path) ->
+ return '' if not path
+ p = splitPath path
+ return p.basename
+
+ exists: (path) ->
+ return test '-f', path
+
+ fileExists: (path) ->
+ return test '-f', path
+
+ dirExists: (path) ->
+ return test '-d', path
+
+ newer: (first,second) ->
+ return true if (!test "-d", second) and (!test "-f", second)
+ return false if (!test "-d",first) and (!test "-f", first)
+ f = fs.statSync(first).mtime
+ s = fs.statSync(second).mtime
+ return f > s
+
+ flattenEncode: (path) ->
+ path.basename = "#{ path.dirname.replace(/[\/\\]/g, '_') }_#{path.basename}"
+ path.dirname = ""
+
+ flattenDecode: (path) ->
+ f = path.basename.match(/^(.*)_(.*)$/ )
+ path.basename = "#{f[1].replace(/[_]/g, '/') }/#{f[2]}"
+ path.dirname = ""
+
+ except: (match) ->
+ # await through.obj defer file, enc, callback
+ through.obj (file, enc, callback) ->
+
+ # check if the file is an actual file.
+ # if it's not, just skip this tool.
+ if !file or !file.path
+ return callback null, file
+
+ # do something with the file
+ if file.path.match( match )
+ return callback null
+
+ return callback null, file
+
+
+ rmfile: (dir, file, callback) ->
+ p = path.join(dir, file)
+ fs.lstat p, (err, stat) ->
+ if err
+ callback.call null, err
+ else if stat.isDirectory()
+ rmdir p, callback
+ else
+ fs.unlink p, callback
+ return
+ return
+
+ rmdir: (dir, callback) ->
+ #echo "RMDIR #{dir}"
+ fs.readdir dir, (err, files) ->
+ if err
+ callback.call null, err
+ else if files.length
+ i = undefined
+ j = undefined
+ i = j = files.length
+ while i--
+ rmfile dir, files[i], (err) ->
+ if err
+ callback.call null, err
+ else if --j == 0
+ fs.rmdir dir, callback
+ return
+ else
+ fs.rmdir dir, callback
+ return
+ return
+
+ guid: ->
+ x = -> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring 1
+ "#{x()}#{x()}-#{x()}-#{x()}-#{x()}-#{x()}#{x()}#{x()}"
+
+ Fail: (text) ->
+ echo ""
+ echo "#{ error 'Task Failed:' } #{error_message text}"
+ echo ""
+ rm '-rf', workdir
+ process.exit(1)
+
+ execute: (cmdline,options,callback, ondata)->
+ if typeof options == 'function'
+ ondata = callback
+ callback = options
+ options = { }
+
+ # if we're busy, schedule again...
+ if concurrency >= threshold
+ queue.push(->
+ execute cmdline, options, callback, ondata
+ )
+ return
+
+ concurrency++
+
+ options.cwd = options.cwd or basefolder
+ echo " #{quiet_info options.cwd} :: #{info cmdline}" if !options.silent
+
+ options.silent = !verbose
+
+ proc = exec cmdline, options, (code,stdout,stderr)->
+ concurrency--
+
+ if code and (options.retry or 0) > 0
+ echo warning "retrying #{options.retry} #{options.cwd}/#{cmdline}"
+ options.retry--
+ return execute cmdline,options,callback,ondata
+
+
+ # run the next one in the queue
+ if queue.length
+ fn = (queue.shift())
+ fn()
+
+ if code and !options.ignoreexitcode
+ echo error "Exec Failed #{quiet_info options.cwd} :: #{info cmdline}"
+ if( stderr.length )
+ echo error "(stderr)"
+ echo marked ">> #{error stderr}"
+ if( stdout.length )
+ echo warning "(stdout)"
+ echo warning stdout
+
+ Fail "Execute Task failed, fast exit"
+ callback(code,stdout,stderr)
+
+ proc.stdout.on 'data', ondata if ondata
+ return proc
+
+ autorest: (args,done,ignoreexitcode) ->
+ echo info "Queuing up: AutoRest #{args.join(' ')}"
+ execute "autorest \"--use=#{basefolder}\" #{args.map((a) -> "\"#{a}\"").join(' ')}" , {silent:true, ignoreexitcode: ignoreexitcode || false}, (code,stdout,stderr) ->
+ return done(code,stdout,stderr)
+
+# build task for global build
+module.exports.task 'build', 'builds project', ->
+ echo "Building project in #{basefolder}"
+
+module.exports.task 'clean', 'cleans the project files', ->
+
+module.exports.task 'regenerate', 'regenerates expected files for testing', ->
+
+
+# task for vs code
+module.exports.task 'code', 'launches vs code', ->
+ exec "code #{basefolder}"
+
+module.exports.task 'release-only', '', (done)->
+ Fail( "This command requires --configuration release" ) if configuration isnt "Release"
+ done()
+
+configString = (s)->
+ "#{s.charAt 0 .toUpperCase()}#{s.slice 1 .toLowerCase() }"
+
+# bring current module into global namespace.
+Import module.exports
+
+###############################################
+# Global values
+process.env["autorest.home"] = path.normalize("#{os.tmpdir()}/autorest#{hashCode(basefolder)}")
+process.env.tmp = process.env.tmp or "#{basefolder}/tmp"
+
+package_json = require("#{basefolder}/package.json")
+
+
+Import
+ stable: argv.stable or false
+ configuration: if argv.configuration then configString( argv.configuration) else (if argv.release then 'Release' else 'Debug')
+ github_apikey: argv.github_apikey or process.env.GITHUB_APIKEY or null
+ nuget_apikey: argv.nuget_apikey or process.env.NUGET_APIKEY or null
+ npm_apikey: argv.npm_apikey or process.env.NPM_APIKEY or null
+ autorest_home: process.env["autorest.home"]
+ today: moment().format('YYYYMMDD')
+ now: moment().format('YYYYMMDD-HHmm')
+ force: argv.force or false
+ threshold: argv.threshold or ((os.cpus().length)-1) or 1
+ verbose: argv.verbose or null
+ workdir: "#{process.env.tmp}/gulp/#{module.exports.guid()}"
+ watch: argv.watch or false
+
+mkdir "-p", workdir if !test "-d", workdir
+
+###############################################
+# UI stuff
+TerminalRenderer = require('marked-terminal')
+marked.setOptions {
+ renderer: new TerminalRenderer({
+ heading: chalk.green.bold,
+ firstHeading: chalk.green.bold,
+ showSectionPrefix: false,
+ strong: chalk.bold.cyan,
+ em: chalk.cyan,
+ blockquote: chalk.magenta,
+ tab: 2
+ })
+}
+
+set '+e'
+
+Import
+ error: chalk.bold.red
+ error_message: chalk.bold.cyan
+ warning: chalk.bold.yellow
+ info: chalk.bold.green
+ quiet_info: chalk.green
+
+###############################################
+task 'default','', ->
+ cmds = ""
+
+ for name, t of gulp.tasks
+ cmds += "\n gulp **#{name}** - #{t.description}" if t.description? and t.description.length
+ switches = ""
+
+ echo marked """
+
+# Usage
+
+## gulp commands
+#{cmds}
+
+## available switches
+ *--force* specify when you want to force an action (restore, etc)
+ *--configuration* 'debug' or 'release'
+ *--release* same as --configuration=release
+ *--nightly* generate label for package as 'YYYYMMDD-0000-nightly'
+ *--preview* generate label for package as 'YYYYMMDD-HHmm-preview'
+ *--verbose* enable verbose output
+ *--threshold=nn* set parallelism threshold (default = 10)
+
+#{switches}
+"""
+
+task 'test', "Run Tests", ->
+
+task 'fix-line-endings', 'Fixes line endings to file-type appropriate values.', ->
+ source "**/*.iced"
+ .pipe eol {eolc: 'LF', encoding:'utf8'}
+ .pipe destination '.'
+
+task 'version-number', '!', (done)->
+ if argv.version
+ global.version = argv.version if argv.version
+ done();
+ else
+ # git rev-list --parents HEAD --count --full-history
+ execute "git rev-list --parents HEAD --count --full-history" , {silent:true}, (c,o,e)->
+ pv = (package_json.version).trim()
+ global.version = "#{semver.major(pv)}.#{semver.minor(pv)}.#{o.trim()}"
+ done();
diff --git a/.gulp/dotnet.iced b/.gulp/dotnet.iced
new file mode 100644
index 0000000000..6ddea8e5c5
--- /dev/null
+++ b/.gulp/dotnet.iced
@@ -0,0 +1,59 @@
+
+# ==============================================================================
+# file selections
+
+Import
+ projects:() ->
+ source '**/*.csproj'
+ .pipe except /preview/ig
+
+# ==============================================================================
+# Functions
+
+dotnet = (cmd) ->
+ foreach (file, callback) ->
+ # check if the file is an actual file.
+ # if it's not, just skip this tool.
+ if !file or !file.path
+ return callback null, file
+
+ # do something with the file
+ await execute "dotnet #{cmd} #{ file.path } /nologo", defer code,stdout,stderr
+ # Fail "dotnet #{cmd} failed" if code
+ # or just done, no more processing
+ return callback null
+
+# ==============================================================================
+# Tasks
+
+
+task 'build','dotnet',['restore'], (done) ->
+ execute "dotnet build -c #{configuration} #{solution} /nologo /clp:NoSummary", (code, stdout, stderr) ->
+ execute "dotnet publish -c #{configuration} #{sourceFolder} --output #{sourceFolder}/bin/netcoreapp2.0 /nologo /clp:NoSummary ", (code, stdout, stderr) ->
+ done()
+
+task 'clear-cache-on-force', '', (done)->
+ if global.force
+ execute "dotnet nuget locals http-cache --clear", (c,o,e) ->
+ done()
+ else
+ done()
+
+task 'restore','restores the dotnet packages for the projects',['clear-cache-on-force'], (done) ->
+
+ if ! test '-d', "#{os.homedir()}/.nuget"
+ global.force = true
+
+ projects()
+ .pipe where (each) -> # check for project.assets.json files are up to date
+ rm "#{folder each.path}/obj/project.assets.json" if (force and test '-f', "#{folder each.path}/obj/project.assets.json")
+ return true if force
+ assets = "#{folder each.path}/obj/project.assets.json"
+ return false if (exists assets) and (newer assets, each.path)
+ return true
+ .pipe foreach (each,done)->
+ execute "dotnet restore #{ each.path } /nologo", {retry:1},(code,stderr,stdout) ->
+ done()
+
+# the dotnet gulp-plugin.
+module.exports = dotnet
\ No newline at end of file
diff --git a/.gulp/gulpfile.iced b/.gulp/gulpfile.iced
new file mode 100644
index 0000000000..ea9bd8c18c
--- /dev/null
+++ b/.gulp/gulpfile.iced
@@ -0,0 +1,27 @@
+require './common.iced'
+
+# ==============================================================================
+# tasks required for this build
+Tasks "dotnet" # dotnet functions
+Tasks "regeneration"
+
+# ==============================================================================
+# Settings
+Import
+ initialized: false
+ solution: "#{basefolder}/autorest.java.sln"
+ sourceFolder: "#{basefolder}/src/"
+
+# ==============================================================================
+# Tasks
+
+task 'init', "" ,(done)->
+ Fail "YOU MUST HAVE NODEJS VERSION GREATER THAN 7.10.0" if semver.lt( process.versions.node , "7.10.0" )
+ done()
+
+# Run language-specific tests:
+task 'test', "", [], (done) ->
+ await execute "mvn test -pl test/vanilla", defer code, stderr, stdout
+ await execute "mvn test -pl test/azure", defer code, stderr, stdout
+ await execute "mvn test -pl test/azurefluent", defer code, stderr, stdout
+ done();
diff --git a/.gulp/regeneration.iced b/.gulp/regeneration.iced
new file mode 100644
index 0000000000..74b8a5a887
--- /dev/null
+++ b/.gulp/regeneration.iced
@@ -0,0 +1,146 @@
+
+###############################################
+# LEGACY
+# Instead: have bunch of configuration files sitting in a well-known spot, discover them, feed them to AutoRest, done.
+
+regenExpected = (opts,done) ->
+ outputDir = if !!opts.outputBaseDir then "#{opts.outputBaseDir}/#{opts.outputDir}" else opts.outputDir
+ keys = Object.getOwnPropertyNames(opts.mappings)
+ instances = keys.length
+
+ for kkey in keys
+ optsMappingsValue = opts.mappings[kkey]
+ key = kkey.trim();
+
+ swaggerFiles = (if optsMappingsValue instanceof Array then optsMappingsValue[0] else optsMappingsValue).split(";")
+ args = [
+ "--#{opts.language}",
+ "--output-folder=#{outputDir}/#{key}",
+ "--license-header=#{if !!opts.header then opts.header else 'MICROSOFT_MIT_NO_VERSION'}",
+ "--enable-xml"
+ ]
+
+ for swaggerFile in swaggerFiles
+ args.push("--input-file=#{if !!opts.inputBaseDir then "#{opts.inputBaseDir}/#{swaggerFile}" else swaggerFile}")
+
+ if (opts.addCredentials)
+ args.push("--#{opts.language}.add-credentials=true")
+
+ if (opts.azureArm)
+ args.push("--#{opts.language}.azure-arm=true")
+
+ if (opts.fluent)
+ args.push("--#{opts.language}.fluent=true")
+
+ if (opts.syncMethods)
+ args.push("--#{opts.language}.sync-methods=#{opts.syncMethods}")
+
+ if (opts.flatteningThreshold)
+ args.push("--#{opts.language}.payload-flattening-threshold=#{opts.flatteningThreshold}")
+
+ if (!!opts.nsPrefix)
+ if (optsMappingsValue instanceof Array && optsMappingsValue[1] != undefined)
+ args.push("--#{opts.language}.namespace=#{optsMappingsValue[1]}")
+ else
+ args.push("--#{opts.language}.namespace=#{[opts.nsPrefix, key.replace(/\/|\./, '')].join('.')}")
+
+ if (opts['override-info.version'])
+ args.push("--override-info.version=#{opts['override-info.version']}")
+ if (opts['override-info.title'])
+ args.push("--override-info.title=#{opts['override-info.title']}")
+ if (opts['override-info.description'])
+ args.push("--override-info.description=#{opts['override-info.description']}")
+
+ autorest args,() =>
+ instances--
+ return done() if instances is 0
+
+defaultMappings = {
+ 'AcceptanceTests/ParameterFlattening': 'parameter-flattening.json',
+ 'AcceptanceTests/BodyArray': 'body-array.json',
+ 'AcceptanceTests/BodyBoolean': 'body-boolean.json',
+ 'AcceptanceTests/BodyByte': 'body-byte.json',
+ 'AcceptanceTests/BodyComplex': 'body-complex.json',
+ 'AcceptanceTests/BodyDate': 'body-date.json',
+ 'AcceptanceTests/BodyDateTime': 'body-datetime.json',
+ 'AcceptanceTests/BodyDateTimeRfc1123': 'body-datetime-rfc1123.json',
+ 'AcceptanceTests/BodyDuration': 'body-duration.json',
+ 'AcceptanceTests/BodyDictionary': 'body-dictionary.json',
+ 'AcceptanceTests/BodyFile': 'body-file.json',
+ 'AcceptanceTests/BodyFormData': 'body-formdata.json',
+ 'AcceptanceTests/BodyInteger': 'body-integer.json',
+ 'AcceptanceTests/BodyNumber': 'body-number.json',
+ 'AcceptanceTests/BodyString': 'body-string.json',
+ 'AcceptanceTests/Header': 'header.json',
+ 'AcceptanceTests/Http': 'httpInfrastructure.json',
+ 'AcceptanceTests/Report': 'report.json',
+ 'AcceptanceTests/RequiredOptional': 'required-optional.json',
+ 'AcceptanceTests/Url': 'url.json',
+ 'AcceptanceTests/Validation': 'validation.json',
+ 'AcceptanceTests/CustomBaseUri': 'custom-baseUrl.json',
+ 'AcceptanceTests/CustomBaseUriMoreOptions': 'custom-baseUrl-more-options.json',
+ 'AcceptanceTests/ModelFlattening': 'model-flattening.json'
+}
+
+defaultAzureMappings = {
+ 'AcceptanceTests/Lro': 'lro.json',
+ 'AcceptanceTests/Paging': 'paging.json',
+ 'AcceptanceTests/AzureReport': 'azure-report.json',
+ 'AcceptanceTests/AzureParameterGrouping': 'azure-parameter-grouping.json',
+ 'AcceptanceTests/AzureResource': 'azure-resource.json',
+ 'AcceptanceTests/Head': 'head.json',
+ 'AcceptanceTests/HeadExceptions': 'head-exceptions.json',
+ 'AcceptanceTests/SubscriptionIdApiVersion': 'subscriptionId-apiVersion.json',
+ 'AcceptanceTests/AzureSpecials': 'azure-special-properties.json',
+ 'AcceptanceTests/CustomBaseUri': 'custom-baseUrl.json'
+}
+
+swaggerDir = "node_modules/@microsoft.azure/autorest.testserver/swagger"
+
+task 'regenerate-javaazure', '', (done) ->
+ mappings = {}
+ for key of defaultAzureMappings
+ mappings[key.substring(16).toLowerCase()] = defaultAzureMappings[key]
+ regenExpected {
+ 'outputBaseDir': 'test/azure',
+ 'inputBaseDir': swaggerDir,
+ 'mappings': mappings,
+ 'outputDir': 'src/main/java/fixtures',
+ 'language': 'java',
+ 'azureArm': true,
+ 'nsPrefix': 'Fixtures'
+ },done
+ return null
+
+task 'regenerate-javaazurefluent', '', (done) ->
+ mappings = {}
+ for key of defaultAzureMappings
+ mappings[key.substring(16).toLowerCase()] = defaultAzureMappings[key]
+ regenExpected {
+ 'outputBaseDir': 'test/azurefluent',
+ 'inputBaseDir': swaggerDir,
+ 'mappings': mappings,
+ 'outputDir': 'src/main/java/fixtures',
+ 'language': 'java',
+ 'azureArm': true,
+ 'fluent': true,
+ 'nsPrefix': 'Fixtures'
+ },done
+ return null
+
+task 'regenerate-java', '', (done) ->
+ mappings = {}
+ for key of defaultMappings
+ mappings[key.substring(16).toLowerCase()] = defaultMappings[key]
+ regenExpected {
+ 'outputBaseDir': 'test/vanilla',
+ 'inputBaseDir': swaggerDir,
+ 'mappings': mappings,
+ 'outputDir': 'src/main/java/fixtures',
+ 'language': 'java',
+ 'nsPrefix': 'Fixtures'
+ },done
+ return null
+
+task 'regenerate', "regenerate expected code for tests", ['regenerate-java', 'regenerate-javaazure', 'regenerate-javaazurefluent'], (done) ->
+ done();
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000000..f8a119caaf
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,7 @@
+.gulp/
+.vscode/
+test/
+gulpfile.js
+*.sln
+
+src/obj/
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000000..87ac583fe2
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,14 @@
+{
+ // Use IntelliSense to find out which attributes exist for C# debugging
+ // Use hover for the description of the existing attributes
+ // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": ".NET Core Attach",
+ "type": "coreclr",
+ "request": "attach",
+ "processId": "${command:pickProcess}"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000000..591527e5c7
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,22 @@
+{
+ // we use gulp. npm is just for show.
+ "npm.autoDetect": "off",
+ "[csharp]": {
+ "editor.tabSize": 4
+ },
+ "[typescript]": {
+ "editor.formatOnSave": true,
+ "editor.formatOnPaste": true,
+ "editor.tabSize": 2,
+ "editor.detectIndentation": false
+ },
+ "[json]": {
+ "editor.formatOnSave": true,
+ "editor.formatOnPaste": true,
+ "editor.tabSize": 2,
+ "editor.detectIndentation": false
+ },
+ "files.associations": {
+ "*.iced": "coffeescript"
+ }
+}
\ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 0000000000..41eb96d599
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,29 @@
+{
+ // See https://go.microsoft.com/fwlink/?LinkId=733558
+ // for the documentation about the tasks.json format
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "type": "gulp",
+ "task": "test",
+ "problemMatcher": [
+ "$msCompile"
+ ],
+ "group": {
+ "kind": "test",
+ "isDefault": true
+ }
+ },
+ {
+ "type": "gulp",
+ "task": "build",
+ "group": {
+ "kind": "build",
+ "isDefault": true
+ },
+ "problemMatcher": [
+ "$msCompile"
+ ]
+ }
+ ]
+ }
\ No newline at end of file
diff --git a/README.md b/README.md
index 72f1506a93..f5acf8f469 100644
--- a/README.md
+++ b/README.md
@@ -12,3 +12,43 @@ provided by the bot. You will only need to do this once across all repos using o
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
+
+# AutoRest extension configuration
+
+``` yaml
+use-extension:
+ "@microsoft.azure/autorest.modeler": "*"
+
+pipeline:
+ java/modeler:
+ input: swagger-document/identity
+ output-artifact: code-model-v1
+ scope: java
+ java/commonmarker:
+ input: modeler
+ output-artifact: code-model-v1
+ java/cm/transform:
+ input: commonmarker
+ output-artifact: code-model-v1
+ java/cm/emitter:
+ input: transform
+ scope: scope-cm/emitter
+ java/generate:
+ plugin: java
+ input: cm/transform
+ output-artifact: source-file-java
+ java/transform:
+ input: generate
+ output-artifact: source-file-java
+ scope: scope-transform-string
+ java/emitter:
+ input: transform
+ scope: scope-java/emitter
+
+scope-java/emitter:
+ input-artifact: source-file-java
+ output-uri-expr: $key
+
+output-artifact:
+- source-file-java
+```
\ No newline at end of file
diff --git a/autorest.java.sln b/autorest.java.sln
new file mode 100644
index 0000000000..d6a015c761
--- /dev/null
+++ b/autorest.java.sln
@@ -0,0 +1,33 @@
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26430.16
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "autorest.java", "src\autorest.java.csproj", "{9E857E16-C008-4311-8799-CFA9D292D0B6}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|x64.Build.0 = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Debug|x86.Build.0 = Debug|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|x64.ActiveCfg = Release|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|x64.Build.0 = Release|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|x86.ActiveCfg = Release|Any CPU
+ {9E857E16-C008-4311-8799-CFA9D292D0B6}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000000..f231d0173d
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,4 @@
+// set the base folder of this project
+global.basefolder = `${__dirname}`
+require ("rechoir").prepare(require('interpret').extensions, './.gulp/gulpfile.iced');
+require ('./.gulp/gulpfile.iced')
diff --git a/package.json b/package.json
new file mode 100644
index 0000000000..4e805f5b9a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "@microsoft.azure/autorest.java",
+ "version": "1.9.0",
+ "description": "The Java extension for classic generators in AutoRest.",
+ "scripts": {
+ "start": "dotnet src/bin/netcoreapp2.0/autorest.java.dll --server",
+ "test": "gulp test",
+ "build": "gulp build",
+ "prepare": "gulp build",
+ "clean": "gulp clean",
+ "nuke": "git clean -xdf"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/Azure/autorest.java"
+ },
+ "readme": "https://github.com/Azure/autorest.java/readme.md",
+ "keywords": [
+ "autorest",
+ "classic-generators",
+ "java"
+ ],
+ "author": "Microsoft Corporation",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/Azure/autorest/issues"
+ },
+ "homepage": "https://github.com/Azure/autorest.java/blob/master/README.md",
+ "devDependencies": {
+ "coffee-script": "^1.11.1",
+ "dotnet-sdk-2.0.0": "^1.1.1",
+ "gulp": "^3.9.1",
+ "gulp-filter": "^5.0.0",
+ "gulp-line-ending-corrector": "^1.0.1",
+ "iced-coffee-script": "^108.0.11",
+ "marked": "^0.3.6",
+ "marked-terminal": "^2.0.0",
+ "moment": "^2.17.1",
+ "run-sequence": "*",
+ "shx": "^0.2.2",
+ "through2-parallel": "^0.1.3",
+ "yargs": "^8.0.2",
+ "@microsoft.azure/autorest.testserver": "^1.9.0"
+ },
+ "dependencies": {
+ "dotnet-2.0.0": "^1.1.0"
+ }
+}
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000000..57b41583a1
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,202 @@
+
+
+ 4.0.0
+
+ com.microsoft.azure
+ autorest-java
+ 1.0.0-SNAPSHOT
+ pom
+
+ AutoRest Code Generator Tests
+ This package contains the test for AutoRest generated Java clients.
+ https://github.com/Azure/autorest
+
+
+
+ The MIT License (MIT)
+ http://opensource.org/licenses/MIT
+ repo
+
+
+
+
+ scm:git:https://github.com/Azure/autorest-clientruntime-for-java
+ scm:git:git@github.com:Azure/autorest-clientruntime-for-java.git
+ HEAD
+
+
+
+ UTF-8
+
+ ${project.basedir}
+
+
+
+
+ microsoft
+ Microsoft
+
+
+
+
+
+ ossrh
+ Sonatype Snapshots
+ https://oss.sonatype.org/content/repositories/snapshots/
+ default
+
+ true
+ always
+
+
+
+
+
+
+ ossrh
+ Sonatype Snapshots
+ https://oss.sonatype.org/content/repositories/snapshots/
+ true
+ default
+
+
+
+
+
+
+ com.microsoft.azure
+ azure-mgmt-resources
+ 1.0.0
+
+
+ com.microsoft.rest
+ client-runtime
+ 1.0.3-SNAPSHOT
+
+
+ com.microsoft.azure
+ azure-client-runtime
+ 1.0.3-SNAPSHOT
+
+
+ commons-codec
+ commons-codec
+ 1.10
+
+
+ commons-io
+ commons-io
+ 2.4
+ test
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ junit
+ junit-dep
+ 4.11
+ test
+
+
+ org.slf4j
+ slf4j-simple
+ 1.7.22
+ test
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 2.17
+
+
+ com.microsoft.azure
+ autorest-build-tools
+ 1.0.0
+
+
+ com.puppycrawl.tools
+ checkstyle
+ 6.18
+
+
+
+ checkstyle.xml
+ samedir=build-tools/src/main/resources
+ suppressions.xml
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.1
+
+ 1.7
+ 1.7
+ true
+ true
+ -Xlint:unchecked
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.8
+
+ *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage
+ /**
+
* Copyright (c) Microsoft Corporation. All rights reserved.
+
* Licensed under the MIT License. See License.txt in the project root for
+
* license information.
+
*/]]>
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-resources-plugin
+ 2.4.3
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.18.1
+
+
+ **/Test*.java
+ **/*Test.java
+ **/*Tests.java
+ **/*TestCase.java
+
+
+
+
+ org.apache.maven.plugins
+ maven-release-plugin
+ 2.5.2
+
+
+
+
+
+ test/vanilla
+ test/azure
+ test/azurefluent
+
+
diff --git a/src/Program.cs b/src/Program.cs
new file mode 100644
index 0000000000..8fc92517bc
--- /dev/null
+++ b/src/Program.cs
@@ -0,0 +1,173 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using AutoRest.Core;
+using AutoRest.Core.Extensibility;
+using AutoRest.Core.Model;
+using AutoRest.Core.Parsing;
+using AutoRest.Core.Utilities;
+using Microsoft.Perks.JsonRPC;
+
+using IAnyPlugin = AutoRest.Core.Extensibility.IPlugin, AutoRest.Core.ITransformer, AutoRest.Core.CodeGenerator, AutoRest.Core.CodeNamer, AutoRest.Core.Model.CodeModel>;
+
+namespace AutoRest.Java
+{
+ public static class ExtensionsLoader
+ {
+ public static IAnyPlugin GetPlugin(string name)
+ {
+ switch (name)
+ {
+ case "Java": return new AutoRest.Java.PluginJv();
+ case "Azure.Java": return new AutoRest.Java.Azure.PluginJva();
+ case "Azure.Java.Fluent": return new AutoRest.Java.Azure.PluginJvaf();
+ }
+ throw new Exception("Unknown plugin: " + name);
+ }
+ }
+
+ public class Program : NewPlugin
+ {
+ public static int Main(string[] args )
+ {
+ if(args != null && args.Length > 0 && args[0] == "--server") {
+ var connection = new Connection(Console.Out, Console.OpenStandardInput());
+ connection.Dispatch>("GetPluginNames", async () => new []{ "java" });
+ connection.Dispatch("Process", (plugin, sessionId) => new Program(connection, plugin, sessionId).Process());
+ connection.DispatchNotification("Shutdown", connection.Stop);
+
+ // wait for something to do.
+ connection.GetAwaiter().GetResult();
+
+ Console.Error.WriteLine("Shutting Down");
+ return 0;
+ }
+ Console.WriteLine("This is not an entry point.");
+ Console.WriteLine("Please invoke this extension through AutoRest.");
+ return 1;
+ }
+
+ private string plugin;
+
+ public Program(Connection connection, string plugin, string sessionId) : base(connection, sessionId)
+ {
+ this.plugin = plugin;
+ }
+
+ private T GetXmsCodeGenSetting(CodeModel codeModel, string name)
+ {
+ try
+ {
+ return (T)Convert.ChangeType(
+ codeModel.CodeGenExtensions[name],
+ typeof(T).GenericTypeArguments.Length == 0 ? typeof(T) : typeof(T).GenericTypeArguments[0] // un-nullable
+ );
+ }
+ catch
+ {
+ return default(T);
+ }
+ }
+
+ protected override async Task ProcessInternal()
+ {
+ var codeGenerator = this.plugin;
+
+ var files = await ListInputs();
+ if (files.Length != 1)
+ {
+ throw new Exception($"Generator received incorrect number of inputs: {files.Length} : {string.Join(",", files)}");
+ }
+ var modelAsJson = (await ReadFile(files[0])).EnsureYamlIsJson();
+ var codeModelT = new ModelSerializer().Load(modelAsJson);
+
+ // get internal name
+ var language = new[] {
+ "CSharp",
+ "Ruby",
+ "NodeJS",
+ "Python",
+ "Go",
+ "Php",
+ "Java",
+ "AzureResourceSchema",
+ "JsonRpcClient" }
+ .Where(x => x.ToLowerInvariant() == codeGenerator)
+ .First();
+
+ // build settings
+ var altNamespace = (await GetValue("input-file") ?? new[] { "" }).FirstOrDefault()?.Split('/').Last().Split('\\').Last().Split('.').First();
+
+ new Settings
+ {
+ Namespace = await GetValue("namespace"),
+ ClientName = GetXmsCodeGenSetting(codeModelT, "name") ?? await GetValue("override-client-name"),
+ PayloadFlatteningThreshold = GetXmsCodeGenSetting(codeModelT, "ft") ?? await GetValue("payload-flattening-threshold") ?? 0,
+ AddCredentials = await GetValue("add-credentials") ?? false,
+ Host = this
+ };
+ var header = await GetValue("license-header");
+ if (header != null)
+ {
+ Settings.Instance.Header = header;
+ }
+ Settings.Instance.CustomSettings.Add("InternalConstructors", GetXmsCodeGenSetting(codeModelT, "internalConstructors") ?? await GetValue("use-internal-constructors") ?? false);
+ Settings.Instance.CustomSettings.Add("SyncMethods", GetXmsCodeGenSetting(codeModelT, "syncMethods") ?? await GetValue("sync-methods") ?? "essential");
+ Settings.Instance.CustomSettings.Add("UseDateTimeOffset", GetXmsCodeGenSetting(codeModelT, "useDateTimeOffset") ?? await GetValue("use-datetimeoffset") ?? false);
+ Settings.Instance.CustomSettings["ClientSideValidation"] = await GetValue("client-side-validation") ?? false;
+ int defaultMaximumCommentColumns = codeGenerator == "go" ? 120 : Settings.DefaultMaximumCommentColumns;
+ Settings.Instance.MaximumCommentColumns = await GetValue("max-comment-columns") ?? defaultMaximumCommentColumns;
+ Settings.Instance.OutputFileName = await GetValue("output-file");
+ if (codeGenerator == "csharp")
+ {
+ Settings.Instance.Header = $"\n{Settings.Instance.Header}\n";
+ }
+ if (codeGenerator == "ruby" || codeGenerator == "python")
+ {
+ // TODO: sort out matters here entirely instead of relying on Input being read somewhere...
+ var inputFile = await GetValue("input-file");
+ Settings.Instance.Input = inputFile.FirstOrDefault();
+ Settings.Instance.PackageName = await GetValue("package-name");
+ Settings.Instance.PackageVersion = await GetValue("package-version");
+ }
+ if (codeGenerator == "go")
+ {
+ Settings.Instance.PackageVersion = await GetValue("package-version");
+ }
+
+ // process
+ var plugin = ExtensionsLoader.GetPlugin(
+ (await GetValue("azure-arm") ?? false ? "Azure." : "") +
+ language +
+ (await GetValue("fluent") ?? false ? ".Fluent" : "") +
+ (await GetValue("testgen") ?? false ? ".TestGen" : ""));
+ Settings.PopulateSettings(plugin.Settings, Settings.Instance.CustomSettings);
+
+ using (plugin.Activate())
+ {
+ Settings.Instance.Namespace = Settings.Instance.Namespace ?? CodeNamer.Instance.GetNamespaceName(altNamespace);
+ var codeModel = plugin.Serializer.Load(modelAsJson);
+ codeModel = plugin.Transformer.TransformCodeModel(codeModel);
+ if (await GetValue("sample-generation") ?? false)
+ {
+ plugin.CodeGenerator.GenerateSamples(codeModel).GetAwaiter().GetResult();
+ }
+ else
+ {
+ plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
+ }
+ }
+
+ // write out files
+ var outFS = Settings.Instance.FileSystemOutput;
+ var outFiles = outFS.GetFiles("", "*", System.IO.SearchOption.AllDirectories);
+ foreach (var outFile in outFiles)
+ {
+ WriteFile(outFile, outFS.ReadAllText(outFile), null);
+ }
+
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/autorest.java.csproj b/src/autorest.java.csproj
new file mode 100644
index 0000000000..06c6e33d46
--- /dev/null
+++ b/src/autorest.java.csproj
@@ -0,0 +1,97 @@
+
+ # 2>nul || type %~df0|C:\Windows\system32\find.exe /v "setlocal"|C:\Windows\system32\find.exe /v "errorlevel"|powershell.exe -noninteractive -& exit %errorlevel% || #
+
+
+ autorest.java
+ autorest.extension
+ 1.2.2
+
+ true
+ $(MsBuildThisFileDirectory)
+ $(Common)../
+
+ Copyright (c) Microsoft Corporation
+
+ http://go.microsoft.com/fwlink/?LinkID=288890
+ https://github.com/Azure/AutoRest
+ https://raw.githubusercontent.com/Microsoft/dotnet/master/LICENSE
+ true
+
+
+
+ Exe
+ netcoreapp2.0
+ netcoreapp2.0
+ AutoRest.Java
+
+ $(MSBuildProjectDirectory)/bin
+ $(BaseOutputPath)
+
+
+
+
+
+
+
+
+
+
+ $(Powershell)
+ #
+ # modify resgen'd designer files for netframework1.4
+ #
+ cmd /c dir /s /b *.designer.cs |% { dir $_ } |% {
+ $content = (Get-Content "$_" -Raw )
+ if ( -not ($content -match "using System.Reflection") -and ($content -match "This class was auto-generated by the StronglyTypedResourceBuilder") ) {
+ write-host -fore green updating $_
+ $content = $content -replace "(using System;)", "`$1`n using System.Reflection;" -replace "(typeof\(.*\)).Assembly", "`$1.GetTypeInfo().Assembly"
+ Set-Content -value $content -path $_
+ }
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ All
+
+
+
+
+
+
+ $(Powershell)
+ $path = "$(BaseOutputPath)/netcoreapp2.0/$(TargetName).deps.json"
+ $content = (Get-Content "$path" -Raw )
+ $content = $content -replace ' "System.ComponentModel.Primitives/', ' "System.ComponentModel.Primitives.Nope/'
+ $content = $content -replace ' "System.Linq/', ' "System.Linq.Nope/'
+ $content = $content -replace ' "System.Net.Http/', ' "System.Net.Http.Nope/'
+ $content = $content -replace ' "System.Text.RegularExpressions/', ' "System.Text.RegularExpressions.Nope/'
+ $content = $content -replace ' "System.Threading.Thread/', ' "System.Threading.Thread.Nope/'
+ $content = $content -replace ' "System.Threading/', ' "System.Threading.Nope/'
+ $content = $content -replace ' "System.Xml.XDocument/', ' "System.Xml.XDocument.Nope/'
+ Set-Content -value $content -path $path
+
+
+
+
+
\ No newline at end of file
diff --git a/src/azure/ClientModelExtensions.cs b/src/azure/ClientModelExtensions.cs
new file mode 100644
index 0000000000..98557f9740
--- /dev/null
+++ b/src/azure/ClientModelExtensions.cs
@@ -0,0 +1,16 @@
+using AutoRest.Core.Model;
+using AutoRest.Extensions.Azure;
+
+namespace AutoRest.Java.Azure
+{
+ public static class ClientModelExtensions
+ {
+ public static bool IsResource(this IModelType type)
+ {
+ CompositeType compositeType = type as CompositeType;
+ return compositeType != null && (type.Name == "Resource" || type.Name == "SubResource") &&
+ compositeType.Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) &&
+ (bool)compositeType.Extensions[AzureExtensions.AzureResourceExtension];
+ }
+ }
+}
diff --git a/src/azure/CodeGeneratorJva.cs b/src/azure/CodeGeneratorJva.cs
new file mode 100644
index 0000000000..4c16e90542
--- /dev/null
+++ b/src/azure/CodeGeneratorJva.cs
@@ -0,0 +1,126 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using AutoRest.Core;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.azure.Templates;
+using AutoRest.Java.Model;
+using AutoRest.Java.vanilla.Templates;
+using System;
+
+namespace AutoRest.Java.Azure
+{
+ public class CodeGeneratorJva : CodeGeneratorJv
+ {
+ private const string ClientRuntimePackage = "com.microsoft.azure:azure-client-runtime:1.0.0-beta6-SNAPSHOT from snapshot repo https://oss.sonatype.org/content/repositories/snapshots/";
+ private const string _packageInfoFileName = "package-info.java";
+
+ public override bool IsSingleFileGenerationSupported => true;
+
+ public override string UsageInstructions => $"The {ClientRuntimePackage} maven dependency is required to execute the generated code.";
+
+ ///
+ /// Generates Azure Java code for service client.
+ ///
+ ///
+ ///
+ public override async Task Generate(CodeModel cm)
+ {
+ // get Azure Java specific codeModel
+ var codeModel = cm as CodeModelJva;
+ if (codeModel == null)
+ {
+ throw new InvalidCastException("CodeModel is not a Azure Java CodeModel");
+ }
+
+ // Service client
+ var serviceClientTemplate = new AzureServiceClientTemplate { Model = codeModel };
+ await Write(serviceClientTemplate, $"{Path.Combine("implementation", codeModel.Name.ToPascalCase() + "Impl")}{ImplementationFileExtension}");
+
+ // Service client interface
+ var serviceClientInterfaceTemplate = new AzureServiceClientInterfaceTemplate { Model = codeModel };
+ await Write(serviceClientInterfaceTemplate, $"{cm.Name.ToPascalCase()}{ImplementationFileExtension}");
+
+ // operations
+ foreach (MethodGroupJva methodGroup in codeModel.AllOperations)
+ {
+ // Operation
+ var operationsTemplate = new AzureMethodGroupTemplate { Model = methodGroup };
+ await Write(operationsTemplate, $"{Path.Combine("implementation", methodGroup.TypeName.ToPascalCase())}Impl{ImplementationFileExtension}");
+
+ // Operation interface
+ var operationsInterfaceTemplate = new AzureMethodGroupInterfaceTemplate { Model = methodGroup };
+ await Write(operationsInterfaceTemplate, $"{methodGroup.TypeName.ToPascalCase()}{ImplementationFileExtension}");
+ }
+
+ //Models
+ foreach (CompositeTypeJva modelType in cm.ModelTypes.Concat(codeModel.HeaderTypes))
+ {
+ if (modelType.Extensions.ContainsKey(AzureExtensions.ExternalExtension) &&
+ (bool)modelType.Extensions[AzureExtensions.ExternalExtension])
+ {
+ continue;
+ }
+ if (modelType.IsResource)
+ {
+ continue;
+ }
+
+ var modelTemplate = new ModelTemplate { Model = modelType };
+ await Write(modelTemplate, Path.Combine("models", $"{modelType.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ //Enums
+ foreach (EnumTypeJva enumType in cm.EnumTypes)
+ {
+ var enumTemplate = new EnumTemplate { Model = enumType };
+ await Write(enumTemplate, Path.Combine("models", $"{enumTemplate.Model.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Page class
+ foreach (var pageClass in codeModel.pageClasses)
+ {
+ var pageTemplate = new PageTemplate
+ {
+ Model = new PageJva(pageClass.Value, pageClass.Key.Key, pageClass.Key.Value),
+ };
+ await Write(pageTemplate, Path.Combine("models", $"{pageTemplate.Model.TypeDefinitionName.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Exceptions
+ foreach (CompositeTypeJv exceptionType in codeModel.ErrorTypes)
+ {
+ if (exceptionType.Name == "CloudError")
+ {
+ continue;
+ }
+
+ var exceptionTemplate = new ExceptionTemplate { Model = exceptionType };
+ await Write(exceptionTemplate, Path.Combine("models", $"{exceptionTemplate.Model.ExceptionTypeDefinitionName}{ImplementationFileExtension}"));
+ }
+
+ // package-info.java
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm)
+ }, _packageInfoFileName);
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm, "implementation")
+ }, Path.Combine("implementation", _packageInfoFileName));
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm, "models")
+ }, Path.Combine("models", _packageInfoFileName));
+ }
+ }
+}
diff --git a/src/azure/CodeNamerJva.cs b/src/azure/CodeNamerJva.cs
new file mode 100644
index 0000000000..a6de479c86
--- /dev/null
+++ b/src/azure/CodeNamerJva.cs
@@ -0,0 +1,29 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java.Azure
+{
+ public class CodeNamerJva : CodeNamerJv
+ {
+ public override string GetMethodGroupName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ name = PascalCase(name);
+ return name;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azure/GlobalSuppressions.cs b/src/azure/GlobalSuppressions.cs
new file mode 100644
index 0000000000..3b216ec3e1
--- /dev/null
+++ b/src/azure/GlobalSuppressions.cs
@@ -0,0 +1,65 @@
+// This file is used by Code Analysis to maintain SuppressMessage
+// attributes that are applied to this project.
+// Project-level suppressions either have no target or are given
+// a specific target and scoped to a namespace, type, member, etc.
+//
+// To add a suppression to this file, right-click the message in the
+// Code Analysis results, point to "Suppress Message", and click
+// "In Suppression File".
+// You do not need to add suppressions to this file manually.
+
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "AutoRest.Java")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ExceptionStatements")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.AzureServiceClientTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.Azure.PageTemplateModel.#ImportList")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.Azure.AzureServiceClientTemplateModel.#SetDefaultHeaders")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getNextPageLink", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getItems", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "addAll", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getItems", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "PagingBahavior", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ListOperationCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getNextPageLink", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ServiceResponse", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getResponse", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ServiceFuture", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "param", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceFuture", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ServiceCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.AzureJavaCodeNamer.#ImportType(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.AzureJavaCodeNamer.#ImportType(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.Azure.AzureCompositeTypeModel.#_azureRuntimePackage")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.AzureCompositeTypeModel.#.ctor(AutoRest.Java.CompositeTypeModel)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.AzureJavaCodeGenerator.#.ctor(AutoRest.Core.Settings)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.AzureModelTemplateModel.#.ctor(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getItems", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "PagingBahavior", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getNextPageLink", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ListOperationCallback", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#.ctor(AutoRest.Core.ClientModel.Method,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.AzureJavaCodeNamer.#NormalizeTopLevelTypes(AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodGroupTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.AzureServiceClientTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.Azure.AzureSequenceTypeModel.#_azureRuntimePackage")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+
diff --git a/src/azure/Model/CodeModelJva.cs b/src/azure/Model/CodeModelJva.cs
new file mode 100644
index 0000000000..c21b0169cf
--- /dev/null
+++ b/src/azure/Model/CodeModelJva.cs
@@ -0,0 +1,68 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Model;
+using AutoRest.Core.Utilities.Collections;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class CodeModelJva : CodeModelJv
+ {
+ public IDictionary, string> pageClasses =
+ new Dictionary, string>();
+
+ public const string ExternalExtension = "x-ms-external";
+
+ [JsonIgnore]
+ public IEnumerable PropertiesEx => Properties.Where(p => p.ModelType.Name != "ServiceClientCredentials");
+
+ [JsonIgnore]
+ public virtual string ParentDeclaration
+ {
+ get
+ {
+ return " extends AzureServiceClient implements " + Name;
+ }
+ }
+
+ [JsonIgnore]
+ public override List InterfaceImports
+ {
+ get
+ {
+ var imports = base.InterfaceImports;
+ imports.Add("com.microsoft.azure.AzureClient");
+ return imports.OrderBy(i => i).ToList();
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable ImplImports
+ {
+ get
+ {
+ var imports = base.ImplImports.ToList();
+ imports.Add("com.microsoft.azure.AzureClient");
+ imports.Remove("com.microsoft.rest.ServiceClient");
+ imports.Remove("okhttp3.OkHttpClient");
+ imports.Remove("retrofit2.Retrofit");
+ imports.Add("com.microsoft.azure.AzureServiceClient");
+ return imports.OrderBy(i => i).ToList();
+ }
+ }
+
+ [JsonIgnore]
+ public string SetDefaultHeaders
+ {
+ get
+ {
+ return "";
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Model/CompositeTypeJva.cs b/src/azure/Model/CompositeTypeJva.cs
new file mode 100644
index 0000000000..eaf9c2f34b
--- /dev/null
+++ b/src/azure/Model/CompositeTypeJva.cs
@@ -0,0 +1,97 @@
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Model;
+using Newtonsoft.Json;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class CompositeTypeJva : CompositeTypeJv
+ {
+ public CompositeTypeJva()
+ {
+ }
+
+ public CompositeTypeJva(string name) : base(name)
+ {
+ }
+
+ protected string _azureRuntimePackage = "com.microsoft.azure";
+
+ [JsonIgnore]
+ public override string Package => IsResource
+ ? _azureRuntimePackage
+ : base.Package.Replace(".models", "");
+
+ [JsonIgnore]
+ public bool IsResource =>
+ (Name.RawValue == "Resource" || Name.RawValue == "SubResource") &&
+ Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) && (bool)Extensions[AzureExtensions.AzureResourceExtension];
+
+ [JsonIgnore]
+ public override string ExceptionTypeDefinitionName
+ {
+ get
+ {
+ if (this.Extensions.ContainsKey(SwaggerExtensions.NameOverrideExtension))
+ {
+ var ext = this.Extensions[SwaggerExtensions.NameOverrideExtension] as Newtonsoft.Json.Linq.JContainer;
+ if (ext != null && ext["name"] != null)
+ {
+ return ext["name"].ToString();
+ }
+ }
+ return this.Name + "Exception";
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable Imports
+ {
+ get
+ {
+ var imports = new List();
+ if (Name.Contains('<'))
+ {
+ imports.AddRange(ParseGenericType().SelectMany(t => t.Imports));
+ }
+ else
+ {
+ if (IsResource || Extensions.Get(ExternalExtension) == true)
+ {
+ imports.Add(string.Join(".", Package, Name));
+ }
+ else
+ {
+ imports.Add(string.Join(".", Package, "models", Name));
+ }
+ }
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable ImportList
+ {
+ get
+ {
+ var imports = base.ImportList.ToList();
+ foreach (var property in this.Properties)
+ {
+ if (property.ModelType.IsResource())
+ {
+ imports.Add("com.microsoft.azure." + property.ModelType.Name);
+ }
+ }
+ if (this.BaseModelType != null && (this.BaseModelType.Name == "Resource" || this.BaseModelType.Name == "SubResource"))
+ {
+ imports.Add("com.microsoft.azure." + BaseModelType.Name);
+ }
+ return imports.Distinct();
+ }
+ }
+ }
+}
diff --git a/src/azure/Model/EnumTypeJva.cs b/src/azure/Model/EnumTypeJva.cs
new file mode 100644
index 0000000000..26f3f6a216
--- /dev/null
+++ b/src/azure/Model/EnumTypeJva.cs
@@ -0,0 +1,15 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using AutoRest.Core.Model;
+using AutoRest.Java.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class EnumTypeJva : EnumTypeJv
+ {
+ [JsonIgnore]
+ public override string ModelsPackage => ".models";
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Model/MethodGroupJva.cs b/src/azure/Model/MethodGroupJva.cs
new file mode 100644
index 0000000000..b5d791a0a5
--- /dev/null
+++ b/src/azure/Model/MethodGroupJva.cs
@@ -0,0 +1,22 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Model;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class MethodGroupJva : MethodGroupJv
+ {
+ public const string ExternalExtension = "x-ms-external";
+
+ public MethodGroupJva()
+ {
+ }
+ public MethodGroupJva(string name) : base(name)
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Model/MethodJva.cs b/src/azure/Model/MethodJva.cs
new file mode 100644
index 0000000000..47ba10eec0
--- /dev/null
+++ b/src/azure/Model/MethodJva.cs
@@ -0,0 +1,803 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using AutoRest.Core.Utilities.Collections;
+using static AutoRest.Core.Utilities.DependencyInjection;
+using Newtonsoft.Json;
+using System.Text.RegularExpressions;
+using System.Text;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class MethodJva : MethodJv
+ {
+ [JsonIgnore]
+ public string ClientRequestIdString => AzureExtensions.GetClientRequestIdString(this);
+
+ [JsonIgnore]
+ public string RequestIdString => AzureExtensions.GetRequestIdString(this);
+
+ ///
+ /// Returns true if method has x-ms-long-running-operation extension.
+ ///
+ [JsonIgnore]
+ public bool IsLongRunningOperation
+ {
+ get { return Extensions.ContainsKey(AzureExtensions.LongRunningExtension); }
+ }
+
+ [JsonIgnore]
+ public bool IsPagingNextOperation
+ {
+ get { return Extensions.ContainsKey("nextLinkMethod") && (bool) Extensions["nextLinkMethod"]; }
+ }
+
+ [JsonIgnore]
+ public bool IsPagingOperation => Extensions.ContainsKey(AzureExtensions.PageableExtension) &&
+ Extensions[AzureExtensions.PageableExtension] != null &&
+ !IsPagingNextOperation;
+
+ [JsonIgnore]
+ public bool IsPagingNonPollingOperation => Extensions.ContainsKey(AzureExtensions.PageableExtension) &&
+ Extensions[AzureExtensions.PageableExtension] == null &&
+ !IsPagingNextOperation;
+
+ [JsonIgnore]
+ public bool SimulateAsPagingOperation { set; get; } = false;
+
+ [JsonIgnore]
+ public ResponseJva ReturnTypeJva => ReturnType as ResponseJva;
+
+ ///
+ /// Get the type for operation exception.
+ ///
+ [JsonIgnore]
+ public override string OperationExceptionTypeString
+ {
+ get
+ {
+ if (DefaultResponse.Body == null || DefaultResponse.Body.Name == "CloudError")
+ {
+ return "CloudException";
+ }
+ else if (this.DefaultResponse.Body is CompositeType)
+ {
+ CompositeTypeJva type = this.DefaultResponse.Body as CompositeTypeJva;
+ return type.ExceptionTypeDefinitionName;
+ }
+ else
+ {
+ return "RestException";
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable RetrofitParameters
+ {
+ get
+ {
+ List parameters = base.RetrofitParameters.ToList();
+ var par = new ParameterJv
+ {
+ SerializedName = "User-Agent",
+ Location = ParameterLocation.Header,
+ ModelType = new PrimaryTypeJv(KnownPrimaryType.String),
+ ClientProperty = new PropertyJv
+ {
+ Name = "userAgent"
+ }
+ };
+ par.Name.FixedValue = Group.IsNullOrEmpty() ? "this.userAgent()" : "this.client.userAgent()";
+ parameters.Add(par);
+
+ if (IsPagingNextOperation)
+ {
+ parameters.RemoveAll(p => p.Location == ParameterLocation.Path);
+ parameters.Insert(0, new ParameterJv
+ {
+ Name = "nextUrl",
+ SerializedName = "nextUrl",
+ ModelType = New(KnownPrimaryType.String),
+ Documentation = "The URL to get the next page of items.",
+ Location = ParameterLocation.Path,
+ IsRequired = true
+ });
+ }
+
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodParameterApiDeclaration
+ {
+ get
+ {
+ var declaration = base.MethodParameterApiDeclaration;
+ if (IsPagingNextOperation)
+ {
+ declaration = declaration.Replace("@Path(\"nextUrl\")", "@Url");
+ }
+ foreach (var parameter in RetrofitParameters.Where(p =>
+ p.Location == ParameterLocation.Path || p.Location == ParameterLocation.Query))
+ {
+ if (parameter.Extensions.ContainsKey(AzureExtensions.SkipUrlEncodingExtension) &&
+ (bool) parameter.Extensions[AzureExtensions.SkipUrlEncodingExtension] == true)
+ {
+ declaration = declaration.Replace(
+ string.Format(CultureInfo.InvariantCulture, "@{0}(\"{1}\")", parameter.Location.ToString(), parameter.SerializedName),
+ string.Format(CultureInfo.InvariantCulture, "@{0}(value = \"{1}\", encoded = true)", parameter.Location.ToString(), parameter.SerializedName));
+ }
+ }
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodParameterDeclaration
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ List declarations = new List();
+ foreach (var parameter in LocalParameters.Where(p => !p.IsConstant))
+ {
+ declarations.Add("final " + parameter.ClientType.ParameterVariant.Name + " " + parameter.Name);
+ }
+
+ var declaration = string.Join(", ", declarations);
+ return declaration;
+ }
+ return base.MethodParameterDeclaration;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodRequiredParameterDeclaration
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ List declarations = new List();
+ foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+ {
+ declarations.Add("final " + parameter.ClientType.ParameterVariant.Name + " " + parameter.Name);
+ }
+
+ var declaration = string.Join(", ", declarations);
+ return declaration;
+ }
+ return base.MethodRequiredParameterDeclaration;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodParameterDeclarationWithCallback
+ {
+ get
+ {
+ var parameters = MethodParameterDeclaration;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ if (this.IsPagingOperation)
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback",
+ ReturnTypeJva.SequenceElementTypeString);
+ }
+ else if (this.IsPagingNextOperation)
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceFuture<{0}> serviceFuture, final ListOperationCallback<{1}> serviceCallback",
+ ReturnTypeJva.ServiceFutureGenericParameterString, ReturnTypeJva.SequenceElementTypeString);
+ }
+ else
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeJva.GenericBodyClientTypeString);
+ }
+
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodRequiredParameterDeclarationWithCallback
+ {
+ get
+ {
+ var parameters = MethodRequiredParameterDeclaration;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ if (this.IsPagingOperation)
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback",
+ ReturnTypeJva.SequenceElementTypeString);
+ }
+ else if (this.IsPagingNextOperation)
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceFuture<{0}> serviceFuture, final ListOperationCallback<{1}> serviceCallback",
+ ReturnTypeJva.ServiceFutureGenericParameterString, ReturnTypeJva.SequenceElementTypeString);
+ }
+ else
+ {
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeJva.GenericBodyClientTypeString);
+ }
+
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodParameterInvocationWithCallback
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ return base.MethodParameterInvocationWithCallback.Replace("serviceCallback", "serviceFuture, serviceCallback");
+ }
+ return base.MethodParameterInvocationWithCallback;
+ }
+ }
+
+ [JsonIgnore]
+ public override string MethodRequiredParameterInvocationWithCallback
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ return base.MethodRequiredParameterInvocationWithCallback.Replace("serviceCallback", "serviceFuture, serviceCallback");
+ }
+ return base.MethodRequiredParameterInvocationWithCallback;
+ }
+ }
+
+ [JsonIgnore]
+ public override bool IsParameterizedHost =>
+ (CodeModel?.Extensions?.ContainsKey(SwaggerExtensions.ParameterizedHostExtension) ?? false) &&
+ !IsPagingNextOperation;
+
+ [JsonIgnore]
+ public override IEnumerable Exceptions
+ {
+ get
+ {
+ var exceptions = base.Exceptions.ToList();
+ if (this.IsLongRunningOperation)
+ {
+ exceptions.Add("InterruptedException");
+ }
+ return exceptions;
+ }
+ }
+
+ [JsonIgnore]
+ public override List ExceptionStatements
+ {
+ get
+ {
+ List exceptions = base.ExceptionStatements;
+ if (this.IsLongRunningOperation)
+ {
+ exceptions.Add("InterruptedException exception thrown when long running operation is interrupted");
+ }
+ return exceptions;
+ }
+ }
+
+ [JsonIgnore]
+ public string PollingMethod
+ {
+ get
+ {
+ string method;
+ if (this.HttpMethod == HttpMethod.Put || this.HttpMethod == HttpMethod.Patch)
+ {
+ method = "getPutOrPatchResult";
+ }
+ else if (this.HttpMethod == HttpMethod.Delete || this.HttpMethod == HttpMethod.Post)
+ {
+ method = "getPostOrDeleteResult";
+ }
+ else
+ {
+ throw new InvalidOperationException("Invalid long running operation HTTP method " + this.HttpMethod);
+ }
+ if (ReturnType.Headers != null)
+ {
+ method += "WithHeaders";
+ }
+ return method;
+ }
+ }
+
+ [JsonIgnore]
+ public string PollingResourceTypeArgs
+ {
+ get
+ {
+ string args = "new TypeToken<" + ReturnTypeJva.GenericBodyClientTypeString + ">() { }.getType()";
+ if (ReturnType.Headers != null)
+ {
+ args += ", " + ReturnTypeJva.HeaderWireType.Name + ".class";
+ }
+ return args;
+ }
+ }
+
+ [JsonIgnore]
+ public override string ResponseBuilder
+ {
+ get
+ {
+ return "AzureResponseBuilder";
+ }
+ }
+
+ [JsonIgnore]
+ public override string ReturnTypeResponseName =>
+ ReturnTypeJv?.BodyClientType?.ServiceResponseVariant()?.Name;
+
+ public string PagingGroupedParameterTransformation(bool filterRequired = false)
+ {
+ var builder = new IndentedStringBuilder();
+ if (IsPagingOperation)
+ {
+ string invocation;
+ MethodJva nextMethod = GetPagingNextMethodWithInvocation(out invocation);
+ TransformPagingGroupedParameter(builder, nextMethod, filterRequired);
+ }
+ return builder.ToString();
+ }
+
+ public string NextMethodParameterInvocation(bool filterRequired = false)
+ {
+ string invocation;
+ MethodJva nextMethod = GetPagingNextMethodWithInvocation(out invocation);
+ if (filterRequired)
+ {
+ if (this.InputParameterTransformation.IsNullOrEmpty() || nextMethod.InputParameterTransformation.IsNullOrEmpty())
+ {
+ return nextMethod.MethodDefaultParameterInvocation;
+ }
+ var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ List invocations = new List();
+ foreach (var parameter in nextMethod.LocalParameters)
+ {
+ if (parameter.IsRequired)
+ {
+ invocations.Add(parameter.Name);
+ }
+ else if (parameter.Name == nextGroupType.Name && groupedType.IsRequired)
+ {
+ invocations.Add(parameter.Name);
+ }
+ else
+ {
+ invocations.Add("null");
+ }
+ }
+ return string.Join(", ", invocations);
+ }
+ else
+ {
+ return nextMethod.MethodParameterInvocation;
+ }
+ }
+
+ [JsonIgnore]
+ public string PagingNextPageLinkParameterName
+ {
+ get
+ {
+ string invocation;
+ MethodJva nextMethod = GetPagingNextMethodWithInvocation(out invocation);
+ return nextMethod.Parameters.First(p => p.Name.ToString().StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name;
+ }
+ }
+
+ public override string ResponseGeneration(bool filterRequired = false)
+ {
+ if (this.IsPagingOperation && !this.IsPagingNextOperation)
+ {
+ var builder = new IndentedStringBuilder();
+ builder.AppendLine("{0} response = {1}Delegate(call.execute());",
+ ReturnTypeJva.WireResponseTypeString, this.Name);
+
+ string invocation;
+ MethodJva nextMethod = GetPagingNextMethodWithInvocation(out invocation);
+
+ builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.body()) {{", ((SequenceType)ReturnType.Body).ElementType.Name)
+ .Indent().AppendLine("@Override")
+ .AppendLine("public Page<{0}> nextPage(String {1}) throws {2}, IOException {{",
+ ((SequenceType)ReturnType.Body).ElementType.Name,
+ nextMethod.Parameters.First(p => p.Name.ToString().StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name,
+ OperationExceptionTypeString)
+ .Indent();
+ TransformPagingGroupedParameter(builder, nextMethod, filterRequired);
+ builder.AppendLine("return {0}({1}).body();",
+ invocation, filterRequired ? nextMethod.MethodDefaultParameterInvocation : nextMethod.MethodParameterInvocation)
+ .Outdent().AppendLine("}")
+ .Outdent().AppendLine("};");
+ return builder.ToString();
+ }
+ else if (this.IsPagingNonPollingOperation)
+ {
+ var returnTypeBody = ReturnType.Body as SequenceTypeJva;
+ var builder = new IndentedStringBuilder();
+ builder.AppendLine("{0}<{1}<{2}>> response = {3}Delegate(call.execute());",
+ ReturnTypeJva.ClientResponseType, returnTypeBody.PageImplType, returnTypeBody.ElementType.Name, this.Name.ToCamelCase());
+ builder.AppendLine("{0} result = response.body().items();", this.ReturnType.Body.Name);
+ return builder.ToString();
+ }
+ else
+ {
+ return base.ResponseGeneration();
+ }
+ }
+
+ [JsonIgnore]
+ public override string ReturnValue
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNonPollingOperation)
+ {
+ if (ReturnType.Headers != null)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.headers(), response.response())",
+ ReturnTypeJva.ClientResponseType);
+ }
+ else
+ {
+ return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.response())",
+ ReturnTypeJva.ClientResponseType);
+ }
+ }
+ else
+ {
+ return base.ReturnValue;
+ }
+ }
+ }
+
+ public override string SuccessCallback(bool filterRequired = false)
+ {
+ if (this.IsPagingOperation)
+ {
+ var builder = new IndentedStringBuilder();
+ builder.AppendLine("{0} result = {1}Delegate(response);",
+ ReturnTypeJva.WireResponseTypeString, this.Name);
+ builder.AppendLine("if (serviceCallback != null) {").Indent();
+ builder.AppendLine("serviceCallback.load(result.body().items());");
+ builder.AppendLine("if (result.body().nextPageLink() != null").Indent().Indent()
+ .AppendLine("&& serviceCallback.progress(result.body().items()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent();
+ string invocation;
+ MethodJva nextMethod = GetPagingNextMethodWithInvocation(out invocation, true);
+ TransformPagingGroupedParameter(builder, nextMethod, filterRequired);
+ var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.body().nextPageLink(), {1});",
+ invocation,
+ filterRequired ? nextMethod.MethodRequiredParameterInvocationWithCallback : nextMethod.MethodParameterInvocationWithCallback);
+ builder.AppendLine(nextCall.Replace(
+ string.Format(", {0}", nextMethod.Parameters.First(p => p.Name.ToString().StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name),
+ "")).Outdent();
+ builder.AppendLine("} else {").Indent();
+ if (ReturnType.Headers == null)
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ else
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.headers(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ builder.Outdent().AppendLine("}").Outdent().AppendLine("}");
+ if (ReturnType.Headers == null)
+ {
+ builder.AppendLine("serviceFuture.success(new {0}<>(result.body().items(), response));", ReturnTypeJva.ClientResponseType);
+ }
+ else
+ {
+ builder.AppendLine("serviceFuture.success(new {0}<>(result.body().items(), result.headers(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ return builder.ToString();
+ }
+ else if (this.IsPagingNextOperation)
+ {
+ var builder = new IndentedStringBuilder();
+ builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeJva.WireResponseTypeString, this.Name);
+ builder.AppendLine("serviceCallback.load(result.body().items());");
+ builder.AppendLine("if (result.body().nextPageLink() != null").Indent().Indent();
+ builder.AppendLine("&& serviceCallback.progress(result.body().items()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent();
+ var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.body().nextPageLink(), {1});",
+ this.Name,
+ filterRequired ? MethodRequiredParameterInvocationWithCallback : MethodParameterInvocationWithCallback);
+ builder.AppendLine(nextCall.Replace(
+ string.Format(", {0}", Parameters.First(p => p.Name.ToString().StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name),
+ "")).Outdent();
+ builder.AppendLine("} else {").Indent();
+ if (ReturnType.Headers == null)
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ else
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.headers(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ builder.Outdent().AppendLine("}");
+ return builder.ToString();
+ }
+ else if (this.IsPagingNonPollingOperation)
+ {
+ var returnTypeBody = ReturnType.Body as SequenceTypeJva;
+ var builder = new IndentedStringBuilder();
+ builder.AppendLine("{0}<{1}<{2}>> result = {3}Delegate(response);",
+ ReturnTypeJva.ClientResponseType, returnTypeBody.PageImplType, returnTypeBody.ElementType.Name, this.Name.ToCamelCase());
+ if (ReturnType.Headers == null)
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(result.body().items(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ else
+ {
+ builder.AppendLine("serviceCallback.success(new {0}<>(result.body().items(), result.headers(), result.response()));", ReturnTypeJva.ClientResponseType);
+ }
+ return builder.ToString();
+ }
+ return base.SuccessCallback();
+ }
+
+ private MethodJva GetPagingNextMethodWithInvocation(out string invocation, bool async = false, bool singlePage = true)
+ {
+ String methodSuffixString = "WithServiceResponse";
+ if (singlePage)
+ {
+ methodSuffixString = "SinglePage";
+ }
+ if (IsPagingNextOperation)
+ {
+ invocation = Name + methodSuffixString + (async ? "Async" : "");
+ return this;
+ }
+ string name = this.Extensions.GetValue>("nextMethodName")?.ToCamelCase();
+ string group = this.Extensions.GetValue>("nextMethodGroup")?.ToCamelCase();
+ group = CodeNamerJva.Instance.GetMethodGroupName(group);
+ var methodModel =
+ CodeModel.Methods.FirstOrDefault(m =>
+ (group == null ? m.Group == null : group.Equals(m.Group, StringComparison.OrdinalIgnoreCase))
+ && m.Name.ToString().Equals(name, StringComparison.OrdinalIgnoreCase)) as MethodJva;
+ group = group.ToPascalCase();
+ name = name + methodSuffixString;
+ if (async)
+ {
+ name = name + "Async";
+ }
+ if (group == null || this.Group == methodModel.Group)
+ {
+ invocation = name;
+ }
+ else
+ {
+ invocation = string.Format(CultureInfo.InvariantCulture, "{0}.get{1}().{2}", ClientReference.Replace("this.", ""), group, name);
+ }
+ return methodModel;
+ }
+
+ public string GetPagingNextMethodInvocation(bool async = false, bool singlePage = true)
+ {
+ string invocation;
+ GetPagingNextMethodWithInvocation(out invocation, async, singlePage);
+ return invocation;
+ }
+
+ protected virtual void TransformPagingGroupedParameter(IndentedStringBuilder builder, MethodJva nextMethod, bool filterRequired = false)
+ {
+ if (this.InputParameterTransformation.IsNullOrEmpty() || nextMethod.InputParameterTransformation.IsNullOrEmpty())
+ {
+ return;
+ }
+ var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ if (nextGroupType.Name == groupedType.Name)
+ {
+ return;
+ }
+ var nextGroupTypeName = CodeNamerJva.Instance.GetTypeName(nextGroupType.Name);
+ if (filterRequired && !groupedType.IsRequired)
+ {
+ return;
+ }
+ if (!groupedType.IsRequired)
+ {
+ builder.AppendLine("{0} {1} = null;", nextGroupTypeName, nextGroupType.Name.ToCamelCase());
+ builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase());
+ builder.Indent();
+ builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
+ }
+ else
+ {
+ builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
+ }
+ foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter))
+ {
+ builder.AppendLine("{0}.with{1}({2}.{3}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase(), outParam.Name.ToCamelCase());
+ }
+ if (!groupedType.IsRequired)
+ {
+ builder.Outdent().AppendLine(@"}");
+ }
+ }
+
+ public override string ClientResponse(bool filterRequired = false)
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeJva.GenericBodyWireTypeString, this.Name);
+ builder.AppendLine("{0} body = null;", ReturnTypeJva.ServiceFutureGenericParameterString)
+ .AppendLine("if (result.body() != null) {")
+ .Indent().AppendLine("{0}", ReturnTypeJva.ConvertBodyToClientType("result.body()", "body"))
+ .Outdent().AppendLine("}");
+ builder.AppendLine("ServiceResponse<{0}> clientResponse = new ServiceResponse<{0}>(body, result.response());",
+ ReturnTypeJva.ServiceFutureGenericParameterString);
+ return builder.ToString();
+ }
+ else if (this.IsPagingNonPollingOperation)
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeJva.GenericBodyWireTypeString, this.Name);
+ builder.AppendLine("ServiceResponse<{0}> clientResponse = new ServiceResponse<{0}>(result.body().items(), result.response());",
+ ReturnTypeJva.ServiceFutureGenericParameterString);
+ return builder.ToString();
+ }
+ else
+ {
+ return base.ClientResponse(filterRequired);
+ }
+ }
+
+ [JsonIgnore]
+ public override string ServiceFutureFactoryMethod
+ {
+ get
+ {
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ if (ReturnType.Headers == null)
+ {
+ return "fromPageResponse";
+ }
+ else
+ {
+ return "fromHeaderPageResponse";
+ }
+ }
+ else
+ {
+ return base.ServiceFutureFactoryMethod;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public override string CallbackDocumentation
+ {
+ get
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ if (this.IsPagingNextOperation)
+ {
+ builder.AppendLine(" * @param serviceFuture the ServiceFuture object tracking the Retrofit calls");
+ }
+ builder.Append(" * @param serviceCallback the async ServiceCallback to handle successful and failed responses.");
+ return builder.ToString();
+ }
+ }
+
+ [JsonIgnore]
+ public string NextUrlConstruction
+ {
+ get
+ {
+ var builder = new StringBuilder("String.format(");
+ var regex = new Regex("{\\w+}");
+ var matches = regex.Matches(Url);
+ builder.Append("\"").Append(regex.Replace(Url, "%s").TrimStart('/')).Append("\"");
+ foreach (Match match in matches)
+ {
+ var sn = match.Value.Trim('{', '}');
+ builder.Append(", " + base.RetrofitParameters.First(p => p.SerializedName == sn).WireName);
+ }
+ return builder.Append(")").ToString();
+ }
+ }
+
+ [JsonIgnore]
+ public override string RuntimeBasePackage
+ {
+ get
+ {
+ return "com.microsoft.azure";
+ }
+ }
+
+ [JsonIgnore]
+ public override List InterfaceImports
+ {
+ get
+ {
+ var imports = base.InterfaceImports;
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ imports.Remove("com.microsoft.rest.ServiceCallback");
+ imports.Add("com.microsoft.azure.ListOperationCallback");
+ imports.Add("com.microsoft.azure.Page");
+ imports.Add("com.microsoft.azure.PagedList");
+ }
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public override List ImplImports
+ {
+ get
+ {
+ var imports = base.ImplImports;
+ if (this.IsLongRunningOperation)
+ {
+ imports.Remove("com.microsoft.azure.AzureResponseBuilder");
+ this.Responses.Select(r => r.Value.Body).Concat(new IModelType[] { DefaultResponse.Body })
+ .SelectMany(t => t.ImportSafe())
+ .Where(i => !this.Parameters.Any(p => p.ModelType.ImportSafe().Contains(i)))
+ .ForEach(i => imports.Remove(i));
+ // return type may have been removed as a side effect
+ imports.AddRange(ReturnTypeJva.ImplImports);
+ }
+ var typeName = (ReturnTypeJva.BodyClientType as SequenceTypeJva)?.PageImplType;
+ CompositeType ctype = null;
+ if (typeName != null)
+ {
+ ctype = new CompositeTypeJva();
+ ctype.Name.CopyFrom(typeName);
+ ctype.CodeModel = CodeModel;
+ }
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ imports.Remove("java.util.ArrayList");
+ imports.Remove("com.microsoft.rest.ServiceCallback");
+ imports.Add("com.microsoft.azure.ListOperationCallback");
+ imports.Add("com.microsoft.azure.Page");
+ imports.Add("com.microsoft.azure.PagedList");
+ imports.Add("com.microsoft.azure.AzureServiceFuture");
+ imports.AddRange(ctype.ImportSafe());
+ }
+ if (this.IsPagingNextOperation)
+ {
+ imports.Remove("retrofit2.http.Path");
+ imports.Add("retrofit2.http.Url");
+ }
+ if (this.IsPagingNonPollingOperation)
+ {
+ imports.AddRange(ctype.ImportSafe());
+ }
+ return imports;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Model/PageJva.cs b/src/azure/Model/PageJva.cs
new file mode 100644
index 0000000000..d9672d5eaf
--- /dev/null
+++ b/src/azure/Model/PageJva.cs
@@ -0,0 +1,47 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using Newtonsoft.Json;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class PageJva
+ {
+ public PageJva(string typeDefinitionName, string nextLinkName, string itemName)
+ {
+ this.TypeDefinitionName = typeDefinitionName;
+ this.NextLinkName = nextLinkName;
+ this.ItemName = itemName;
+ }
+
+ public string NextLinkName { get; private set; }
+
+ public string ItemName { get; private set; }
+
+ public string TypeDefinitionName { get; private set; }
+
+ [JsonIgnore]
+ public IEnumerable ImportList
+ {
+ get
+ {
+ List imports = new List();
+ imports.Add("com.microsoft.azure.Page");
+ imports.Add("java.util.List");
+ imports.Add("com.fasterxml.jackson.annotation.JsonProperty");
+ return imports.OrderBy(i => i).Distinct();
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ModelsPackage
+ {
+ get
+ {
+ return "models";
+ }
+ }
+ }
+}
diff --git a/src/azure/Model/ResponseJva.cs b/src/azure/Model/ResponseJva.cs
new file mode 100644
index 0000000000..2f6b082b6b
--- /dev/null
+++ b/src/azure/Model/ResponseJva.cs
@@ -0,0 +1,127 @@
+using System.Globalization;
+using AutoRest.Core.Model;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class ResponseJva : ResponseJv
+ {
+ public ResponseJva()
+ {
+ }
+
+ public ResponseJva(IModelTypeJv body, IModelTypeJv headers)
+ : base(body, headers)
+ {
+ }
+
+ public MethodJva Parent { get; set; }
+
+ [JsonIgnore]
+ public bool IsPagedResponse => Parent.IsPagingNextOperation || Parent.IsPagingOperation;
+
+ [JsonIgnore]
+ public override IModelTypeJv BodyClientType
+ {
+ get
+ {
+ var bodySequenceType = base.BodyClientType as SequenceTypeJva;
+ if (bodySequenceType != null && IsPagedResponse)
+ {
+ var result = new SequenceTypeJva
+ {
+ ElementType = bodySequenceType.ElementType,
+ PageImplType = bodySequenceType.PageImplType
+ };
+ result.Name.OnGet += name => $"Paged{name}";
+ return result;
+ }
+ return base.BodyClientType;
+ }
+ }
+
+ [JsonIgnore]
+ public override string GenericBodyClientTypeString
+ {
+ get
+ {
+ var bodySequenceType = base.BodyClientType as SequenceTypeJva;
+ if (bodySequenceType != null && IsPagedResponse)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "PagedList<{0}>", bodySequenceType.ElementType.Name);
+ }
+ return base.GenericBodyClientTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public override string ServiceFutureGenericParameterString
+ {
+ get
+ {
+ var bodySequenceType = base.BodyClientType as SequenceTypeJva;
+ if (bodySequenceType != null && IsPagedResponse)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "List<{0}>", bodySequenceType.ElementType.Name);
+ }
+ return GenericBodyClientTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public override string ServiceResponseGenericParameterString
+ {
+ get
+ {
+ var bodySequenceType = base.BodyClientType as SequenceTypeJva;
+ if (bodySequenceType != null && IsPagedResponse)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "Page<{0}>", bodySequenceType.ElementType.Name);
+ }
+ return GenericBodyClientTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public override string GenericBodyWireTypeString
+ {
+ get
+ {
+ var sequenceType = base.BodyClientType as SequenceTypeJva;
+ if (sequenceType != null && (IsPagedResponse || Parent.IsPagingNonPollingOperation))
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", sequenceType.PageImplType, sequenceType.ElementType.Name);
+ }
+ return base.GenericBodyWireTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public override string ClientCallbackTypeString
+ {
+ get
+ {
+ if (Body is SequenceType && IsPagedResponse)
+ {
+ return BodyClientType.Name;
+ }
+ return base.ClientCallbackTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public override string ObservableClientResponseTypeString
+ {
+ get
+ {
+ if (IsPagedResponse)
+ {
+ return "ServiceResponse<" + ServiceResponseGenericParameterString + ">";
+ }
+ return base.ObservableClientResponseTypeString;
+ }
+ }
+ }
+}
diff --git a/src/azure/Model/SequenceTypeJva.cs b/src/azure/Model/SequenceTypeJva.cs
new file mode 100644
index 0000000000..ecc532e814
--- /dev/null
+++ b/src/azure/Model/SequenceTypeJva.cs
@@ -0,0 +1,13 @@
+using AutoRest.Core.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java.Azure.Model
+{
+ public class SequenceTypeJva : SequenceTypeJv
+ {
+ protected string _azureRuntimePackage = "com.microsoft.azure";
+
+ public string PageImplType { get; set; }
+ }
+}
diff --git a/src/azure/PluginJva.cs b/src/azure/PluginJva.cs
new file mode 100644
index 0000000000..800b73d412
--- /dev/null
+++ b/src/azure/PluginJva.cs
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+//
+
+using AutoRest.Core;
+using AutoRest.Core.Extensibility;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java.Azure
+{
+ public sealed class PluginJva : Plugin
+ {
+ public PluginJva()
+ {
+ Context = new Context
+ {
+ // inherit base settings
+ Context,
+
+ // set code model implementations our own implementations
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory()
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureMethodGroupInterfaceTemplate.cshtml b/src/azure/Templates/AzureMethodGroupInterfaceTemplate.cshtml
new file mode 100644
index 0000000000..8745c01b7c
--- /dev/null
+++ b/src/azure/Templates/AzureMethodGroupInterfaceTemplate.cshtml
@@ -0,0 +1,32 @@
+@using System
+@using AutoRest.Java.azure.Templates
+@using AutoRest.Java.vanilla.Templates
+@using System.Linq;
+@using AutoRest.Java
+@using AutoRest.Java.Model
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+/**
+@Header(" * ").TrimMultilineHeader()
+ */
+@EmptyLine
+
+package @(Settings.Namespace.ToLower());
+@EmptyLine
+@foreach (var importClass in Model.InterfaceImports)
+{
+@:import @importClass;
+}
+@EmptyLine
+
+/**
+ * An instance of this class provides access to all the operations defined
+ * in @(Model.TypeName).
+ */
+public interface @Model.TypeName {
+ @foreach (MethodJv method in Model.Methods)
+ {
+ @:@Include(new MethodInterfaceTemplate(), method)
+ @EmptyLine
+ }
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureMethodGroupRetrofitTemplate.cshtml b/src/azure/Templates/AzureMethodGroupRetrofitTemplate.cshtml
new file mode 100644
index 0000000000..e35bbe7bc7
--- /dev/null
+++ b/src/azure/Templates/AzureMethodGroupRetrofitTemplate.cshtml
@@ -0,0 +1,40 @@
+@using System.Linq;
+@using AutoRest.Core.Model
+@using AutoRest.Core.Utilities
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+/**
+ * The interface defining all the services for @Model.TypeName to be
+ * used by Retrofit to perform actually REST calls.
+ */
+interface @Model.MethodGroupServiceType {
+@foreach (MethodJva method in Model.Methods)
+{
+if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
+{
+@: @@Multipart
+}
+else
+{
+@: @@Headers({ "Content-Type: @method.RequestContentType", "x-ms-logging-context: @Model.MethodGroupFullType @method.Name" })
+}
+if (method.HttpMethod == HttpMethod.Delete)
+{
+@: @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
+}
+else if (method.IsPagingNextOperation)
+{
+@: @@GET
+}
+else
+{
+@: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
+}
+if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
+{
+@: @@Streaming
+}
+@: Observable> @(method.Name)(@method.MethodParameterApiDeclaration);
+@EmptyLine
+}
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureMethodGroupTemplate.cshtml b/src/azure/Templates/AzureMethodGroupTemplate.cshtml
new file mode 100644
index 0000000000..125cee1dca
--- /dev/null
+++ b/src/azure/Templates/AzureMethodGroupTemplate.cshtml
@@ -0,0 +1,62 @@
+@using System
+@using AutoRest.Java.azure.Templates
+@using System.Linq;
+@using AutoRest.Java
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+/**
+@Header(" * ").TrimMultilineHeader()
+ */
+@EmptyLine
+
+package @(Settings.Namespace.ToLower()).@(Model.ImplPackage);
+@EmptyLine
+@foreach (var importClass in Model.ImplImports)
+{
+@:import @importClass;
+}
+@EmptyLine
+
+/**
+ * An instance of this class provides access to all the operations defined
+ * in @(Model.TypeName).
+ */
+public class @(Model.MethodGroupImplType)@(Model.ParentDeclaration) {
+ /** The Retrofit service to perform REST calls. */
+ private @Model.MethodGroupServiceType service;
+ /** The service client containing this operation class. */
+ private @(Model.ServiceClientType) client;
+ @EmptyLine
+ /**
+ * Initializes an instance of @(Model.MethodGroupImplType).
+ *
+ * @@param retrofit the Retrofit instance built from a Retrofit Builder.
+ * @@param client the instance of the service client containing this operation class.
+ */
+ public @(Model.MethodGroupImplType)(Retrofit retrofit, @(Model.ServiceClientType) client) {
+ this.service = retrofit.create(@(Model.MethodGroupServiceType).class);
+ this.client = client;
+ }
+ @EmptyLine
+
+ @Include(new AzureMethodGroupRetrofitTemplate(), Model)
+
+ @EmptyLine
+
+ @foreach (MethodJva method in Model.Methods)
+ {
+ if (method.IsPagingOperation || method.IsPagingNextOperation)
+ {
+ @:@(Include(new PagingMethodTemplate(), method))
+ }
+ else if (method.SimulateAsPagingOperation)
+ {
+ @:@(Include(new SimulatedPageMethodTemplate(), method))
+ }
+ else
+ {
+ @:@(Include(new AzureMethodTemplate(), method))
+ }
+ @EmptyLine
+ }
+}
diff --git a/src/azure/Templates/AzureMethodTemplate.cshtml b/src/azure/Templates/AzureMethodTemplate.cshtml
new file mode 100644
index 0000000000..211a6a114c
--- /dev/null
+++ b/src/azure/Templates/AzureMethodTemplate.cshtml
@@ -0,0 +1,269 @@
+@using System
+@using AutoRest.Java
+@using AutoRest.Java.vanilla.Templates
+@using AutoRest.Java.azure.Templates
+@using System.Linq
+@using AutoRest.Core.Utilities
+@using AutoRest.Java.Model
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+@if (!Model.IsLongRunningOperation)
+{
+@:@(Include(new MethodTemplate(), Model as MethodJv))
+}
+else
+{
+if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired))
+{
+
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@throws @Model.OperationExceptionTypeString thrown if the request is rejected by server
+ * @@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object if successful.
+}
+ */
+public @Model.ReturnTypeResponseName @(Model.Name)(@Model.MethodRequiredParameterDeclaration) {
+@if (@Model.ReturnTypeJva.BodyClientType.ResponseVariant.Name == "void")
+{
+@: @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation).toBlocking().last().body();
+}
+else
+{
+@: return @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation).toBlocking().last().body();
+}
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJva.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCallback) {
+ return ServiceFuture.@(Model.ServiceFutureFactoryMethod)(@(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation), serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the observable for the request
+ */
+public Observable<@Model.ReturnTypeJva.GenericBodyClientTypeString> @(Model.Name)Async(@Model.MethodRequiredParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation).map(new Func1<@Model.ReturnTypeJva.ClientResponseTypeString, @Model.ReturnTypeJva.GenericBodyClientTypeString>() {
+ @@Override
+ public @Model.ReturnTypeJva.GenericBodyClientTypeString call(@Model.ReturnTypeJva.ClientResponseTypeString response) {
+ return response.body();
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the observable for the request
+ */
+public Observable<@Model.ReturnTypeJva.ClientResponseTypeString> @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterDeclaration) {
+@foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate.Where(p => p.IsRequired))
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (!parameter.IsRequired)
+ {
+@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.GetDefaultValue(Model) ?? "null");
+ }
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ClientType.ParameterVariant.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+ }
+}
+ @Model.BuildInputMappings(true)
+ @Model.RequiredParameterConversion
+ Observable> observable = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation);
+ return client.getAzureClient().@(Model.PollingMethod)Async(observable, @Model.PollingResourceTypeArgs);
+}
+
+}
+
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@throws @Model.OperationExceptionTypeString thrown if the request is rejected by server
+ * @@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object if successful.
+}
+ */
+public @Model.ReturnTypeResponseName @(Model.Name)(@Model.MethodParameterDeclaration) {
+@if (@Model.ReturnTypeResponseName == "void")
+{
+@: @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation).toBlocking().last().body();
+}
+else
+{
+@: return @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation).toBlocking().last().body();
+}
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJva.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallback) {
+ return ServiceFuture.@(Model.ServiceFutureFactoryMethod)(@(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation), serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the observable for the request
+ */
+public Observable<@Model.ReturnTypeJva.GenericBodyClientTypeString> @(Model.Name)Async(@Model.MethodParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation).map(new Func1<@Model.ReturnTypeJva.ClientResponseTypeString, @Model.ReturnTypeJva.GenericBodyClientTypeString>() {
+ @@Override
+ public @Model.ReturnTypeJva.GenericBodyClientTypeString call(@Model.ReturnTypeJva.ClientResponseTypeString response) {
+ return response.body();
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the observable for the request
+ */
+public Observable<@Model.ReturnTypeJva.ClientResponseTypeString> @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterDeclaration) {
+@foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate)
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ModelType.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+ }
+}
+ @Model.BuildInputMappings()
+ @Model.ParameterConversion
+ Observable> observable = service.@(Model.Name)(@Model.MethodParameterApiInvocation);
+ return client.getAzureClient().@(Model.PollingMethod)Async(observable, @Model.PollingResourceTypeArgs);
+}
+
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureServiceClientInterfaceTemplate.cshtml b/src/azure/Templates/AzureServiceClientInterfaceTemplate.cshtml
new file mode 100644
index 0000000000..fafa77d9ba
--- /dev/null
+++ b/src/azure/Templates/AzureServiceClientInterfaceTemplate.cshtml
@@ -0,0 +1,87 @@
+@using System
+@using AutoRest.Java.azure.Templates
+@using AutoRest.Java.vanilla.Templates
+@using System.Linq
+@using AutoRest.Core.Utilities
+@using AutoRest.Java
+@using AutoRest.Java.Model
+@inherits AutoRest.Core.Template
+/**
+@Header(" * ").TrimMultilineHeader()
+ */
+@EmptyLine
+
+package @(Settings.Namespace.ToLower());
+@EmptyLine
+@foreach (var importClass in Model.InterfaceImports)
+{
+@:import @importClass;
+}
+@EmptyLine
+
+/**
+ * The interface for @Model.Name class.
+ */
+public interface @Model.Name {
+ /**
+ * Gets the REST client.
+ *
+ * @@return the {@@link RestClient} object.
+ */
+ RestClient restClient();
+@EmptyLine
+ /**
+ * Gets the {@@link AzureClient} used for long running operations.
+ * @@return the azure client;
+ */
+ AzureClient getAzureClient();
+@EmptyLine
+ /**
+ * Gets the User-Agent header for the client.
+ *
+ * @@return the user agent string.
+ */
+ String userAgent();
+@foreach (var property in Model.PropertiesEx)
+{
+@EmptyLine
+@: /**
+@: * Gets @(property.Documentation).
+@: *
+@: * @@return the @(property.Name) value.
+@: */
+@: @property.ModelType.ServiceResponseVariant().Name @(property.Name.ToCamelCase())();
+if(!property.IsReadOnly)
+{
+@EmptyLine
+@: /**
+@: * Sets @(property.Documentation).
+@: *
+@: * @@param @(property.Name.ToCamelCase()) the @(property.Name) value.
+@: * @@return the service client itself
+@: */
+@: @(Model.Name) with@(property.Name.ToPascalCase())(@(property.ModelType.ServiceResponseVariant().Name) @(property.Name.ToCamelCase()));
+}
+}
+
+@foreach (var operation in Model.AllOperations)
+{
+@EmptyLine
+@: /**
+@: * Gets the @(operation.TypeName) object to access its operations.
+@: * @@return the @(operation.TypeName) object.
+@: */
+@: @(operation.TypeName) @(operation.Name.ToCamelCase())();
+}
+@EmptyLine
+@if (Model.RootMethods.Any())
+{
+
+ @foreach (MethodJv method in Model.RootMethods)
+ {
+ @:@Include(new MethodInterfaceTemplate(), method)
+ @EmptyLine
+ }
+
+}
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureServiceClientRetrofitTemplate.cshtml b/src/azure/Templates/AzureServiceClientRetrofitTemplate.cshtml
new file mode 100644
index 0000000000..284f4eaaff
--- /dev/null
+++ b/src/azure/Templates/AzureServiceClientRetrofitTemplate.cshtml
@@ -0,0 +1,40 @@
+@using System.Linq;
+@using AutoRest.Core.Model
+@using AutoRest.Core.Utilities
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+/**
+ * The interface defining all the services for @Model.Name to be
+ * used by Retrofit to perform actually REST calls.
+ */
+interface @Model.ServiceClientServiceType {
+@foreach (MethodJva method in Model.RootMethods)
+{
+if (method.RequestContentType == "multipart/form-data" || method.RequestContentType == "application/x-www-form-urlencoded")
+{
+@: @@Multipart
+}
+else
+{
+@: @@Headers({ "Content-Type: @method.RequestContentType", "x-ms-logging-context: @Model.FullyQualifiedDomainName @method.Name" })
+}
+if (method.HttpMethod == HttpMethod.Delete)
+{
+@: @@HTTP(path = "@(method.Url.TrimStart('/'))", method = "DELETE", hasBody = true)
+}
+else if (method.IsPagingNextOperation)
+{
+@: @@GET
+}
+else
+{
+@: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))")
+}
+if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
+{
+@: @@Streaming
+}
+@: Observable> @(method.Name)(@method.MethodParameterApiDeclaration);
+@EmptyLine
+}
+}
\ No newline at end of file
diff --git a/src/azure/Templates/AzureServiceClientTemplate.cshtml b/src/azure/Templates/AzureServiceClientTemplate.cshtml
new file mode 100644
index 0000000000..76ac539f65
--- /dev/null
+++ b/src/azure/Templates/AzureServiceClientTemplate.cshtml
@@ -0,0 +1,223 @@
+@using System
+@using AutoRest.Java.azure.Templates
+@using AutoRest.Java.vanilla.Templates
+@using System.Linq
+@using AutoRest.Core.Utilities
+@using AutoRest.Java
+@using AutoRest.Java.Azure.Model
+@using AutoRest.Java.Model
+@inherits AutoRest.Core.Template
+/**
+@Header(" * ").TrimMultilineHeader()
+ */
+@EmptyLine
+
+package @(Settings.Namespace.ToLower()).@(Model.ImplPackage);
+
+@EmptyLine
+@foreach (var importClass in Model.ImplImports)
+{
+@:import @importClass;
+}
+@EmptyLine
+
+/**
+ * Initializes a new instance of the @(Model.Name)Impl class.
+ */
+public class @(Model.Name)Impl@(Model.ParentDeclaration) {
+@if (Model.RootMethods.Any())
+{
+@: /** The Retrofit service to perform REST calls. */
+@: private @Model.ServiceClientServiceType service;
+}
+ /** the {@@link AzureClient} used for long running operations. */
+ private AzureClient azureClient;
+@EmptyLine
+ /**
+ * Gets the {@@link AzureClient} used for long running operations.
+ * @@return the azure client;
+ */
+ public AzureClient getAzureClient() {
+ return this.azureClient;
+ }
+@foreach (var property in Model.PropertiesEx)
+{
+@EmptyLine
+@: /** @(property.Documentation.ToString().Period()) */
+@: private @(property.ModelType.ServiceResponseVariant().Name) @(property.Name.ToCamelCase());
+@EmptyLine
+@: /**
+@: * Gets @(property.Documentation.ToString().Period())
+@: *
+@: * @@return the @(property.Name) value.
+@: */
+@: public @(property.ModelType.ServiceResponseVariant().Name) @(property.Name.ToCamelCase())() {
+@: return this.@(property.Name.ToCamelCase());
+@: }
+if(!property.IsReadOnly)
+{
+@EmptyLine
+@: /**
+@: * Sets @(property.Documentation.ToString().Period())
+@: *
+@: * @@param @(property.Name.ToCamelCase()) the @(property.Name) value.
+@: * @@return the service client itself
+@: */
+@: public @(Model.Name)Impl with@(property.Name.ToPascalCase())(@(property.ModelType.ServiceResponseVariant().Name) @(property.Name.ToCamelCase())) {
+@: this.@(property.Name.ToCamelCase()) = @(property.Name.ToCamelCase());
+@: return this;
+@: }
+}
+}
+
+@foreach (var operation in Model.AllOperations)
+{
+@EmptyLine
+@: /**
+@: * The @(operation.MethodGroupDeclarationType) object to access its operations.
+@: */
+@: private @(operation.MethodGroupDeclarationType) @(operation.Name);
+@EmptyLine
+@: /**
+@: * Gets the @(operation.MethodGroupDeclarationType) object to access its operations.
+@: * @@return the @(operation.MethodGroupDeclarationType) object.
+@: */
+@: public @(operation.MethodGroupDeclarationType) @(operation.Name)() {
+@: return this.@(operation.Name);
+@: }
+}
+@EmptyLine
+
+@if (Settings.AddCredentials)
+{
+
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ *
+ * @@param credentials the management credentials for Azure
+ */
+ public @(Model.Name)Impl(ServiceClientCredentials credentials) {
+ this("@Model.BaseUrl", credentials);
+ }
+@EmptyLine
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ *
+ * @@param baseUrl the base URL of the host
+ * @@param credentials the management credentials for Azure
+ */
+ @(Model.IsCustomBaseUri ? "private" : "public") @(Model.Name)Impl(String baseUrl, ServiceClientCredentials credentials) {
+ super(baseUrl, credentials);
+ initialize();
+ }
+@EmptyLine
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ *
+ * @@param restClient the REST client to connect to Azure.
+ */
+ public @(Model.Name)Impl(RestClient restClient) {
+ super(restClient);
+ initialize();
+ }
+
+@EmptyLine
+
+
+}
+else
+{
+
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ */
+ public @(Model.Name)Impl() {
+ this("@Model.BaseUrl");
+ }
+@EmptyLine
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ *
+ * @@param baseUrl the base URL of the host
+ */
+ @(Model.IsCustomBaseUri ? "private" : "public") @(Model.Name)Impl(String baseUrl) {
+ this(baseUrl, null);
+ }
+@EmptyLine
+ /**
+ * Initializes an instance of @(Model.Name) client.
+ *
+ * @@param restClient the REST client to connect to Azure
+ */
+ public @(Model.Name)Impl(RestClient restClient) {
+ super(restClient);
+ restClient.baseUrl("@Model.BaseUrl");
+ initialize();
+ }
+@EmptyLine
+
+}
+ protected void initialize() {
+@foreach (var property in Model.PropertiesEx.Where(p => p.DefaultValue != null))
+{
+ @:this.@(property.Name) = @(property.DefaultValue);
+}
+@foreach (MethodGroupJva operation in Model.AllOperations)
+{
+@: this.@(operation.Name) = new @(operation.MethodGroupImplType)(restClient().retrofit(), this);
+}
+ @Model.SetDefaultHeaders
+ this.azureClient = new AzureClient(this);
+@if (Model.RootMethods.Any())
+{
+@: initializeService();
+}
+ }
+@EmptyLine
+
+ /**
+ * Gets the User-Agent header for the client.
+ *
+ * @@return the user agent string.
+ */
+ @@Override
+ public String userAgent() {
+@if (Model.ApiVersion == null)
+{
+@: return String.format("%s (%s)", super.userAgent(), "@Model.Name");
+}
+else
+{
+@: return String.format("%s (%s, %s)", super.userAgent(), "@Model.Name", "@Model.ApiVersion");
+}
+ }
+@if (Model.RootMethods.Any())
+{
+@EmptyLine
+
+ private void initializeService() {
+ service = restClient().retrofit().create(@(Model.ServiceClientServiceType).class);
+ }
+
+@EmptyLine
+if (Model.RootMethods.Any())
+{
+@: @Include(new AzureServiceClientRetrofitTemplate(), Model)
+@EmptyLine
+}
+
+@foreach (MethodJva method in Model.RootMethods)
+{
+ if (method.IsPagingOperation || method.IsPagingNextOperation)
+ {
+ @:@(Include(new PagingMethodTemplate(), method))
+ }
+ else
+ {
+ @:@(Include(new AzureMethodTemplate(), method))
+ }
+ @EmptyLine
+}
+
+}
+}
diff --git a/src/azure/Templates/PageTemplate.cshtml b/src/azure/Templates/PageTemplate.cshtml
new file mode 100644
index 0000000000..8906f9d470
--- /dev/null
+++ b/src/azure/Templates/PageTemplate.cshtml
@@ -0,0 +1,77 @@
+@using System.Linq
+@using AutoRest.Java
+@inherits AutoRest.Core.Template
+/**
+@Header(" * ").TrimMultilineHeader()
+ */
+@EmptyLine
+
+package @(Settings.Namespace.ToLower()).@(Model.ModelsPackage);
+@EmptyLine
+@foreach (var importClass in Model.ImportList)
+{
+@:import @importClass;
+}
+@EmptyLine
+
+/**
+ * An instance of this class defines a page of Azure resources and a link to
+ * get the next page of resources, if any.
+ *
+ * @@param type of Azure resource
+ */
+public class @Model.TypeDefinitionName implements Page {
+ /**
+ * The link to the next page.
+ */
+ @@JsonProperty("@Model.NextLinkName")
+ private String nextPageLink;
+ @EmptyLine
+ /**
+ * The list of items.
+ */
+ @@JsonProperty("@Model.ItemName")
+ private List items;
+ @EmptyLine
+ /**
+ * Gets the link to the next page.
+ *
+ * @@return the link to the next page.
+ */
+ @@Override
+ public String nextPageLink() {
+ return this.nextPageLink;
+ }
+ @EmptyLine
+ /**
+ * Gets the list of items.
+ *
+ * @@return the list of items in {@@link List}.
+ */
+ @@Override
+ public List items() {
+ return items;
+ }
+ @EmptyLine
+ /**
+ * Sets the link to the next page.
+ *
+ * @@param nextPageLink the link to the next page.
+ * @@return this Page object itself.
+ */
+ public @Model.TypeDefinitionName setNextPageLink(String nextPageLink) {
+ this.nextPageLink = nextPageLink;
+ return this;
+ }
+ @EmptyLine
+ /**
+ * Sets the list of items.
+ *
+ * @@param items the list of items in {@@link List}.
+ * @@return this Page object itself.
+ */
+ public @Model.TypeDefinitionName setItems(List items) {
+ this.items = items;
+ return this;
+ }
+}
diff --git a/src/azure/Templates/PagingMethodTemplate.cshtml b/src/azure/Templates/PagingMethodTemplate.cshtml
new file mode 100644
index 0000000000..07f62c1bbc
--- /dev/null
+++ b/src/azure/Templates/PagingMethodTemplate.cshtml
@@ -0,0 +1,460 @@
+@using System.Linq;
+@using AutoRest.Core.Model
+@using AutoRest.Core.Utilities
+@using AutoRest.Java
+@using AutoRest.Java.Model
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+@if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired))
+{
+
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@throws @Model.OperationExceptionTypeString thrown if the request is rejected by server
+ * @@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object if successful.
+}
+ */
+public @Model.ReturnTypeResponseName @(Model.Name)(@Model.MethodRequiredParameterDeclaration) {
+ @Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped response = @(Model.Name)SinglePageAsync(@Model.MethodRequiredParameterInvocation).toBlocking().single();
+ return new @(Model.ReturnTypeJva.GenericBodyClientTypeString)(response.body()) {
+ @@Override
+ public @Model.ReturnTypeJva.ServiceResponseGenericParameterString nextPage(String @Model.PagingNextPageLinkParameterName) {
+ @Model.PagingGroupedParameterTransformation(true)
+ return @(Model.GetPagingNextMethodInvocation(true))(@Model.NextMethodParameterInvocation(true)).toBlocking().single().body();
+ }
+ };
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJva.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCallback) {
+ return AzureServiceFuture.@(Model.ServiceFutureFactoryMethod)(
+ @(Model.Name)SinglePageAsync(@Model.MethodRequiredParameterInvocation),
+ new Func1>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(String @Model.PagingNextPageLinkParameterName) {
+ @Model.PagingGroupedParameterTransformation(true)
+ return @(Model.GetPagingNextMethodInvocation(true))(@Model.NextMethodParameterInvocation(true));
+ }
+ },
+ serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeResponseName.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterString> @(Model.Name)Async(@Model.MethodRequiredParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation)
+ .map(new Func1<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, @Model.ReturnTypeJva.ServiceResponseGenericParameterString>() {
+ @@Override
+ public @Model.ReturnTypeJva.ServiceResponseGenericParameterString call(@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped response) {
+ return response.body();
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeResponseName.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterDeclaration) {
+ return @(Model.Name)SinglePageAsync(@Model.MethodRequiredParameterInvocation)
+ .concatMap(new Func1<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped>>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped page) {
+ String @Model.PagingNextPageLinkParameterName = page.body().nextPageLink();
+ if (@Model.PagingNextPageLinkParameterName == null) {
+ return Observable.just(page);
+ }
+ @Model.PagingGroupedParameterTransformation(true)
+ return Observable.just(page).concatWith(@(Model.GetPagingNextMethodInvocation(true, false))(@Model.NextMethodParameterInvocation(true)));
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeJva.ClientResponseType} if successful.
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> @(Model.Name)SinglePageAsync(@Model.MethodRequiredParameterDeclaration) {
+ @foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate.Where(p => p.IsRequired))
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (!parameter.IsRequired)
+ {
+@: final @(parameter.ClientType.Name) @(parameter.Name) = @(parameter.ClientType.GetDefaultValue(Model) ?? "null");
+ }
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ClientType.ParameterVariant.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+
+ }
+}
+ @Model.BuildInputMappings(true)
+
+@if (Model.IsParameterizedHost)
+{
+@: String parameterizedHost = Joiner.on(", ").join(@Model.HostParameterReplacementArgs);
+}
+ @Model.ParameterConversion
+@if (Model.IsPagingNextOperation)
+{
+@: String nextUrl = @(Model.NextUrlConstruction);
+}
+ return service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation)
+ .flatMap(new Func1, Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped>>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(Response<@Model.CallType> response) {
+ try {
+ @Model.ReturnTypeJva.GenericBodyWireTypeStringWrapped result = @(Model.Name)Delegate(response);
+ return Observable.just(@(Model.ReturnTypeJva.ServiceResponseCreation(Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, "result.body()", "result")));
+ } catch (Throwable t) {
+ return Observable.error(t);
+ }
+ }
+ });
+}
+@EmptyLine
+
+}
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@throws @Model.OperationExceptionTypeString thrown if the request is rejected by server
+ * @@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object if successful.
+}
+ */
+public @Model.ReturnTypeResponseName @(Model.Name)(@Model.MethodParameterDeclaration) {
+ @Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped response = @(Model.Name)SinglePageAsync(@Model.MethodParameterInvocation).toBlocking().single();
+ return new @(Model.ReturnTypeJva.GenericBodyClientTypeString)(response.body()) {
+ @@Override
+ public @Model.ReturnTypeJva.ServiceResponseGenericParameterString nextPage(String @Model.PagingNextPageLinkParameterName) {
+ @Model.PagingGroupedParameterTransformation()
+ return @(Model.GetPagingNextMethodInvocation(true))(@Model.NextMethodParameterInvocation()).toBlocking().single().body();
+ }
+ };
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJva.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallback) {
+ return AzureServiceFuture.@(Model.ServiceFutureFactoryMethod)(
+ @(Model.Name)SinglePageAsync(@Model.MethodParameterInvocation),
+ new Func1>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(String @Model.PagingNextPageLinkParameterName) {
+ @Model.PagingGroupedParameterTransformation()
+ return @(Model.GetPagingNextMethodInvocation(true))(@Model.NextMethodParameterInvocation());
+ }
+ },
+ serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeResponseName.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterString> @(Model.Name)Async(@Model.MethodParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation)
+ .map(new Func1<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, @Model.ReturnTypeJva.ServiceResponseGenericParameterString>() {
+ @@Override
+ public @Model.ReturnTypeJva.ServiceResponseGenericParameterString call(@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped response) {
+ return response.body();
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeResponseName.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterDeclaration) {
+ return @(Model.Name)SinglePageAsync(@Model.MethodParameterInvocation)
+ .concatMap(new Func1<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped>>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped page) {
+ String @Model.PagingNextPageLinkParameterName = page.body().nextPageLink();
+ if (@Model.PagingNextPageLinkParameterName == null) {
+ return Observable.just(page);
+ }
+ @Model.PagingGroupedParameterTransformation()
+ return Observable.just(page).concatWith(@(Model.GetPagingNextMethodInvocation(true, false))(@Model.NextMethodParameterInvocation()));
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+ @Model.ReturnTypeJva.GenericBodyWireTypeStringWrapped
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+ * @@throws IllegalArgumentException thrown if parameters fail the validation
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the @Model.ReturnTypeResponseName.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeJva.ClientResponseType} if successful.
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJva.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> @(Model.Name)SinglePageAsync(@Model.MethodParameterDeclaration) {
+ @foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate)
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ModelType.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+ }
+}
+ @Model.BuildInputMappings()
+
+@if (Model.IsParameterizedHost)
+{
+@: String parameterizedHost = Joiner.on(", ").join(@Model.HostParameterReplacementArgs);
+}
+ @Model.ParameterConversion
+@if (Model.IsPagingNextOperation)
+{
+@: String nextUrl = @(Model.NextUrlConstruction);
+}
+ return service.@(Model.Name)(@Model.MethodParameterApiInvocation)
+ .flatMap(new Func1, Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped>>() {
+ @@Override
+ public Observable<@Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped> call(Response<@Model.CallType> response) {
+ try {
+ @Model.ReturnTypeJva.GenericBodyWireTypeStringWrapped result = @(Model.Name)Delegate(response);
+ return Observable.just(@(Model.ReturnTypeJva.ServiceResponseCreation(Model.ReturnTypeJva.ServiceResponseGenericParameterStringWrapped, "result.body()", "result")));
+ } catch (Throwable t) {
+ return Observable.error(t);
+ }
+ }
+ });
+}
+@EmptyLine
+private @Model.ReturnTypeJva.WireResponseTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString {
+ return @(Model.ClientReference).restClient().responseBuilderFactory().<@Model.ReturnTypeJva.GenericBodyWireTypeString, @Model.OperationExceptionTypeString>newInstance(@(Model.ClientReference).serializerAdapter())
+@foreach (var response in Model.Responses)
+{
+
+ @:.register(@((int)response.Key), new TypeToken<@((response.Value as ResponseJva).GenericBodyWireTypeString)>() { }.getType())
+}
+@if (Model.DefaultResponse.Body != null)
+{
+ @:.registerError(@(Model.OperationExceptionTypeString).class)
+}
+@if (Model.HttpMethod == HttpMethod.Head)
+{
+ if (Model.ReturnType.Headers != null)
+ {
+ @:.buildEmptyWithHeaders(response, @(Model.ReturnType.Headers.Name).class);
+ }
+ else
+ {
+ @:.buildEmpty(response);
+ }
+}
+else
+{
+ if (Model.ReturnType.Headers != null)
+ {
+ @:.buildWithHeaders(response, @(Model.ReturnType.Headers.Name).class);
+ }
+ else
+ {
+ @:.build(response);
+ }
+}
+}
\ No newline at end of file
diff --git a/src/azure/Templates/SimulatedPageMethodTemplate.cshtml b/src/azure/Templates/SimulatedPageMethodTemplate.cshtml
new file mode 100644
index 0000000000..b5c4254544
--- /dev/null
+++ b/src/azure/Templates/SimulatedPageMethodTemplate.cshtml
@@ -0,0 +1,347 @@
+@using System.Linq;
+@using AutoRest.Core.Model
+@using AutoRest.Core.Utilities
+@using AutoRest.Java
+@using AutoRest.Java.Model
+@using AutoRest.Java.Azure.Model
+@inherits AutoRest.Core.Template
+@if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired))
+{
+
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the PagedList<@Model.ReturnTypeJv.SequenceElementTypeString> object if successful.
+}
+ */
+public PagedList<@Model.ReturnTypeJv.SequenceElementTypeString> @(Model.Name)(@Model.MethodRequiredParameterDeclaration) {
+ @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<@Model.ReturnTypeJv.SequenceElementTypeString> page = new @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<>();
+ page.setItems(@(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation).toBlocking().single().body());
+ page.setNextPageLink(null);
+ return new PagedList<@Model.ReturnTypeJv.SequenceElementTypeString>(page) {
+ @@Override
+ public Page<@Model.ReturnTypeJv.SequenceElementTypeString> nextPage(String nextPageLink) {
+ return null;
+ }
+ };
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJv.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCallback) {
+ return ServiceFuture.@(Model.ServiceFutureFactoryMethod)(@(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation), serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeJv.GenericBodyClientTypeString.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJv.ClientResponseType} object if successful.
+}
+ */
+public Observable> @(Model.Name)Async(@Model.MethodRequiredParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterInvocation).map(new Func1<@Model.ReturnTypeJv.ClientResponseTypeString, Page<@Model.ReturnTypeJv.SequenceElementTypeString>>() {
+ @@Override
+ public Page<@Model.ReturnTypeJv.SequenceElementTypeString> call(@Model.ReturnTypeJv.ClientResponseTypeString response) {
+ @Model.ReturnTypeJv.GenericBodyWireTypeString page = new @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<>();
+ page.setItems(response.body());
+ return page;
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeJv.GenericBodyClientTypeString.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJv.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJv.ClientResponseTypeString> @(Model.Name)WithServiceResponseAsync(@Model.MethodRequiredParameterDeclaration) {
+@foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate.Where(p => p.IsRequired))
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (!parameter.IsRequired)
+ {
+@: final @(parameter.ClientType.Name) @(parameter.Name) = @(parameter.ClientType.GetDefaultValue(Model) ?? "null");
+ }
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ClientType.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+
+ }
+}
+ @Model.BuildInputMappings(true)
+
+@if (Model.IsParameterizedHost)
+{
+@: String parameterizedHost = Joiner.on(", ").join(@Model.HostParameterReplacementArgs);
+}
+ @Model.ParameterConversion
+ return service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation)
+ .flatMap(new Func1, Observable<@(Model.ReturnTypeJv.ClientResponseTypeString)>>() {
+ @@Override
+ public Observable<@(Model.ReturnTypeJv.ClientResponseTypeString)> call(Response<@Model.CallType> response) {
+ try {
+ @Model.ClientResponse()
+ return Observable.just(clientResponse);
+ } catch (Throwable t) {
+ return Observable.error(t);
+ }
+ }
+ });
+}
+@EmptyLine
+
+}
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the PagedList<@Model.ReturnTypeJv.SequenceElementTypeString> object if successful.
+}
+ */
+public PagedList<@Model.ReturnTypeJv.SequenceElementTypeString> @(Model.Name)(@Model.MethodParameterDeclaration) {
+ @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<@Model.ReturnTypeJv.SequenceElementTypeString> page = new @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<>();
+ page.setItems(@(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation).toBlocking().single().body());
+ page.setNextPageLink(null);
+ return new PagedList<@Model.ReturnTypeJv.SequenceElementTypeString>(page) {
+ @@Override
+ public Page<@Model.ReturnTypeJv.SequenceElementTypeString> nextPage(String nextPageLink) {
+ return null;
+ }
+ };
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@Model.CallbackDocumentation
+ * @@return the {@@link ServiceFuture} object
+ */
+public ServiceFuture<@Model.ReturnTypeJv.ServiceFutureGenericParameterString> @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallback) {
+ return ServiceFuture.@(Model.ServiceFutureFactoryMethod)(@(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation), serviceCallback);
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeJv.GenericBodyClientTypeString.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJv.ClientResponseType} object if successful.
+}
+ */
+public Observable> @(Model.Name)Async(@Model.MethodParameterDeclaration) {
+ return @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterInvocation).map(new Func1<@Model.ReturnTypeJv.ClientResponseTypeString, Page<@Model.ReturnTypeJv.SequenceElementTypeString>>() {
+ @@Override
+ public Page<@Model.ReturnTypeJv.SequenceElementTypeString> call(@Model.ReturnTypeJv.ClientResponseTypeString response) {
+ @Model.ReturnTypeJv.GenericBodyWireTypeString page = new @((Model.ReturnTypeJv.BodyClientType as SequenceTypeJva).PageImplType)<>();
+ page.setItems(response.body());
+ return page;
+ }
+ });
+}
+@EmptyLine
+/**
+@if (!string.IsNullOrEmpty(Model.Summary))
+{
+@: * @Model.Summary.EscapeXmlComment().Period()
+}
+@if (!string.IsNullOrEmpty(Model.Description))
+{
+@: * @Model.Description.EscapeXmlComment().Period()
+}
+ *
+@foreach (var param in Model.LocalParameters.Where(p => !p.IsConstant))
+{
+@: * @@param @param.Name @(param.Documentation.Else("the " + param.ModelType.Name + " value").EscapeXmlComment().Trim())
+}
+@if (Model.ReturnType.Body != null)
+{
+@: * @@return the observable to the @Model.ReturnTypeJv.GenericBodyClientTypeString.EscapeXmlComment() object
+}
+else
+{
+@: * @@return the {@@link @Model.ReturnTypeJv.ClientResponseType} object if successful.
+}
+ */
+public Observable<@Model.ReturnTypeJv.ClientResponseTypeString> @(Model.Name)WithServiceResponseAsync(@Model.MethodParameterDeclaration) {
+@foreach (var param in Model.RequiredNullableParameters)
+{
+@: if (@param.Name == null) {
+@: throw new IllegalArgumentException("Parameter @param.Name is required and cannot be null.");
+@: }
+}
+@foreach (var param in Model.ParametersToValidate)
+{
+@: Validator.validate(@(param.Name));
+}
+@foreach (ParameterJv parameter in Model.LocalParameters)
+{
+ if (parameter.IsConstant)
+ {
+@: final @(parameter.ModelType.Name) @(parameter.Name) = @(parameter.DefaultValue ?? "null");
+ }
+}
+ @Model.BuildInputMappings()
+
+@if (Model.IsParameterizedHost)
+{
+@: String parameterizedHost = Joiner.on(", ").join(@Model.HostParameterReplacementArgs);
+}
+ @Model.ParameterConversion
+ return service.@(Model.Name)(@Model.MethodParameterApiInvocation)
+ .flatMap(new Func1, Observable<@(Model.ReturnTypeJv.ClientResponseTypeString)>>() {
+ @@Override
+ public Observable<@(Model.ReturnTypeJv.ClientResponseTypeString)> call(Response<@Model.CallType> response) {
+ try {
+ @Model.ClientResponse()
+ return Observable.just(clientResponse);
+ } catch (Throwable t) {
+ return Observable.error(t);
+ }
+ }
+ });
+}
+@EmptyLine
+private @Model.ReturnTypeJv.WireResponseTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString {
+ return @(Model.ClientReference).restClient().responseBuilderFactory().<@Model.ReturnTypeJv.GenericBodyWireTypeString, @Model.OperationExceptionTypeString>newInstance(@(Model.ClientReference).serializerAdapter())
+@foreach (var response in Model.Responses)
+{
+
+ @:.register(@((int)response.Key), new TypeToken<@((response.Value as ResponseJv).GenericBodyWireTypeString)>() { }.getType())
+}
+@if (Model.DefaultResponse.Body != null)
+{
+ @:.registerError(@(Model.OperationExceptionTypeString).class)
+}
+@if (Model.HttpMethod == HttpMethod.Head)
+{
+ if (Model.ReturnType.Headers != null)
+ {
+ @:.buildEmptyWithHeaders(response, @(Model.ReturnType.Headers.Name).class);
+ }
+ else
+ {
+ @:.buildEmpty(response);
+ }
+}
+else
+{
+ if (Model.ReturnType.Headers != null)
+ {
+ @:.buildWithHeaders(response, @(Model.ReturnType.Headers.Name).class);
+ }
+ else
+ {
+ @:.build(response);
+ }
+}
+}
diff --git a/src/azure/TransformerJva.cs b/src/azure/TransformerJva.cs
new file mode 100644
index 0000000000..fb427bd2a6
--- /dev/null
+++ b/src/azure/TransformerJva.cs
@@ -0,0 +1,296 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Newtonsoft.Json.Linq;
+using AutoRest.Core;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Utilities.Collections;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java.Azure
+{
+ public class TransformerJva : TransformerJv, ITransformer
+ {
+ ///
+ /// A type-specific method for code model tranformation.
+ /// Note: This is the method you want to override.
+ ///
+ ///
+ ///
+ public override CodeModelJv TransformCodeModel(CodeModel cm)
+ {
+ var codeModel = cm as CodeModelJva;
+
+ // we're guaranteed to be in our language-specific context here.
+ Settings.Instance.AddCredentials = true;
+
+ // This extension from general extensions must be run prior to Azure specific extensions.
+ AzureExtensions.ProcessParameterizedHost(codeModel);
+ AzureExtensions.ProcessClientRequestIdExtension(codeModel);
+ AzureExtensions.UpdateHeadMethods(codeModel);
+ AzureExtensions.ProcessGlobalParameters(codeModel);
+ AzureExtensions.FlattenModels(codeModel);
+ AzureExtensions.FlattenMethodParameters(codeModel);
+ ParameterGroupExtensionHelper.AddParameterGroups(codeModel);
+ AddLongRunningOperations(codeModel);
+ AzureExtensions.AddAzureProperties(codeModel);
+ AzureExtensions.SetDefaultResponses(codeModel);
+
+ // set Parent on responses (required for pageable)
+ foreach (MethodJva method in codeModel.Methods)
+ {
+ foreach (ResponseJva response in method.Responses.Values)
+ {
+ response.Parent = method;
+ }
+ (method.DefaultResponse as ResponseJva).Parent = method;
+ method.ReturnTypeJva.Parent = method;
+ }
+ AzureExtensions.AddPageableMethod(codeModel);
+
+ // pluralize method groups
+ foreach (var mg in codeModel.Operations)
+ {
+ mg.Name.OnGet += name => name.IsNullOrEmpty() || name.EndsWith("s", StringComparison.OrdinalIgnoreCase) ? name : $"{name}s";
+ }
+
+ NormalizePaginatedMethods(codeModel, codeModel.pageClasses);
+
+ // param order (PATH first)
+ foreach (MethodJva method in codeModel.Methods)
+ {
+ var ps = method.Parameters.ToList();
+ method.ClearParameters();
+ foreach (var p in ps.Where(x => x.Location == ParameterLocation.Path))
+ {
+ method.Add(p);
+ }
+ foreach (var p in ps.Where(x => x.Location != ParameterLocation.Path))
+ {
+ method.Add(p);
+ }
+ }
+
+ return codeModel;
+ }
+
+ public static void AddLongRunningOperations(CodeModel codeModel)
+ {
+ if (codeModel == null)
+ {
+ throw new ArgumentNullException("codeModel");
+ }
+
+ foreach (var operation in codeModel.Operations)
+ {
+ var methods = operation.Methods.ToArray();
+ operation.ClearMethods();
+ foreach (var method in methods)
+ {
+ operation.Add(method);
+ if (true == method.Extensions.Get(AzureExtensions.LongRunningExtension))
+ {
+ // copy the method
+ var m = Duplicate(method);
+
+ // change the name, remove the extension.
+ m.Name = "Begin" + m.Name.ToPascalCase();
+ m.Extensions.Remove(AzureExtensions.LongRunningExtension);
+
+ operation.Add(m);
+ }
+ }
+ }
+ }
+
+
+ CodeModelJva ITransformer.TransformCodeModel(CodeModel codeModel)
+ {
+ return this.TransformCodeModel(codeModel) as CodeModelJva;
+ }
+
+ ///
+ /// Changes paginated method signatures to return Page type.
+ ///
+ ///
+ ///
+ public void NormalizePaginatedMethods(CodeModel serviceClient, IDictionary, string> pageClasses)
+ {
+ if (serviceClient == null)
+ {
+ throw new ArgumentNullException("serviceClient");
+ }
+
+ var convertedTypes = new Dictionary();
+
+ foreach (MethodJva method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension) || (m as MethodJva).SimulateAsPagingOperation))
+ {
+ string nextLinkString;
+ string pageClassName = GetPagingSetting(method.Extensions, pageClasses, method.SimulateAsPagingOperation, out nextLinkString);
+ if (string.IsNullOrEmpty(pageClassName))
+ {
+ continue;
+ }
+ if (string.IsNullOrEmpty(nextLinkString))
+ {
+ method.Extensions[AzureExtensions.PageableExtension] = null;
+ }
+ bool anyTypeConverted = false;
+ foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeTypeJva).Select(s => s.Key).ToArray())
+ {
+ anyTypeConverted = true;
+ var compositeType = (CompositeTypeJva)method.Responses[responseStatus].Body;
+ var sequenceType = compositeType.Properties.Select(p => p.ModelType).FirstOrDefault(t => t is SequenceTypeJva) as SequenceTypeJva;
+
+ // if the type is a wrapper over page-able response
+ if (sequenceType != null)
+ {
+ IModelType pagedResult;
+ pagedResult = new SequenceTypeJva
+ {
+ ElementType = sequenceType.ElementType,
+ PageImplType = pageClassName
+ };
+
+ convertedTypes[method.Responses[responseStatus].Body] = pagedResult;
+ var resp = New(pagedResult, method.Responses[responseStatus].Headers) as ResponseJva;
+ resp.Parent = method;
+ method.Responses[responseStatus] = resp;
+ }
+ }
+
+ if (!anyTypeConverted && method.SimulateAsPagingOperation)
+ {
+ foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is SequenceTypeJva).Select(s => s.Key).ToArray())
+ {
+ var sequenceType = (SequenceTypeJva)method.Responses[responseStatus].Body;
+
+ IModelType pagedResult;
+ pagedResult = new SequenceTypeJva
+ {
+ ElementType = sequenceType.ElementType,
+ PageImplType = pageClassName
+ };
+
+ convertedTypes[method.Responses[responseStatus].Body] = pagedResult;
+ var resp = New(pagedResult, method.Responses[responseStatus].Headers) as ResponseJva;
+ resp.Parent = method;
+ method.Responses[responseStatus] = resp;
+ }
+ }
+
+ if (convertedTypes.ContainsKey(method.ReturnType.Body))
+ {
+ var resp = New(convertedTypes[method.ReturnType.Body], method.ReturnType.Headers) as ResponseJva;
+ resp.Parent = method;
+ method.ReturnType = resp;
+ }
+ }
+
+ SwaggerExtensions.RemoveUnreferencedTypes(serviceClient,
+ new HashSet(convertedTypes.Keys.Where(x => x is CompositeTypeJva).Cast().Select(t => t.Name.ToString())));
+ }
+
+ public virtual void NormalizeODataMethods(CodeModel client)
+ {
+ if (client == null)
+ {
+ throw new ArgumentNullException("client");
+ }
+
+ foreach (var method in client.Methods)
+ {
+ if (method.Extensions.ContainsKey(AzureExtensions.ODataExtension))
+ {
+ var odataFilter = method.Parameters.FirstOrDefault(p =>
+ p.SerializedName.EqualsIgnoreCase("$filter") &&
+ (p.Location == ParameterLocation.Query) &&
+ p.ModelType is CompositeType);
+
+ if (odataFilter == null)
+ {
+ continue;
+ }
+
+ // Remove all odata parameters
+ method.Remove(source =>
+ (source.SerializedName.EqualsIgnoreCase("$filter") ||
+ source.SerializedName.EqualsIgnoreCase("$top") ||
+ source.SerializedName.EqualsIgnoreCase("$orderby") ||
+ source.SerializedName.EqualsIgnoreCase("$skip") ||
+ source.SerializedName.EqualsIgnoreCase("$expand"))
+ && (source.Location == ParameterLocation.Query));
+
+ var odataQuery = New(new
+ {
+ SerializedName = "$filter",
+ Name = "odataQuery",
+ ModelType = New($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"),
+ Documentation = "OData parameters to apply to the operation.",
+ Location = ParameterLocation.Query,
+ odataFilter.IsRequired
+ });
+ odataQuery.Extensions[AzureExtensions.ODataExtension] =
+ method.Extensions[AzureExtensions.ODataExtension];
+ method.Insert(odataQuery);
+ }
+ }
+ }
+
+ private static string GetPagingSetting(Dictionary extensions,
+ IDictionary, string> pageClasses, bool simulatingPaging, out string nextLinkName)
+ {
+ // default value
+ nextLinkName = null;
+ var itemName = "value";
+ string className = null;
+
+ if (extensions.ContainsKey(AzureExtensions.PageableExtension))
+ {
+ var ext = extensions[AzureExtensions.PageableExtension] as JContainer;
+
+ if (ext == null)
+ {
+ return null;
+ }
+
+ nextLinkName = (string)ext["nextLinkName"];
+ itemName = (string)ext["itemName"] ?? "value";
+ className = (string)ext["className"];
+ }
+ else if (!simulatingPaging)
+ {
+ return null;
+ }
+
+ var keypair = new KeyValuePair(nextLinkName, itemName);
+ if (!pageClasses.ContainsKey(keypair))
+ {
+ if (string.IsNullOrWhiteSpace(className))
+ {
+ if (pageClasses.Count > 0)
+ {
+ className = $"PageImpl{pageClasses.Count}";
+ }
+ else
+ {
+ className = "PageImpl";
+ }
+ }
+ pageClasses.Add(keypair, className);
+ }
+
+ return pageClasses[keypair];
+ }
+ }
+}
diff --git a/src/azurefluent/CodeGeneratorJvaf.cs b/src/azurefluent/CodeGeneratorJvaf.cs
new file mode 100644
index 0000000000..9c218afeef
--- /dev/null
+++ b/src/azurefluent/CodeGeneratorJvaf.cs
@@ -0,0 +1,114 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using AutoRest.Core;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Fluent.Model;
+using AutoRest.Java.azure.Templates;
+using AutoRest.Java.Model;
+using AutoRest.Java.vanilla.Templates;
+using System;
+
+namespace AutoRest.Java.Azure.Fluent
+{
+ public class CodeGeneratorJvaf : CodeGeneratorJva
+ {
+ private const string ClientRuntimePackage = "com.microsoft.azure:azure-client-runtime:1.0.0-beta6-SNAPSHOT";
+ private const string _packageInfoFileName = "package-info.java";
+
+ public override bool IsSingleFileGenerationSupported => true;
+
+ public override string UsageInstructions => $"The {ClientRuntimePackage} maven dependency is required to execute the generated code.";
+
+ ///
+ /// Generates C# code for service client.
+ ///
+ ///
+ ///
+ public override async Task Generate(CodeModel cm)
+ {
+ // get Azure Java specific codeModel
+ var codeModel = cm as CodeModelJvaf;
+ if (codeModel == null)
+ {
+ throw new InvalidCastException("CodeModel is not a Azure Java Fluent CodeModel");
+ }
+
+ // Service client
+ var serviceClientTemplate = new AzureServiceClientTemplate { Model = codeModel };
+ await Write(serviceClientTemplate, $"{Path.Combine("implementation", codeModel.Name.ToPascalCase() + "Impl")}{ImplementationFileExtension}");
+
+ // operations
+ foreach (MethodGroupJvaf methodGroup in codeModel.AllOperations)
+ {
+ // Operation
+ var operationsTemplate = new AzureMethodGroupTemplate { Model = methodGroup };
+ await Write(operationsTemplate, $"{Path.Combine("implementation", methodGroup.TypeName.ToPascalCase())}Inner{ImplementationFileExtension}");
+ }
+
+ //Models
+ foreach (CompositeTypeJvaf modelType in cm.ModelTypes.Concat(codeModel.HeaderTypes))
+ {
+ if (modelType.Extensions.ContainsKey(AzureExtensions.ExternalExtension) &&
+ (bool)modelType.Extensions[AzureExtensions.ExternalExtension])
+ {
+ continue;
+ }
+ if (modelType.IsResource)
+ {
+ continue;
+ }
+
+ var modelTemplate = new ModelTemplate { Model = modelType };
+ await Write(modelTemplate, Path.Combine(modelType.ModelsPackage.Trim('.'), $"{modelType.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ //Enums
+ foreach (EnumTypeJvaf enumType in cm.EnumTypes)
+ {
+ var enumTemplate = new EnumTemplate { Model = enumType };
+ await Write(enumTemplate, Path.Combine(enumType.ModelsPackage.Trim('.'), $"{enumTemplate.Model.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Page class
+ foreach (var pageClass in codeModel.pageClasses)
+ {
+ var pageTemplate = new PageTemplate
+ {
+ Model = new PageJvaf(pageClass.Value, pageClass.Key.Key, pageClass.Key.Value),
+ };
+ await Write(pageTemplate, Path.Combine("implementation", $"{pageTemplate.Model.TypeDefinitionName.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Exceptions
+ foreach (CompositeTypeJv exceptionType in codeModel.ErrorTypes)
+ {
+ if (exceptionType.Name == "CloudError")
+ {
+ continue;
+ }
+
+ var exceptionTemplate = new ExceptionTemplate { Model = exceptionType };
+ await Write(exceptionTemplate, Path.Combine(exceptionType.ModelsPackage.Trim('.'), $"{exceptionTemplate.Model.ExceptionTypeDefinitionName}{ImplementationFileExtension}"));
+ }
+
+ // package-info.java
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm)
+ }, _packageInfoFileName);
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm, "implementation")
+ }, Path.Combine("implementation", _packageInfoFileName));
+ }
+ }
+}
diff --git a/src/azurefluent/GlobalSuppressions.cs b/src/azurefluent/GlobalSuppressions.cs
new file mode 100644
index 0000000000..31eeaabf7f
--- /dev/null
+++ b/src/azurefluent/GlobalSuppressions.cs
@@ -0,0 +1,27 @@
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureJavaFluentCodeGenerator.#.ctor(AutoRest.Core.Settings)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureJavaFluentCodeNamer.#NormalizeTopLevelTypes(AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodGroupTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#.ctor(AutoRest.Core.ClientModel.Method,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#TransformPagingGroupedParameter(AutoRest.Core.Utilities.IndentedStringBuilder,AutoRest.Java.Azure.AzureMethodTemplateModel,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentMethodTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentModelTemplateModel.#.ctor(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentServiceClientTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.AzureFluentServiceClientTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "AutoRest.Java")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.FluentCompositeTypeModel.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.Azure.Fluent.FluentCompositeTypeModel.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.FluentEnumTypeModel.#.ctor(AutoRest.Core.ClientModel.EnumType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.FluentEnumTypeModel.#.ctor(AutoRest.Core.ClientModel.EnumType,System.String)")]
+// This file is used by Code Analysis to maintain SuppressMessage
+// attributes that are applied to this project.
+// Project-level suppressions either have no target or are given
+// a specific target and scoped to a namespace, type, member, etc.
+//
+// To add a suppression to this file, right-click the message in the
+// Code Analysis results, point to "Suppress Message", and click
+// "In Suppression File".
+// You do not need to add suppressions to this file manually.
diff --git a/src/azurefluent/Model/CodeModelJvaf.cs b/src/azurefluent/Model/CodeModelJvaf.cs
new file mode 100644
index 0000000000..ba6483b490
--- /dev/null
+++ b/src/azurefluent/Model/CodeModelJvaf.cs
@@ -0,0 +1,77 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class CodeModelJvaf : CodeModelJva
+ {
+ [JsonIgnore]
+ public override string ImplPackage
+ {
+ get
+ {
+ return "implementation";
+ }
+ }
+
+ [JsonIgnore]
+ public override string ParentDeclaration
+ {
+ get
+ {
+ return " extends AzureServiceClient";
+ }
+ }
+
+ [JsonIgnore]
+ public override List InterfaceImports
+ {
+ get
+ {
+ var imports = base.InterfaceImports;
+ imports.Add("com.microsoft.azure.AzureClient");
+ return imports.OrderBy(i => i).ToList();
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable ImplImports
+ {
+ get
+ {
+ var imports = new List();
+ var ns = Namespace.ToLowerInvariant();
+ foreach (var i in base.ImplImports.ToList())
+ {
+ if (i.StartsWith(ns + "." + ImplPackage, StringComparison.OrdinalIgnoreCase))
+ {
+ // Same package, do nothing
+ }
+ else if (Operations.Any(m => i.EndsWith(m.TypeName, StringComparison.OrdinalIgnoreCase)))
+ {
+ // do nothing
+ }
+ else if (i.EndsWith(this.Name, StringComparison.OrdinalIgnoreCase))
+ {
+ // do nothing
+ }
+ else
+ {
+ imports.Add(i);
+ }
+ }
+ return imports.OrderBy(i => i).ToList();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azurefluent/Model/CompositeTypeJvaf.cs b/src/azurefluent/Model/CompositeTypeJvaf.cs
new file mode 100644
index 0000000000..d8122f4610
--- /dev/null
+++ b/src/azurefluent/Model/CompositeTypeJvaf.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Globalization;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Azure.Model;
+using System.Collections.Generic;
+using System.Linq;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class CompositeTypeJvaf : CompositeTypeJva
+ {
+ public CompositeTypeJvaf()
+ {
+ Name.OnGet += nam => nam.IsNullOrEmpty() || !IsInnerModel ? nam : nam + "Inner";
+ }
+
+ public CompositeTypeJvaf(string name) : base(name)
+ {
+ Name.OnGet += nam => nam.IsNullOrEmpty() || !IsInnerModel ? nam : nam + "Inner";
+ }
+
+ public override IEnumerableWithIndex Properties
+ {
+ get
+ {
+ var res = base.Properties;
+ res.OfType().ForEach(p => p.IsInnerModel = IsInnerModel);
+ return res;
+ }
+ }
+
+ [JsonIgnore]
+ public override string Package
+ {
+ get
+ {
+ if (this.IsResource)
+ {
+ return _azureRuntimePackage;
+ }
+ else if (Extensions.ContainsKey(ExternalExtension) &&
+ (bool)Extensions[ExternalExtension])
+ {
+ return _runtimePackage;
+ }
+ else if (Name.ToString().EndsWith("Inner", StringComparison.Ordinal))
+ {
+ return (CodeModel?.Namespace.ToLowerInvariant()) + ".implementation";
+ }
+ else
+ {
+ return (CodeModel?.Namespace.ToLowerInvariant());
+ }
+ }
+ }
+
+
+ [JsonIgnore]
+ public override string ModelsPackage => IsInnerModel ? ".implementation" : "";
+
+ public bool IsInnerModel { get; set; } = false;
+
+ [JsonIgnore]
+ public override IEnumerable Imports
+ {
+ get
+ {
+ var imports = new List();
+ if (Name.Contains('<'))
+ {
+ imports.AddRange(ParseGenericType().SelectMany(t => t.Imports));
+ }
+ else
+ {
+ imports.Add(string.Join(".", Package, Name));
+ }
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public override IEnumerable ImportList
+ {
+ get
+ {
+ List imports = base.ImportList.ToList();
+ if (BaseModelType != null && BaseModelType.Name.ToString().EndsWith("Inner", StringComparison.Ordinal) ^ IsInnerModel)
+ {
+ imports.AddRange(BaseModelType.ImportSafe());
+ }
+ return imports.Distinct();
+ }
+ }
+ }
+}
diff --git a/src/azurefluent/Model/EnumTypeJvaf.cs b/src/azurefluent/Model/EnumTypeJvaf.cs
new file mode 100644
index 0000000000..249658d76b
--- /dev/null
+++ b/src/azurefluent/Model/EnumTypeJvaf.cs
@@ -0,0 +1,33 @@
+using System.Collections.Generic;
+using System.Globalization;
+using AutoRest.Java.Azure.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class EnumTypeJvaf : EnumTypeJva
+ {
+ [JsonIgnore]
+ public override IEnumerable Imports
+ {
+ get
+ {
+ if (Name != "String")
+ {
+ yield return string.Join(".",
+ (CodeModel?.Namespace.ToLowerInvariant()) + (Name.ToString().EndsWith("Inner") ? ".implementation" : ""),
+ Name);
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public override string ModelsPackage
+ {
+ get
+ {
+ return "";
+ }
+ }
+ }
+}
diff --git a/src/azurefluent/Model/MethodGroupJvaf.cs b/src/azurefluent/Model/MethodGroupJvaf.cs
new file mode 100644
index 0000000000..de9e8fc697
--- /dev/null
+++ b/src/azurefluent/Model/MethodGroupJvaf.cs
@@ -0,0 +1,137 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Java.Azure.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class MethodGroupJvaf : MethodGroupJva
+ {
+ private List supportedInterfaces = new List();
+ private List interfacesToImport = new List();
+
+ public MethodGroupJvaf()
+ {
+ }
+ public MethodGroupJvaf(string name) : base(name)
+ {
+ }
+
+ [JsonIgnore]
+ public override string MethodGroupDeclarationType => MethodGroupImplType;
+
+ [JsonIgnore]
+ public override string ImplClassSuffix => "Inner";
+
+ [JsonIgnore]
+ public override string ParentDeclaration
+ {
+ get
+ {
+ DiscoverAllSupportedInterfaces();
+
+ if (supportedInterfaces.Count() > 0)
+ {
+ return $" implements {string.Join(", ", supportedInterfaces)}";
+ }
+
+ return "";
+ }
+ }
+
+ [JsonIgnore]
+ public override string ServiceClientType => CodeModel.Name + "Impl";
+
+ [JsonIgnore]
+ public override string ImplPackage => "implementation";
+
+ [JsonIgnore]
+ public override IEnumerable ImplImports
+ {
+ get
+ {
+ DiscoverAllSupportedInterfaces();
+ var imports = new List();
+ var ns = CodeModel.Namespace.ToLowerInvariant();
+ foreach (var interfaceToImport in interfacesToImport)
+ {
+ imports.Add(interfaceToImport);
+ }
+ foreach (var i in base.ImplImports.ToList())
+ {
+ if (i.StartsWith(ns + "." + ImplPackage, StringComparison.OrdinalIgnoreCase))
+ {
+ // Same package, do nothing
+ }
+ else if (i == ns + "." + this.TypeName)
+ {
+ // do nothing
+ }
+ else
+ {
+ imports.Add(i);
+ }
+ }
+ return imports;
+ }
+ }
+
+ private bool AnyMethodSupportsInnerListing()
+ {
+ var listMethod = this.Methods.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, WellKnowMethodNames.List));
+ var listByResourceGroup = this.Methods.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, WellKnowMethodNames.ListByResourceGroup));
+ return listMethod != null && listByResourceGroup != null
+ && StringComparer.OrdinalIgnoreCase.Equals(
+ ((ResponseJva)listMethod.ReturnType).SequenceElementTypeString,
+ ((ResponseJva)listByResourceGroup.ReturnType).SequenceElementTypeString);
+ }
+
+ private void DiscoverAllSupportedInterfaces()
+ {
+ const string InnerSupportsGet = "InnerSupportsGet";
+ const string InnerSupportsDelete = "InnerSupportsDelete";
+ const string InnerSupportsListing = "InnerSupportsListing";
+
+ // In case this method has already discovered the interfaces to be implemented, we don't need to do anything again.
+ if (supportedInterfaces.Count() > 0)
+ {
+ return;
+ }
+
+ const string packageName = "com.microsoft.azure.management.resources.fluentcore.collection";
+ var getMethod = this.Methods.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, WellKnowMethodNames.GetByResourceGroup));
+ if (getMethod != null && Take2RequiredParameters(getMethod))
+ {
+ supportedInterfaces.Add($"{InnerSupportsGet}<{((ResponseJva)getMethod.ReturnType).GenericBodyClientTypeString}>");
+ interfacesToImport.Add($"{packageName}.{InnerSupportsGet}");
+ }
+
+ var deleteMethod = this.Methods.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, WellKnowMethodNames.Delete));
+ if (deleteMethod != null && Take2RequiredParameters(deleteMethod))
+ {
+ supportedInterfaces.Add($"{InnerSupportsDelete}<{((ResponseJva)deleteMethod.ReturnType).ClientCallbackTypeString}>");
+ interfacesToImport.Add($"{packageName}.{InnerSupportsDelete}");
+ }
+
+ if (AnyMethodSupportsInnerListing())
+ {
+ // Getting list method to get the name of the type to be supported.
+ var listMethod = this.Methods.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, WellKnowMethodNames.List));
+
+ supportedInterfaces.Add($"{InnerSupportsListing}<{((ResponseJva)listMethod.ReturnType).SequenceElementTypeString}>");
+ interfacesToImport.Add($"{packageName}.{InnerSupportsListing}");
+ }
+ }
+
+ private static bool Take2RequiredParameters(Method method)
+ {
+ // When parameters are optional we generate more methods.
+ return method.Parameters.Count(x => !x.IsClientProperty && !x.IsConstant && x.IsRequired) == 2;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azurefluent/Model/MethodJvaf.cs b/src/azurefluent/Model/MethodJvaf.cs
new file mode 100644
index 0000000000..db6ea8d569
--- /dev/null
+++ b/src/azurefluent/Model/MethodJvaf.cs
@@ -0,0 +1,285 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using AutoRest.Core;
+using Newtonsoft.Json;
+using System;
+using AutoRest.Core.Utilities.Collections;
+using System.Text.RegularExpressions;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class MethodJvaf : MethodJva
+ {
+ public override void Disambiguate()
+ {
+ if (string.IsNullOrWhiteSpace(this.MethodGroup.Name))
+ {
+ base.Disambiguate();
+
+ return;
+ }
+
+ var methodType = GetMethodType(this);
+ var originalName = Name;
+
+ if (methodType != MethodType.Other)
+ {
+ string newName = null;
+
+ if (this.MethodGroup.Methods.Count(x => GetMethodType(x as MethodJvaf) == methodType) == 1)
+ {
+ switch (methodType)
+ {
+ case MethodType.ListBySubscription:
+ newName = WellKnowMethodNames.List;
+ break;
+
+ case MethodType.ListByResourceGroup:
+ newName = WellKnowMethodNames.ListByResourceGroup;
+ break;
+
+ case MethodType.Delete:
+ newName = WellKnowMethodNames.Delete;
+ break;
+
+ case MethodType.Get:
+ newName = WellKnowMethodNames.GetByResourceGroup;
+ break;
+
+ default:
+ throw new Exception("Flow should not hit this statement.");
+ }
+ }
+ if (!string.IsNullOrWhiteSpace(newName))
+ {
+ if (methodType == MethodType.ListByResourceGroup || methodType == MethodType.ListBySubscription)
+ {
+ this.SimulateAsPagingOperation = true;
+ }
+
+ var name = CodeNamer.Instance.GetUnique(newName, this, Parent.IdentifiersInScope, Parent.Children.Except(this.SingleItemAsEnumerable()));
+ if (name != originalName)
+ {
+ Name = name;
+ }
+ return;
+ }
+ }
+
+ base.Disambiguate();
+ }
+
+ [JsonIgnore]
+ public override IEnumerable RetrofitParameters
+ {
+ get
+ {
+ List parameters = base.RetrofitParameters.ToList();
+
+ parameters.First(p => p.SerializedName == "User-Agent")
+ .ClientProperty = new PropertyJvaf
+ {
+ Name = "userAgent"
+ };
+ return parameters;
+ }
+ }
+
+ protected override void TransformPagingGroupedParameter(IndentedStringBuilder builder, MethodJva nextMethod, bool filterRequired = false)
+ {
+ if (this.InputParameterTransformation.IsNullOrEmpty() || nextMethod.InputParameterTransformation.IsNullOrEmpty())
+ {
+ return;
+ }
+ var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
+ if (nextGroupType.Name == groupedType.Name)
+ {
+ return;
+ }
+ var nextGroupTypeName = CodeNamer.Instance.GetTypeName(nextGroupType.Name) + "Inner";
+ if (filterRequired && !groupedType.IsRequired)
+ {
+ return;
+ }
+ if (!groupedType.IsRequired)
+ {
+ builder.AppendLine("{0} {1} = null;", nextGroupTypeName, nextGroupType.Name.ToCamelCase());
+ builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase());
+ builder.Indent();
+ builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
+ }
+ else
+ {
+ builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
+ }
+ foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter))
+ {
+ builder.AppendLine("{0}.with{1}({2}.{3}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase(), outParam.Name.ToCamelCase());
+ }
+ if (!groupedType.IsRequired)
+ {
+ builder.Outdent().AppendLine(@"}");
+ }
+ }
+
+ [JsonIgnore]
+ public override List InterfaceImports
+ {
+ get
+ {
+ var imports = base.InterfaceImports;
+ if (this.IsPagingOperation || this.IsPagingNextOperation || this.SimulateAsPagingOperation)
+ {
+ imports.Add("com.microsoft.azure.PagedList");
+
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ imports.Add("com.microsoft.azure.ListOperationCallback");
+ }
+
+ if (!this.SimulateAsPagingOperation)
+ {
+ imports.Remove("com.microsoft.rest.ServiceCallback");
+ }
+
+ var pageType = ReturnTypeJva.BodyClientType as SequenceTypeJva;
+ if (pageType != null)
+ {
+ imports.AddRange(new CompositeTypeJvaf(pageType.PageImplType).ImportSafe());
+ }
+ }
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public override List ImplImports
+ {
+ get
+ {
+ var pageType = ReturnTypeJva.BodyClientType as SequenceTypeJva;
+
+ var imports = base.ImplImports;
+ if (OperationExceptionTypeString != "CloudException" && OperationExceptionTypeString != "RestException")
+ {
+ imports.RemoveAll(i => new CompositeTypeJva(OperationExceptionTypeString) { CodeModel = CodeModel }.ImportSafe().Contains(i));
+ imports.AddRange(new CompositeTypeJvaf(OperationExceptionTypeString) { CodeModel = CodeModel }.ImportSafe());
+ }
+ if (this.IsLongRunningOperation)
+ {
+ imports.Remove("com.microsoft.azure.AzureResponseBuilder");
+ this.Responses.Select(r => r.Value.Body).Concat(new IModelType[]{ DefaultResponse.Body })
+ .SelectMany(t => t.ImportSafe())
+ .Where(i => !this.Parameters.Any(p => p.ModelType.ImportSafe().Contains(i)))
+ .ForEach(i => imports.Remove(i));
+ // return type may have been removed as a side effect
+ imports.AddRange(this.ReturnTypeJva.ImplImports);
+ }
+ imports = imports.Distinct().ToList();
+ if (this.IsPagingOperation || this.IsPagingNextOperation || SimulateAsPagingOperation)
+ {
+ imports.Add("com.microsoft.azure.PagedList");
+
+ if (this.IsPagingOperation || this.IsPagingNextOperation)
+ {
+ imports.Add("com.microsoft.azure.ListOperationCallback");
+ }
+
+ if (!this.SimulateAsPagingOperation)
+ {
+ imports.Remove("com.microsoft.rest.ServiceCallback");
+ }
+
+ imports.Remove("java.util.ArrayList");
+ imports.Add("com.microsoft.azure.Page");
+ if (pageType != null)
+ {
+ imports.RemoveAll(i => new CompositeTypeJva((ReturnTypeJva.BodyClientType as SequenceTypeJva).PageImplType) { CodeModel = CodeModel }.ImportSafe().Contains(i));
+ }
+ }
+
+ if (this.IsPagingNonPollingOperation && pageType != null)
+ {
+ imports.RemoveAll(i => new CompositeTypeJva((ReturnTypeJva.BodyClientType as SequenceTypeJva).PageImplType) { CodeModel = CodeModel }.ImportSafe().Contains(i));
+ }
+ return imports;
+ }
+ }
+
+ private enum MethodType
+ {
+ Other,
+ ListBySubscription,
+ ListByResourceGroup,
+ Get,
+ Delete
+ }
+
+ private static MethodType GetMethodType(MethodJvaf method)
+ {
+ Regex leading = new Regex("^/+");
+ Regex trailing = new Regex("/+$");
+ var methodUrl = trailing.Replace(leading.Replace(method.Url, ""), "");
+ if (method.HttpMethod == HttpMethod.Get)
+ {
+ var urlSplits = methodUrl.Split('/');
+ if ((urlSplits.Count() == 5 || urlSplits.Count() == 7)
+ && StringComparer.OrdinalIgnoreCase.Equals(urlSplits[0], "subscriptions")
+ && method.ReturnType.Body is SequenceType)
+ {
+ if (urlSplits.Count() == 5)
+ {
+ if (StringComparer.OrdinalIgnoreCase.Equals(urlSplits[2], "providers"))
+ {
+ return MethodType.ListBySubscription;
+ }
+ else
+ {
+ return MethodType.ListByResourceGroup;
+ }
+ }
+ else if (StringComparer.OrdinalIgnoreCase.Equals(urlSplits[2], "resourceGroups"))
+ {
+ return MethodType.ListByResourceGroup;
+ }
+ }
+ if (IsTopLevelResourceUrl(methodUrl))
+ {
+ return MethodType.Get;
+ }
+ }
+ else if (method.HttpMethod == HttpMethod.Delete)
+ {
+ if (method.Name.Value.ToLowerInvariant().StartsWith("begin")
+ || method.MethodGroup.Methods.Count(x => x.HttpMethod == HttpMethod.Delete) > 1)
+ {
+ return MethodType.Other;
+ }
+
+ if (IsTopLevelResourceUrl(methodUrl))
+ {
+ return MethodType.Delete;
+ }
+ }
+
+ return MethodType.Other;
+ }
+
+ private static bool IsTopLevelResourceUrl(string url)
+ {
+ var urlSplits = url.Split('/');
+
+ return urlSplits.Count() == 8 && StringComparer.OrdinalIgnoreCase.Equals(urlSplits[0], "subscriptions")
+ && StringComparer.OrdinalIgnoreCase.Equals(urlSplits[2], "resourceGroups")
+ && StringComparer.OrdinalIgnoreCase.Equals(urlSplits[4], "providers");
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azurefluent/Model/PageJvaf.cs b/src/azurefluent/Model/PageJvaf.cs
new file mode 100644
index 0000000000..f35bfe7ee4
--- /dev/null
+++ b/src/azurefluent/Model/PageJvaf.cs
@@ -0,0 +1,24 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using AutoRest.Java.Azure.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class PageJvaf : PageJva
+ {
+ public PageJvaf(string typeDefinitionName, string nextLinkName, string itemName)
+ : base(typeDefinitionName, nextLinkName, itemName) {
+ }
+
+ [JsonIgnore]
+ public override string ModelsPackage
+ {
+ get
+ {
+ return "implementation";
+ }
+ }
+ }
+}
diff --git a/src/azurefluent/Model/PropertyJvaf.cs b/src/azurefluent/Model/PropertyJvaf.cs
new file mode 100644
index 0000000000..cfb5910755
--- /dev/null
+++ b/src/azurefluent/Model/PropertyJvaf.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Azure.Fluent.Model
+{
+ public class PropertyJvaf : PropertyJv
+ {
+ public bool IsInnerModel { get; set; } = false;
+
+ [JsonIgnore]
+ public override IEnumerable Imports
+ {
+ get
+ {
+ var imports = new List(ModelType.ImportSafe()
+ .Where(c => !c.StartsWith(Parent.CodeModel?.Namespace.ToLowerInvariant(), StringComparison.Ordinal) ||
+ c.EndsWith("Inner", StringComparison.Ordinal) ^ IsInnerModel));
+ if (ModelType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
+ {
+ imports.AddRange(ModelType.ImportSafe());
+ imports.AddRange((ModelType as IModelTypeJv).ResponseVariant.ImportSafe());
+ }
+ return imports;
+ }
+ }
+ }
+}
diff --git a/src/azurefluent/PluginJvaf.cs b/src/azurefluent/PluginJvaf.cs
new file mode 100644
index 0000000000..5545581468
--- /dev/null
+++ b/src/azurefluent/PluginJvaf.cs
@@ -0,0 +1,41 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+//
+
+using AutoRest.Core;
+using AutoRest.Core.Extensibility;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Azure.Fluent;
+using AutoRest.Java.Azure.Fluent.Model;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java.Azure
+{
+ public sealed class PluginJvaf : Plugin
+ {
+ public PluginJvaf()
+ {
+ Context = new Context
+ {
+ // inherit base settings
+ Context,
+
+ // set code model implementations our own implementations
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory(),
+ new Factory()
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/azurefluent/TransformerJvaf.cs b/src/azurefluent/TransformerJvaf.cs
new file mode 100644
index 0000000000..9ad154596b
--- /dev/null
+++ b/src/azurefluent/TransformerJvaf.cs
@@ -0,0 +1,131 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Newtonsoft.Json.Linq;
+using AutoRest.Core;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Utilities.Collections;
+using AutoRest.Extensions;
+using AutoRest.Extensions.Azure;
+using AutoRest.Java.Azure.Model;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+using AutoRest.Java.Azure.Fluent.Model;
+
+namespace AutoRest.Java.Azure
+{
+ public class TransformerJvaf : TransformerJva, ITransformer
+ {
+ public override CodeModelJv TransformCodeModel(CodeModel cm)
+ {
+ var codeModel = cm as CodeModelJva;
+
+ // we're guaranteed to be in our language-specific context here.
+ Settings.Instance.AddCredentials = true;
+
+ // This extension from general extensions must be run prior to Azure specific extensions.
+ AzureExtensions.ProcessParameterizedHost(codeModel);
+ AzureExtensions.ProcessClientRequestIdExtension(codeModel);
+ AzureExtensions.UpdateHeadMethods(codeModel);
+ AzureExtensions.ProcessGlobalParameters(codeModel);
+ AzureExtensions.FlattenModels(codeModel);
+ AzureExtensions.FlattenMethodParameters(codeModel);
+ ParameterGroupExtensionHelper.AddParameterGroups(codeModel);
+ AddLongRunningOperations(codeModel);
+ AzureExtensions.AddAzureProperties(codeModel);
+ AzureExtensions.SetDefaultResponses(codeModel);
+
+ // set Parent on responses (required for pageable)
+ foreach (MethodJva method in codeModel.Methods)
+ {
+ foreach (ResponseJva response in method.Responses.Values)
+ {
+ response.Parent = method;
+ }
+ (method.DefaultResponse as ResponseJva).Parent = method;
+ method.ReturnTypeJva.Parent = method;
+ }
+ AzureExtensions.AddPageableMethod(codeModel);
+
+ // pluralize method groups
+ foreach (var mg in codeModel.Operations)
+ {
+ mg.Name.OnGet += name => name.IsNullOrEmpty() || name.EndsWith("s", StringComparison.OrdinalIgnoreCase) ? $"{name}" : $"{name}s";
+ }
+
+ NormalizePaginatedMethods(codeModel, codeModel.pageClasses);
+
+ // determine inner models
+ NormalizeTopLevelTypes(codeModel);
+
+ // param order (PATH first)
+ foreach (MethodJva method in codeModel.Methods)
+ {
+ var ps = method.Parameters.ToList();
+ method.ClearParameters();
+ foreach (var p in ps.Where(x => x.Location == ParameterLocation.Path))
+ {
+ method.Add(p);
+ }
+ foreach (var p in ps.Where(x => x.Location != ParameterLocation.Path))
+ {
+ method.Add(p);
+ }
+ }
+
+ return codeModel;
+ }
+
+ CodeModelJvaf ITransformer.TransformCodeModel(CodeModel cm)
+ {
+ return TransformCodeModel(cm) as CodeModelJvaf;
+ }
+
+ public void NormalizeTopLevelTypes(CodeModel serviceClient)
+ {
+ foreach (var param in serviceClient.Methods.SelectMany(m => m.Parameters))
+ {
+ AppendInnerToTopLevelType(param.ModelType, serviceClient);
+ }
+ foreach (var response in serviceClient.Methods.SelectMany(m => m.Responses).Select(r => r.Value))
+ {
+ AppendInnerToTopLevelType(response.Body, serviceClient);
+ AppendInnerToTopLevelType(response.Headers, serviceClient);
+ }
+ foreach (var model in serviceClient.ModelTypes)
+ {
+ if (model.BaseModelType != null && (model.BaseModelType.Name == "Resource" || model.BaseModelType.Name == "SubResource"))
+ AppendInnerToTopLevelType(model, serviceClient);
+ }
+ }
+
+ private void AppendInnerToTopLevelType(IModelType type, CodeModel serviceClient)
+ {
+ if (type == null)
+ {
+ return;
+ }
+ CompositeTypeJvaf compositeType = type as CompositeTypeJvaf;
+ SequenceType sequenceType = type as SequenceType;
+ DictionaryType dictionaryType = type as DictionaryType;
+ if (compositeType != null && !compositeType.IsResource)
+ {
+ compositeType.IsInnerModel = true;
+ }
+ else if (sequenceType != null)
+ {
+ AppendInnerToTopLevelType(sequenceType.ElementType, serviceClient);
+ }
+ else if (dictionaryType != null)
+ {
+ AppendInnerToTopLevelType(dictionaryType.ValueType, serviceClient);
+ }
+ }
+ }
+}
diff --git a/src/azurefluent/WellKnowMethodNames.cs b/src/azurefluent/WellKnowMethodNames.cs
new file mode 100644
index 0000000000..ecd9138396
--- /dev/null
+++ b/src/azurefluent/WellKnowMethodNames.cs
@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace AutoRest.Java.Azure.Fluent
+{
+ class WellKnowMethodNames
+ {
+ public const string GetByResourceGroup = "GetByResourceGroup";
+ public const string ListByResourceGroup = "ListByResourceGroup";
+ public const string List = "List";
+ public const string Delete = "Delete";
+
+ }
+}
diff --git a/src/vanilla/ClientModelExtensions.cs b/src/vanilla/ClientModelExtensions.cs
new file mode 100644
index 0000000000..d33c71ca40
--- /dev/null
+++ b/src/vanilla/ClientModelExtensions.cs
@@ -0,0 +1,105 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using AutoRest.Core.Model;
+using AutoRest.Java.Model;
+
+namespace AutoRest.Java
+{
+ public static class ClientModelExtensions
+ {
+ public const string ExternalExtension = "x-ms-external";
+
+ public static string Period(this string documentation)
+ {
+ if (string.IsNullOrEmpty(documentation))
+ {
+ return documentation;
+ }
+ documentation = documentation.Trim();
+ if (!documentation.EndsWith(".", StringComparison.Ordinal))
+ {
+ documentation += ".";
+ }
+ return documentation;
+ }
+
+ public static string TrimMultilineHeader(this string header)
+ {
+ if (string.IsNullOrEmpty(header))
+ {
+ return header;
+ }
+ StringBuilder builder = new StringBuilder();
+ foreach (var headerLine in header.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
+ {
+ builder.Append(headerLine.TrimEnd()).Append(Environment.NewLine);
+ }
+ return builder.ToString();
+ }
+
+ public static string GetJsonProperty(this Property property)
+ {
+ if (property == null)
+ {
+ return null;
+ }
+
+ List settings = new List();
+ settings.Add(string.Format(CultureInfo.InvariantCulture, "value = \"{0}\"", property.SerializedName));
+ if (property.IsRequired)
+ {
+ settings.Add("required = true");
+ }
+ if (property.IsReadOnly)
+ {
+ settings.Add("access = JsonProperty.Access.WRITE_ONLY");
+ }
+ return string.Join(", ", settings);
+ }
+
+ public static void AddRange(this HashSet hashSet, IEnumerable range)
+ {
+ if( hashSet == null || range == null)
+ {
+ return;
+ }
+
+ foreach(var item in range)
+ {
+ hashSet.Add(item);
+ }
+ }
+
+ ///
+ /// A null friendly wrapper around type imports.
+ ///
+ /// an instance of IJavaType
+ /// a list of imports to append
+ public static IEnumerable ImportSafe(this IModelType type)
+ {
+ if (type == null)
+ {
+ return new List();
+ }
+ return ((IModelTypeJv) type).Imports;
+ }
+
+ public static string ImportFrom(this HttpMethod httpMethod)
+ {
+ string package = "retrofit2.http.";
+ if (httpMethod == HttpMethod.Delete)
+ {
+ return package + "HTTP";
+ }
+ else
+ {
+ return package + httpMethod.ToString().ToUpperInvariant();
+ }
+ }
+ }
+}
diff --git a/src/vanilla/CodeGeneratorJv.cs b/src/vanilla/CodeGeneratorJv.cs
new file mode 100644
index 0000000000..4dd1f76843
--- /dev/null
+++ b/src/vanilla/CodeGeneratorJv.cs
@@ -0,0 +1,99 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using AutoRest.Core;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Java.vanilla.Templates;
+using AutoRest.Java.Model;
+using AutoRest.Core.Model;
+using System;
+
+namespace AutoRest.Java
+{
+ public class CodeGeneratorJv : CodeGenerator
+ {
+ private const string ClientRuntimePackage = "com.microsoft.rest:client-runtime:1.0.0-beta6-SNAPSHOT from snapshot repo https://oss.sonatype.org/content/repositories/snapshots/";
+ private const string _packageInfoFileName = "package-info.java";
+
+ public CodeNamerJv Namer { get; private set; }
+
+ public override string UsageInstructions => $"The {ClientRuntimePackage} maven dependency is required to execute the generated code.";
+
+ public override string ImplementationFileExtension => ".java";
+
+ ///
+ /// Generate Java client code for given ServiceClient.
+ ///
+ ///
+ ///
+ public override async Task Generate(CodeModel cm)
+ {
+ // get Java specific codeModel
+ var codeModel = cm as CodeModelJv;
+ if (codeModel == null)
+ {
+ throw new InvalidCastException("CodeModel is not a Java CodeModel");
+ }
+
+ // Service client
+ var serviceClientTemplate = new ServiceClientTemplate { Model = codeModel };
+ await Write(serviceClientTemplate, $"{Path.Combine("implementation", cm.Name.ToPascalCase() + "Impl")}{ImplementationFileExtension}");
+
+ // Service client interface
+ var serviceClientInterfaceTemplate = new ServiceClientInterfaceTemplate { Model = codeModel };
+ await Write(serviceClientInterfaceTemplate, $"{cm.Name.ToPascalCase()}{ImplementationFileExtension}");
+
+ // operations
+ foreach (MethodGroupJv methodGroup in codeModel.AllOperations)
+ {
+ // Operation
+ var operationsTemplate = new MethodGroupTemplate { Model = methodGroup };
+ await Write(operationsTemplate, $"{Path.Combine("implementation", methodGroup.TypeName.ToPascalCase())}Impl{ImplementationFileExtension}");
+
+ // Operation interface
+ var operationsInterfaceTemplate = new MethodGroupInterfaceTemplate { Model = methodGroup };
+ await Write(operationsInterfaceTemplate, $"{methodGroup.TypeName.ToPascalCase()}{ImplementationFileExtension}");
+ }
+
+ //Models
+ foreach (CompositeTypeJv modelType in cm.ModelTypes.Union(codeModel.HeaderTypes))
+ {
+ var modelTemplate = new ModelTemplate { Model = modelType };
+ await Write(modelTemplate, Path.Combine("models", $"{modelType.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Enums
+ foreach (EnumTypeJv enumType in cm.EnumTypes)
+ {
+ var enumTemplate = new EnumTemplate { Model = enumType };
+ await Write(enumTemplate, Path.Combine("models", $"{enumTemplate.Model.Name.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // Exceptions
+ foreach (CompositeTypeJv exceptionType in codeModel.ErrorTypes)
+ {
+ var exceptionTemplate = new ExceptionTemplate { Model = exceptionType };
+ await Write(exceptionTemplate, Path.Combine("models", $"{exceptionTemplate.Model.ExceptionTypeDefinitionName.ToPascalCase()}{ImplementationFileExtension}"));
+ }
+
+ // package-info.java
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm)
+ }, _packageInfoFileName);
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm, "implementation")
+ }, Path.Combine("implementation", _packageInfoFileName));
+ await Write(new PackageInfoTemplate
+ {
+ Model = new PackageInfoTemplateModel(cm, "models")
+ }, Path.Combine("models", _packageInfoFileName));
+ }
+ }
+}
diff --git a/src/vanilla/CodeNamerJv.cs b/src/vanilla/CodeNamerJv.cs
new file mode 100644
index 0000000000..8f6b6c2778
--- /dev/null
+++ b/src/vanilla/CodeNamerJv.cs
@@ -0,0 +1,237 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text.RegularExpressions;
+using AutoRest.Core;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Core.Model;
+using AutoRest.Java.Model;
+
+namespace AutoRest.Java
+{
+ public class CodeNamerJv : CodeNamer
+ {
+ private Dictionary _visited = new Dictionary();
+
+ public static HashSet PrimaryTypes { get; private set; }
+
+ #region constructor
+
+ ///
+ /// Initializes a new instance of CSharpCodeNamingFramework.
+ ///
+ public CodeNamerJv()
+ {
+ // List retrieved from
+ // http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
+ ReservedWords.AddRange(new []
+ {
+ "abstract", "assert", "boolean", "break", "byte",
+ "case", "catch", "char", "class", "const",
+ "continue", "default", "do", "double", "else",
+ "enum", "extends", "false", "final", "finally",
+ "float", "for", "goto", "if", "implements",
+ "import", "int", "long", "interface","instanceof",
+ "native", "new", "null", "package", "private",
+ "protected","public", "return", "short", "static",
+ "strictfp", "super", "switch", "synchronized","this",
+ "throw", "throws", "transient","true", "try",
+ "void", "volatile", "while", "date", "datetime",
+ "period", "stream", "string", "object", "header"
+ });
+
+ PrimaryTypes = new HashSet();
+ new HashSet
+ {
+ "int", "Integer",
+ "long", "Long",
+ "object", "Object",
+ "bool", "Boolean",
+ "double", "Double",
+ "float", "Float",
+ "byte", "Byte",
+ "byte[]", "Byte[]",
+ "String",
+ "LocalDate",
+ "DateTime",
+ "DateTimeRfc1123",
+ "Duration",
+ "Period",
+ "BigDecimal",
+ "InputStream"
+ }.ForEach(s => PrimaryTypes.Add(s));
+ new HashSet
+ {
+ "int",
+ "long",
+ "bool",
+ "double",
+ "float",
+ "byte",
+ "byte[]"
+ }.ForEach(s => PrimaryTypes.Add(s));
+ }
+
+ #endregion
+
+ #region naming
+
+ public override string GetFieldName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ return '_' + GetVariableName(name);
+ }
+
+ public override string GetPropertyName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property")));
+ }
+
+ public override string GetMethodName(string name)
+ {
+ name = GetEscapedReservedName(name, "Method");
+ return CamelCase(name);
+ }
+
+ public override string GetMethodGroupName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ name = PascalCase(name);
+ if (!name.EndsWith("s", StringComparison.OrdinalIgnoreCase))
+ {
+ name += "s";
+ }
+ return name;
+ }
+
+ public override string GetEnumMemberName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ string result = RemoveInvalidCharacters(new Regex("[\\ -]+").Replace(name, "_"));
+ Func isUpper = new Func(c => c >= 'A' && c <= 'Z');
+ Func isLower = new Func(c => c >= 'a' && c <= 'z');
+ for (int i = 1; i < result.Length - 1; i++)
+ {
+ if (isUpper(result[i]))
+ {
+ if (result[i - 1] != '_' && isLower(result[i - 1]))
+ {
+ result = result.Insert(i, "_");
+ }
+ }
+ }
+ return result.ToUpperInvariant();
+ }
+
+ public override string GetParameterName(string name)
+ {
+ return base.GetParameterName(GetEscapedReservedName(name, "Parameter"));
+ }
+
+ public override string GetVariableName(string name)
+ {
+ return base.GetVariableName(GetEscapedReservedName(name, "Variable"));
+ }
+
+ public static string GetServiceName(string name)
+ {
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ return name;
+ }
+ return name + "Service";
+ }
+
+ #endregion
+
+ #region type handling
+
+ public static string GetJavaException(string exception, CodeModel cm)
+ {
+ switch (exception) {
+ case "IOException":
+ return "java.io.IOException";
+ case "CloudException":
+ return "com.microsoft.azure.CloudException";
+ case "RestException":
+ return "com.microsoft.rest.RestException";
+ case "IllegalArgumentException":
+ return null;
+ case "InterruptedException":
+ return null;
+ default:
+ return (cm.Namespace.ToLowerInvariant())
+ + ".models." + exception;
+ }
+ }
+
+ #endregion
+
+ public override string EscapeDefaultValue(string defaultValue, IModelType type)
+ {
+ if (type == null)
+ {
+ throw new ArgumentNullException("type");
+ }
+
+ var primaryType = type as PrimaryType;
+ if (defaultValue != null && primaryType != null)
+ {
+ if (primaryType.KnownPrimaryType == KnownPrimaryType.Double)
+ {
+ return double.Parse(defaultValue).ToString();
+ }
+ if (primaryType.KnownPrimaryType == KnownPrimaryType.String)
+ {
+ return QuoteValue(defaultValue);
+ }
+ else if (primaryType.KnownPrimaryType == KnownPrimaryType.Boolean)
+ {
+ return defaultValue.ToLowerInvariant();
+ }
+ else if (primaryType.KnownPrimaryType == KnownPrimaryType.Long)
+ {
+ return defaultValue + "L";
+ }
+ else
+ {
+ if (primaryType.KnownPrimaryType == KnownPrimaryType.Date)
+ {
+ return "LocalDate.parse(\"" + defaultValue + "\")";
+ }
+ else if (primaryType.KnownPrimaryType == KnownPrimaryType.DateTime ||
+ primaryType.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
+ {
+ return "DateTime.parse(\"" + defaultValue + "\")";
+ }
+ else if (primaryType.KnownPrimaryType == KnownPrimaryType.TimeSpan)
+ {
+ return "Period.parse(\"" + defaultValue + "\")";
+ }
+ else if (primaryType.KnownPrimaryType == KnownPrimaryType.ByteArray)
+ {
+ return "\"" + defaultValue + "\".getBytes()";
+ }
+ }
+ }
+ return defaultValue;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/GlobalSuppressions.cs b/src/vanilla/GlobalSuppressions.cs
new file mode 100644
index 0000000000..28705d884d
--- /dev/null
+++ b/src/vanilla/GlobalSuppressions.cs
@@ -0,0 +1,195 @@
+// This file is used by Code Analysis to maintain SuppressMessage
+// attributes that are applied to this project.
+// Project-level suppressions either have no target or are given
+// a specific target and scoped to a namespace, type, member, etc.
+//
+// To add a suppression to this file, right-click the message in the
+// Code Analysis results, point to "Suppress Message", and click
+// "In Suppression File".
+// You do not need to add suppressions to this file manually.
+
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member",
+ Target = "AutoRest.Java.ServiceClientTemplateModel.#ModelTemplateModels", Justification="Using another type would add unneeded complexity")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member",
+ Target = "AutoRest.Java.MethodGroupTemplateModel.#MethodTemplateModels", Justification="Using another type would add unneeded complexity")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#ParameterTemplateModels", Justification="Using another type would add unneeded complexity")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member",
+ Target = "AutoRest.Java.ServiceClientTemplateModel.#MethodTemplateModels", Justification="Using another type would add unneeded complexity")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes",
+ Scope = "namespace", Target = "AutoRest.Java.TemplateModels", Justification = "Parallel with other generators")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed",
+ Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Code simplification")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed",
+ Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#DeserializeType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Code simplification")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed",
+ Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#GetDeserializationString(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
+ MessageId = "0#", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#RemoveDuplicateForwardSlashes(System.String)", Justification="Uri will not pass uri validation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",
+ Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#BuildUrl(System.String)", Justification="Uri will not pass uri validation")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods",
+ MessageId = "1", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#.ctor(AutoRest.Core.ClientModel.Method,AutoRest.Core.ClientModel.ServiceClient)", Justification="Validated by LoadFrom method")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods",
+ MessageId = "0", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#.ctor(AutoRest.Core.ClientModel.Method,AutoRest.Core.ClientModel.ServiceClient)", Justification="Validated by LoadFrom method")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods",
+ MessageId = "0", Scope = "member",
+ Target = "AutoRest.Java.ModelTemplateModel.#.ctor(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.ClientModel.ServiceClient)", Justification="Validated by LoadFrom method")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#DeserializeType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateRequiredType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#GetDeserializationString(AutoRest.Core.ClientModel.IType,System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.ServiceClientTemplateModel.#PolymorphicDictionary", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#BuildUrl(System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization",
+ "CA1303:Do not pass literals as localized parameters",
+ MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member",
+ Target = "AutoRest.Java.MethodTemplateModel.#RemoveDuplicateForwardSlashes(System.String)", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.ServiceClientTemplateModel.#PolymorphicDictionary", Justification="Literal string is generated code, no localization concerns")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase",
+ Scope = "member",
+ Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.String)", Justification="Node conventions require lower casing")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
+ Scope = "member",
+ Target = "AutoRest.Java.ModelTemplateModel.#isSpecial(AutoRest.Core.ClientModel.IType)", Justification="False Positive")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
+ MessageId = "gi", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#RemoveDuplicateForwardSlashes(System.String)", Justification="Generated code parameters to regular expression")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#AddQueryParametersToUrl(System.String,AutoRest.Core.Utilities.IndentedStringBuilder)", Justification="Literal string is generated code, no localization concerns.")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#BuildQueryParameterArray(AutoRest.Core.Utilities.IndentedStringBuilder)", Justification="Literal string is generated code, no localization concerns.")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "QueryParameters", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#HasQueryParameters()", Justification="False Positive")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "ms-rest", Scope = "resource", Target = "AutoRest.Java.Properties.Resources.resources", Justification="ms-rest is a valid npm package name")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "isArray", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "util", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateType(AutoRest.Core.ClientModel.IType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ConstructValidationCheck(System.String,System.String,System.String,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ConstructValidationCheck(System.String,System.String,System.String,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "instanceof", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "valueOf", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "typeof", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateDictionaryType(AutoRest.Core.ClientModel.DictionaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateDictionaryType(AutoRest.Core.ClientModel.DictionaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateSequenceType(AutoRest.Core.ClientModel.SequenceType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateSequenceType(AutoRest.Core.ClientModel.SequenceType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateCompositeType(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateCompositeType(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateEnumType(AutoRest.Core.ClientModel.EnumType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateEnumType(AutoRest.Core.ClientModel.EnumType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "isNaN", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "isNaN", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "valueOf", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "typeof", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "instanceof", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(AutoRest.Core.ClientModel.PrimaryType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateEnumType(AutoRest.Core.ClientModel.EnumType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ValidateEnumType(AutoRest.Core.ClientModel.EnumType,AutoRest.Core.Utilities.IScopeProvider,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.ServiceClientTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.ServiceClientTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#TypeImports(System.Collections.Generic.IList`1)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#TypeImports(System.Collections.Generic.IList`1,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ImportFrom(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ImportFrom(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ImportFrom(AutoRest.Core.ClientModel.Parameter,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ImplImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.ServiceClientTemplateModel.#InterfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ImportFrom(AutoRest.Core.ClientModel.Parameter)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ExceptionStatements")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.PackageInfoTemplateModel.#.ctor(AutoRest.Core.ClientModel.ServiceClient,System.String,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#GetJavaException(System.String,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#GetJavaException(System.String,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#QuoteString(System.String,AutoRest.Core.ClientModel.IType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#EscapeDefaultValue(System.String,AutoRest.Core.ClientModel.IType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#BuildInputMappings()")]
+
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.TemplateModels.ClientModelExtensions.#ImportFrom(AutoRest.Core.ClientModel.IType,System.String,AutoRest.Java.JavaCodeNamer)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#ImportType(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#ImportType(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getDateTime", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DateTime", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getDateTime", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DateTime", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.ResponseModel.#converToClientType(AutoRest.Core.ClientModel.IType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.CompositeTypeModel.#_package")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.CompositeTypeModel.#_runtimePackage")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.CompositeTypeModel.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.CompositeTypeModel.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.EnumTypeModel.#.ctor(AutoRest.Core.ClientModel.EnumType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.EnumTypeModel.#.ctor(AutoRest.Core.ClientModel.EnumType,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Imports", Scope = "member", Target = "AutoRest.Java.IModelTypeJv.#Imports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.JavaCodeGenerator.#.ctor(AutoRest.Core.Settings)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#_package")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#.ctor(System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#NormalizeTypeReference(AutoRest.Core.ClientModel.IType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#NormalizeCompositeType(AutoRest.Core.ClientModel.CompositeType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ParameterModels")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#LogicalParameterModels")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.ModelTemplateModel.#.ctor(AutoRest.Core.ClientModel.CompositeType,AutoRest.Core.ClientModel.ServiceClient)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.ParameterModel.#LocationImport(AutoRest.Core.ClientModel.ParameterLocation)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.ParameterModel.#NeedsSpecialSerialization(AutoRest.Core.ClientModel.IType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.ResponseModel.#_response")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.ModelTemplateModel.#PropertyModels")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "AutoRest.Java.PropertyModel.#.ctor(AutoRest.Core.ClientModel.Property,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.PropertyModel.#.ctor(AutoRest.Core.ClientModel.Property,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "AutoRest.Java.ParameterModel.#convertClientTypeToWireType(AutoRest.Java.IModelTypeJv,System.String,System.String,System.String,System.Int32)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.ParameterModel.#convertClientTypeToWireType(AutoRest.Java.IModelTypeJv,System.String,System.String,System.String,System.Int32)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.ResponseModel.#_interfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.ResponseModel.#_interfaceImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "AutoRest.Java.ResponseModel.#_implImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.ResponseModel.#_implImports")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "AutoRest.Java.ResponseModel.#convertToClientType(AutoRest.Java.IModelTypeJv,System.String,System.String,System.Int32)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "AutoRest.Core.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "AutoRest.Java.ParameterModel.#convertClientTypeToWireType(AutoRest.Java.IModelTypeJv,System.String,System.String,System.String,System.Int32)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "AutoRest.Java.PrimaryTypeModel.#DefaultValue(AutoRest.Core.ClientModel.Method)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#MethodGroupTypeString")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "AutoRest.Java.MethodGroupTemplateModel.#MethodGroupFullType")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "AutoRest.Java.PackageInfoTemplateModel.#.ctor(AutoRest.Core.ClientModel.ServiceClient,System.String,System.String)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "AutoRest.Java.JavaCodeNamer.#NormalizeTypeDeclaration(AutoRest.Core.ClientModel.IType)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "AutoRest.Java.MethodTemplateModel.#GetMapping(AutoRest.Core.ClientModel.ParameterMapping,System.Boolean)")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Scope = "member", Target = "AutoRest.Java.ModelTemplateModel.#PropertyModels")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "AutoRest.Java.PropertyModel.#_package")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Imports", Scope = "member", Target = "AutoRest.Java.PropertyModel.#Imports")]
+
diff --git a/src/vanilla/IScopeProvider.cs b/src/vanilla/IScopeProvider.cs
new file mode 100644
index 0000000000..70c4e5cf58
--- /dev/null
+++ b/src/vanilla/IScopeProvider.cs
@@ -0,0 +1,10 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+namespace AutoRest.Java
+{
+ public interface IScopeProvider
+ {
+ string GetVariableName(string prefix);
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/Model/CodeModelJv.cs b/src/vanilla/Model/CodeModelJv.cs
new file mode 100644
index 0000000000..0139a73e4d
--- /dev/null
+++ b/src/vanilla/Model/CodeModelJv.cs
@@ -0,0 +1,106 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class CodeModelJv : CodeModel
+ {
+ public override string BaseUrl
+ {
+ get
+ {
+ if (!base.BaseUrl.Contains("://"))
+ {
+ return $"https://{base.BaseUrl}";
+ }
+ return base.BaseUrl;
+ }
+ set
+ {
+ base.BaseUrl = value;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable AllOperations => Operations.Where(operation => !operation.Name.IsNullOrEmpty()).Cast();
+
+ [JsonIgnore]
+ public bool IsCustomBaseUri => Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension);
+
+ [JsonIgnore]
+ public string ServiceClientServiceType
+ {
+ get
+ {
+ return CodeNamerJv.GetServiceName(Name.ToPascalCase());
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ImplPackage => "implementation";
+
+ [JsonIgnore]
+ public string ModelsPackage => ".models";
+
+ [JsonIgnore]
+ public IEnumerable RootMethods => Methods.Where(m => m.Group.IsNullOrEmpty()).OfType();
+
+ [JsonIgnore]
+ public string FullyQualifiedDomainName => Namespace.ToLowerInvariant() + "." + this.Name;
+
+ [JsonIgnore]
+ public virtual IEnumerable ImplImports
+ {
+ get
+ {
+ HashSet classes = new HashSet();
+ classes.Add(FullyQualifiedDomainName);
+ foreach(var methodGroupFullType in this.AllOperations.Select(op => op.MethodGroupFullType).Distinct())
+ {
+ classes.Add(methodGroupFullType);
+ }
+ if (this.Properties.Any(p => p.ModelType.IsPrimaryType(KnownPrimaryType.Credentials)))
+ {
+ classes.Add("com.microsoft.rest.credentials.ServiceClientCredentials");
+ }
+ classes.AddRange(new[]{
+ "com.microsoft.rest.ServiceClient",
+ "com.microsoft.rest.RestClient",
+ "okhttp3.OkHttpClient",
+ "retrofit2.Retrofit"
+ });
+
+ classes.AddRange(RootMethods
+ .SelectMany(m => m.ImplImports)
+ .OrderBy(i => i));
+
+ return classes.AsEnumerable();
+ }
+ }
+
+ [JsonIgnore]
+ public virtual List InterfaceImports
+ {
+ get
+ {
+ HashSet classes = new HashSet();
+
+ classes.AddRange(RootMethods
+ .SelectMany(m => m.InterfaceImports)
+ .OrderBy(i => i).Distinct());
+
+ classes.Add("com.microsoft.rest.RestClient");
+
+ return classes.ToList();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/Model/CompositeTypeJv.cs b/src/vanilla/Model/CompositeTypeJv.cs
new file mode 100644
index 0000000000..d2ccc0f810
--- /dev/null
+++ b/src/vanilla/Model/CompositeTypeJv.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using AutoRest.Extensions;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class CompositeTypeJv : CompositeType, IModelTypeJv
+ {
+ public const string ExternalExtension = "x-ms-external";
+ protected string _runtimePackage = "com.microsoft.rest";
+
+ public CompositeTypeJv()
+ {
+ }
+
+ public CompositeTypeJv(string name) : base(name)
+ {
+ }
+
+ [JsonIgnore]
+ public virtual string ModelsPackage => (this.CodeModel as CodeModelJv).ModelsPackage;
+
+ [JsonIgnore]
+ public virtual string Package
+ {
+ get
+ {
+ if (Extensions.Get(ExternalExtension) == true) {
+ return _runtimePackage;
+ }
+ else
+ {
+ return string.Join(
+ ".",
+ CodeModel?.Namespace.ToLowerInvariant(),
+ "models");
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable SubTypes
+ {
+ get
+ {
+ if (BaseIsPolymorphic)
+ {
+ foreach (CompositeType type in CodeModel.ModelTypes)
+ {
+ if (type.BaseModelType != null &&
+ type.BaseModelType.SerializedName == this.SerializedName)
+ {
+ yield return type;
+ }
+ }
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ExceptionTypeDefinitionName
+ {
+ get
+ {
+ if (this.Extensions.ContainsKey(SwaggerExtensions.NameOverrideExtension))
+ {
+ var ext = this.Extensions[SwaggerExtensions.NameOverrideExtension] as Newtonsoft.Json.Linq.JContainer;
+ if (ext != null && ext["name"] != null)
+ {
+ return ext["name"].ToString();
+ }
+ }
+ return this.Name + "Exception";
+ }
+ }
+
+ [JsonIgnore]
+ public bool NeedsFlatten
+ {
+ get
+ {
+ return Properties.OfType().Any(p => p.WasFlattened());
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable Imports
+ {
+ get
+ {
+ var imports = new List();
+ if (Name.Contains('<'))
+ {
+ imports.AddRange(ParseGenericType().SelectMany(t => t.Imports));
+ }
+ else
+ {
+ imports.Add(string.Join(".", Package, Name));
+ }
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable ImportList
+ {
+ get
+ {
+ var classes = new HashSet();
+ classes.AddRange(Properties.SelectMany(pm => (pm as PropertyJv).Imports));
+ if (this.Properties.Any(p => !p.GetJsonProperty().IsNullOrEmpty()))
+ {
+ classes.Add("com.fasterxml.jackson.annotation.JsonProperty");
+ }
+ // For polymorphism
+ if (BaseIsPolymorphic)
+ {
+ classes.Add("com.fasterxml.jackson.annotation.JsonTypeInfo");
+ classes.Add("com.fasterxml.jackson.annotation.JsonTypeName");
+ if (SubTypes.Any())
+ {
+ classes.Add("com.fasterxml.jackson.annotation.JsonSubTypes");
+ }
+ }
+ // For flattening
+ if (NeedsFlatten)
+ {
+ classes.Add("com.microsoft.rest.serializer.JsonFlatten");
+ }
+ return classes.AsEnumerable();
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ResponseVariant => this;
+
+ [JsonIgnore]
+ public IModelTypeJv ParameterVariant => this;
+
+ [JsonIgnore]
+ public IModelTypeJv NonNullableVariant => this;
+
+ protected IEnumerable ParseGenericType()
+ {
+ string name = Name;
+ string[] types = Name.ToString().Split(new String[] { "<", ">", ",", ", " }, StringSplitOptions.RemoveEmptyEntries);
+ foreach (var innerType in types.Where(t => !string.IsNullOrWhiteSpace(t)))
+ {
+ if (!CodeNamerJv.PrimaryTypes.Contains(innerType.Trim()))
+ {
+ yield return new CompositeTypeJv { Name = innerType.Trim(), CodeModel = CodeModel };
+ }
+ }
+ }
+ }
+}
diff --git a/src/vanilla/Model/DictionaryTypeJv.cs b/src/vanilla/Model/DictionaryTypeJv.cs
new file mode 100644
index 0000000000..1d1d3b174c
--- /dev/null
+++ b/src/vanilla/Model/DictionaryTypeJv.cs
@@ -0,0 +1,58 @@
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using System;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class DictionaryTypeJv : DictionaryType, IModelTypeJv
+ {
+ public DictionaryTypeJv()
+ {
+ Name.OnGet += value => $"Map";
+ }
+
+ [JsonIgnore]
+ public IEnumerable Imports
+ {
+ get
+ {
+ List imports = new List { "java.util.Map" };
+ return imports.Concat((this.ValueType as IModelTypeJv)?.Imports ?? Enumerable.Empty());
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ResponseVariant
+ {
+ get
+ {
+ var respvariant = (ValueType as IModelTypeJv).ResponseVariant;
+ if (respvariant != ValueType && (respvariant as PrimaryTypeJv)?.Nullable != false)
+ {
+ return new DictionaryTypeJv { ValueType = respvariant };
+ }
+ return this;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ParameterVariant
+ {
+ get
+ {
+ var respvariant = (ValueType as IModelTypeJv).ParameterVariant;
+ if (respvariant != ValueType && (respvariant as PrimaryTypeJv)?.Nullable != false)
+ {
+ return new DictionaryTypeJv { ValueType = respvariant };
+ }
+ return this;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv NonNullableVariant => this;
+ }
+}
diff --git a/src/vanilla/Model/EnumTypeJv.cs b/src/vanilla/Model/EnumTypeJv.cs
new file mode 100644
index 0000000000..d9b99c88d1
--- /dev/null
+++ b/src/vanilla/Model/EnumTypeJv.cs
@@ -0,0 +1,42 @@
+using System.Collections.Generic;
+using System.Globalization;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+using AutoRest.Core;
+
+namespace AutoRest.Java.Model
+{
+ public class EnumTypeJv : EnumType, IModelTypeJv
+ {
+ public EnumTypeJv()
+ {
+ Name.OnGet += name => string.IsNullOrEmpty(name) || name == "enum" ? "String" : CodeNamer.Instance.GetTypeName(name);
+ }
+
+ [JsonIgnore]
+ public virtual string ModelsPackage => (this.CodeModel as CodeModelJv).ModelsPackage;
+
+ [JsonIgnore]
+ public virtual IEnumerable Imports
+ {
+ get
+ {
+ if (Name != "String")
+ {
+ yield return string.Join(".",
+ CodeModel?.Namespace.ToLowerInvariant(),
+ "models", Name);
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ResponseVariant => this;
+
+ [JsonIgnore]
+ public IModelTypeJv ParameterVariant => this;
+
+ [JsonIgnore]
+ public IModelTypeJv NonNullableVariant => this;
+ }
+}
diff --git a/src/vanilla/Model/IModelTypeJv.cs b/src/vanilla/Model/IModelTypeJv.cs
new file mode 100644
index 0000000000..4bdf5ce90c
--- /dev/null
+++ b/src/vanilla/Model/IModelTypeJv.cs
@@ -0,0 +1,34 @@
+using AutoRest.Core.Model;
+using System.Collections.Generic;
+
+namespace AutoRest.Java.Model
+{
+ public interface IModelTypeJv : IModelType
+ {
+ IEnumerable Imports { get; }
+
+ IModelTypeJv ResponseVariant { get; }
+ IModelTypeJv ParameterVariant { get; }
+
+ IModelTypeJv NonNullableVariant { get; }
+ }
+
+ public static class IModelTypeExtensions
+ {
+ public static IModelType ServiceResponseVariant(this IModelType original, bool wantNullable = false)
+ {
+ if (wantNullable)
+ {
+ return original; // the original is always nullable
+ }
+ return (original as IModelTypeJv)?.ResponseVariant?.NonNullableVariant ?? original;
+ }
+
+ public static string GetDefaultValue(this IModelType type, Method parent)
+ {
+ return type is PrimaryTypeJv && type.Name == "RequestBody"
+ ? "RequestBody.create(MediaType.parse(\"" + parent.RequestContentType + "\"), new byte[0])"
+ : type.DefaultValue;
+ }
+ }
+}
diff --git a/src/vanilla/Model/MethodGroupJv.cs b/src/vanilla/Model/MethodGroupJv.cs
new file mode 100644
index 0000000000..40beae29c3
--- /dev/null
+++ b/src/vanilla/Model/MethodGroupJv.cs
@@ -0,0 +1,143 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class MethodGroupJv : MethodGroup
+ {
+ public MethodGroupJv()
+ {
+ Name.OnGet += Core.Utilities.Extensions.ToCamelCase;
+ }
+ public MethodGroupJv(string name) : base(name)
+ {
+ Name.OnGet += Core.Utilities.Extensions.ToCamelCase;
+ }
+
+ [JsonIgnore]
+ public string MethodGroupFullType
+ {
+ get
+ {
+ return (CodeModel.Namespace.ToLowerInvariant()) + "." + TypeName;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodGroupDeclarationType
+ {
+ get
+ {
+ return TypeName;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodGroupImplType
+ {
+ get
+ {
+ return TypeName + ImplClassSuffix;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ImplClassSuffix
+ {
+ get
+ {
+ return "Impl";
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ParentDeclaration
+ {
+ get
+ {
+ return " implements " + MethodGroupTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ImplPackage
+ {
+ get
+ {
+ return "implementation";
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodGroupTypeString
+ {
+ get
+ {
+ if (this.Methods
+ .OfType()
+ .SelectMany(m => m.ImplImports)
+ .Any(i => i.Split('.').LastOrDefault() == TypeName))
+ {
+ return MethodGroupFullType;
+ }
+ return TypeName;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodGroupServiceType
+ {
+ get
+ {
+ return CodeNamerJv.GetServiceName(Name.ToPascalCase());
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ServiceClientType
+ {
+ get
+ {
+ return CodeModel.Name + "Impl";
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable ImplImports
+ {
+ get
+ {
+ var imports = new List();
+ imports.Add("retrofit2.Retrofit");
+ if (MethodGroupTypeString == TypeName)
+ {
+ imports.Add(MethodGroupFullType);
+ }
+ imports.AddRange(this.Methods
+ .OfType()
+ .SelectMany(m => m.ImplImports)
+ .OrderBy(i => i).Distinct());
+ return imports;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable InterfaceImports
+ {
+ get
+ {
+ return this.Methods
+ .OfType()
+ .SelectMany(m => m.InterfaceImports)
+ .OrderBy(i => i).Distinct();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/Model/MethodJv.cs b/src/vanilla/Model/MethodJv.cs
new file mode 100644
index 0000000000..53f91b4e0d
--- /dev/null
+++ b/src/vanilla/Model/MethodJv.cs
@@ -0,0 +1,791 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Text;
+using AutoRest.Core;
+using AutoRest.Core.Utilities;
+using AutoRest.Extensions;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+using AutoRest.Core.Utilities.Collections;
+
+namespace AutoRest.Java.Model
+{
+ public class MethodJv : Method
+ {
+ [JsonIgnore]
+ public virtual IEnumerable RetrofitParameters
+ {
+ get
+ {
+ var parameters = LogicalParameters.OfType().Where(p => p.Location != ParameterLocation.None)
+ .Where(p => !p.Extensions.ContainsKey("hostParameter")).ToList();
+ if (IsParameterizedHost)
+ {
+ parameters.Add(new ParameterJv
+ {
+ Name = "parameterizedHost",
+ SerializedName = "x-ms-parameterized-host",
+ Location = ParameterLocation.Header,
+ IsRequired = true,
+ ModelType = new PrimaryTypeJv(KnownPrimaryType.String)
+ });
+ }
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable OrderedRetrofitParameters
+ {
+ get
+ {
+ return RetrofitParameters.Where(p => p.Location == ParameterLocation.Path)
+ .Union(RetrofitParameters.Where(p => p.Location != ParameterLocation.Path));
+ }
+ }
+
+ ///
+ /// Generate the method parameter declarations for a method
+ ///
+ [JsonIgnore]
+ public virtual string MethodParameterApiDeclaration
+ {
+ get
+ {
+ List declarations = new List();
+ foreach (ParameterJv parameter in OrderedRetrofitParameters)
+ {
+ StringBuilder declarationBuilder = new StringBuilder();
+ if (Url.Contains("{" + parameter.Name + "}"))
+ {
+ parameter.Location = ParameterLocation.Path;
+ }
+ if (parameter.Location == ParameterLocation.Path ||
+ parameter.Location == ParameterLocation.Query ||
+ parameter.Location == ParameterLocation.Header)
+ {
+ declarationBuilder.Append(string.Format(CultureInfo.InvariantCulture,
+ "@{0}(\"{1}\") ",
+ parameter.Location.ToString(),
+ parameter.SerializedName));
+ }
+ else if (parameter.Location == ParameterLocation.Body)
+ {
+ declarationBuilder.Append(string.Format(CultureInfo.InvariantCulture,
+ "@{0} ",
+ parameter.Location.ToString()));
+ }
+ else if (parameter.Location == ParameterLocation.FormData)
+ {
+ declarationBuilder.Append(string.Format(CultureInfo.InvariantCulture,
+ "@Part(\"{0}\") ",
+ parameter.SerializedName));
+ }
+ var declarativeName = parameter.ClientProperty != null ? parameter.ClientProperty.Name : parameter.Name;
+ declarationBuilder.Append(parameter.WireType.Name);
+ declarationBuilder.Append(" " + declarativeName);
+ declarations.Add(declarationBuilder.ToString());
+ }
+
+ var declaration = string.Join(", ", declarations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodParameterDeclaration
+ {
+ get
+ {
+ List declarations = new List();
+ foreach (var parameter in LocalParameters.Where(p => !p.IsConstant))
+ {
+ declarations.Add(parameter.ClientType.ParameterVariant.Name + " " + parameter.Name);
+ }
+
+ var declaration = string.Join(", ", declarations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodRequiredParameterDeclaration
+ {
+ get
+ {
+ List declarations = new List();
+ foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired))
+ {
+ declarations.Add(parameter.ClientType.ParameterVariant.Name + " " + parameter.Name);
+ }
+
+ var declaration = string.Join(", ", declarations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodParameterInvocation
+ {
+ get
+ {
+ List invocations = new List();
+ foreach (var parameter in LocalParameters.Where(p => !p.IsConstant))
+ {
+ invocations.Add(parameter.Name);
+ }
+
+ var declaration = string.Join(", ", invocations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodDefaultParameterInvocation
+ {
+ get
+ {
+ List invocations = new List();
+ foreach (var parameter in LocalParameters)
+ {
+ if (parameter.IsRequired)
+ {
+ invocations.Add(parameter.Name);
+ }
+ else
+ {
+ invocations.Add("null");
+ }
+ }
+
+ var declaration = string.Join(", ", invocations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodRequiredParameterInvocation
+ {
+ get
+ {
+ List invocations = new List();
+ foreach (var parameter in LocalParameters)
+ {
+ if (parameter.IsRequired && !parameter.IsConstant)
+ {
+ invocations.Add(parameter.Name);
+ }
+ }
+
+ var declaration = string.Join(", ", invocations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodParameterApiInvocation
+ {
+ get
+ {
+ List invocations = new List();
+ foreach (var parameter in OrderedRetrofitParameters)
+ {
+ invocations.Add(parameter.WireName);
+ }
+
+ var declaration = string.Join(", ", invocations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public string MethodRequiredParameterApiInvocation
+ {
+ get
+ {
+ List invocations = new List();
+ foreach (var parameter in OrderedRetrofitParameters)
+ {
+ invocations.Add(parameter.WireName);
+ }
+
+ var declaration = string.Join(", ", invocations);
+ return declaration;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual bool IsParameterizedHost => CodeModel.Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension);
+
+ ///
+ /// Generate a reference to the ServiceClient
+ ///
+ [JsonIgnore]
+ public string ClientReference => Group.IsNullOrEmpty() ? "this" : "this.client";
+
+ [JsonIgnore]
+ public string ParameterConversion
+ {
+ get
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ foreach (var p in RetrofitParameters)
+ {
+ if (p.NeedsConversion)
+ {
+ builder.Append(p.ConvertToWireType(p.Name, ClientReference));
+ }
+ }
+ return builder.ToString();
+ }
+ }
+
+ [JsonIgnore]
+ public string RequiredParameterConversion
+ {
+ get
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ foreach (var p in RetrofitParameters.Where(p => p.IsRequired))
+ {
+ if (p.NeedsConversion)
+ {
+ builder.Append(p.ConvertToWireType(p.Name, ClientReference));
+ }
+ }
+ return builder.ToString();
+ }
+ }
+
+ ///
+ /// Generates input mapping code block.
+ ///
+ ///
+ public virtual string BuildInputMappings(bool filterRequired = false)
+ {
+ var builder = new IndentedStringBuilder();
+ foreach (var transformation in InputParameterTransformation)
+ {
+ var outParamName = transformation.OutputParameter.Name;
+ while (Parameters.Any(p => p.Name == outParamName))
+ {
+ outParamName += "1";
+ }
+ transformation.OutputParameter.Name = outParamName;
+ var nullCheck = BuildNullCheckExpression(transformation);
+ bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired && !filterRequired;
+ if (conditionalAssignment)
+ {
+ builder.AppendLine("{0} {1} = null;",
+ ((ParameterJv) transformation.OutputParameter).ClientType.ParameterVariant.Name,
+ outParamName);
+ builder.AppendLine("if ({0}) {{", nullCheck).Indent();
+ }
+
+ if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
+ transformation.OutputParameter.ModelType is CompositeType)
+ {
+ builder.AppendLine("{0}{1} = new {2}();",
+ !conditionalAssignment ? ((ParameterJv)transformation.OutputParameter).ClientType.ParameterVariant.Name + " " : "",
+ outParamName,
+ transformation.OutputParameter.ModelType.Name);
+ }
+
+ foreach (var mapping in transformation.ParameterMappings)
+ {
+ builder.AppendLine("{0}{1}{2};",
+ !conditionalAssignment && !(transformation.OutputParameter.ModelType is CompositeType) ?
+ ((ParameterJv)transformation.OutputParameter).ClientType.ParameterVariant.Name + " " : "",
+ outParamName,
+ GetMapping(mapping, filterRequired));
+ }
+
+ if (conditionalAssignment)
+ {
+ builder.Outdent()
+ .AppendLine("}");
+ }
+ }
+
+ return builder.ToString();
+ }
+
+ private static string GetMapping(ParameterMapping mapping, bool filterRequired = false)
+ {
+ string inputPath = mapping.InputParameter.Name;
+ if (mapping.InputParameterProperty != null)
+ {
+ inputPath += "." + CodeNamer.Instance.CamelCase(mapping.InputParameterProperty) + "()";
+ }
+ if (filterRequired && !mapping.InputParameter.IsRequired)
+ {
+ inputPath = "null";
+ }
+
+ string outputPath = "";
+ if (mapping.OutputParameterProperty != null)
+ {
+ outputPath += ".with" + CodeNamer.Instance.PascalCase(mapping.OutputParameterProperty);
+ return string.Format(CultureInfo.InvariantCulture, "{0}({1})", outputPath, inputPath);
+ }
+ else
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", outputPath, inputPath);
+ }
+ }
+
+ private static string BuildNullCheckExpression(ParameterTransformation transformation)
+ {
+ if (transformation == null)
+ {
+ throw new ArgumentNullException("transformation");
+ }
+
+ return string.Join(" || ",
+ transformation.ParameterMappings
+ .Where(m => !m.InputParameter.IsRequired)
+ .Select(m => m.InputParameter.Name + " != null"));
+ }
+
+ [JsonIgnore]
+ public IEnumerable RequiredNullableParameters
+ {
+ get
+ {
+ foreach (ParameterJv param in Parameters)
+ {
+ if (!param.ModelType.IsPrimaryType(KnownPrimaryType.Int) &&
+ !param.ModelType.IsPrimaryType(KnownPrimaryType.Double) &&
+ !param.ModelType.IsPrimaryType(KnownPrimaryType.Boolean) &&
+ !param.ModelType.IsPrimaryType(KnownPrimaryType.Long) &&
+ !param.ModelType.IsPrimaryType(KnownPrimaryType.UnixTime) &&
+ !param.IsConstant && param.IsRequired)
+ {
+ yield return param;
+ }
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable ParametersToValidate
+ {
+ get
+ {
+ foreach (ParameterJv param in Parameters)
+ {
+ if (param.ModelType is PrimaryType ||
+ param.ModelType is EnumType ||
+ param.IsConstant)
+ {
+ continue;
+ }
+ yield return param;
+ }
+ }
+ }
+
+ ///
+ /// Gets the expression for response body initialization
+ ///
+ [JsonIgnore]
+ public virtual string InitializeResponseBody
+ {
+ get
+ {
+ return string.Empty;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodParameterDeclarationWithCallback
+ {
+ get
+ {
+ var parameters = MethodParameterDeclaration;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback",
+ ReturnTypeJv.GenericBodyClientTypeString);
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodRequiredParameterDeclarationWithCallback
+ {
+ get
+ {
+ var parameters = MethodRequiredParameterDeclaration;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback",
+ ReturnTypeJv.GenericBodyClientTypeString);
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodParameterInvocationWithCallback
+ {
+ get
+ {
+ var parameters = MethodParameterInvocation;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ parameters += "serviceCallback";
+ return parameters;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string MethodRequiredParameterInvocationWithCallback
+ {
+ get
+ {
+ var parameters = MethodDefaultParameterInvocation;
+ if (!parameters.IsNullOrEmpty())
+ {
+ parameters += ", ";
+ }
+ parameters += "serviceCallback";
+ return parameters;
+ }
+ }
+
+ ///
+ /// Get the parameters that are actually method parameters in the order they appear in the method signature
+ /// exclude global parameters
+ ///
+ [JsonIgnore]
+ public IEnumerable LocalParameters
+ {
+ get
+ {
+ //Omit parameter-group properties for now since Java doesn't support them yet
+ var par = Parameters
+ .OfType()
+ .Where(p => p != null && !p.IsClientProperty && !string.IsNullOrWhiteSpace(p.Name))
+ .OrderBy(item => !item.IsRequired)
+ .ToList();
+ return par;
+ }
+ }
+
+ [JsonIgnore]
+ public string HostParameterReplacementArgs
+ {
+ get
+ {
+ var args = new List();
+ foreach (var param in Parameters.Where(p => p.Extensions.ContainsKey("hostParameter")))
+ {
+ args.Add("\"{" + param.SerializedName + "}\", " + param.Name);
+ }
+ return string.Join(", ", args);
+ }
+ }
+
+ ///
+ /// Get the type for operation exception
+ ///
+ [JsonIgnore]
+ public virtual string OperationExceptionTypeString
+ {
+ get
+ {
+ if (this.DefaultResponse.Body is CompositeType)
+ {
+ var type = this.DefaultResponse.Body as CompositeTypeJv;
+ return type.ExceptionTypeDefinitionName;
+ }
+ else
+ {
+ return "RestException";
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable Exceptions
+ {
+ get
+ {
+ yield return OperationExceptionTypeString;
+ yield return "IOException";
+ if (RequiredNullableParameters.Any())
+ {
+ yield return "IllegalArgumentException";
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ExceptionString
+ {
+ get
+ {
+ return string.Join(", ", Exceptions);
+ }
+ }
+
+ [JsonIgnore]
+ public virtual List ExceptionStatements
+ {
+ get
+ {
+ List exceptions = new List();
+ exceptions.Add(OperationExceptionTypeString + " exception thrown from REST call");
+ exceptions.Add("IOException exception thrown from serialization/deserialization");
+ if (RequiredNullableParameters.Any())
+ {
+ exceptions.Add("IllegalArgumentException exception thrown from invalid parameters");
+ }
+ return exceptions;
+ }
+ }
+
+ [JsonIgnore]
+ public string CallType
+ {
+ get
+ {
+ if (this.HttpMethod == HttpMethod.Head)
+ {
+ return "Void";
+ }
+ else
+ {
+ return "ResponseBody";
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ResponseBuilder
+ {
+ get
+ {
+ return "ServiceResponseBuilder";
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string RuntimeBasePackage
+ {
+ get
+ {
+ return "com.microsoft.rest";
+ }
+ }
+
+ [JsonIgnore]
+ public ResponseJv ReturnTypeJv => ReturnType as ResponseJv;
+
+ [JsonIgnore]
+ public virtual string ReturnTypeResponseName => ReturnTypeJv?.BodyClientType?.ServiceResponseVariant()?.Name;
+
+ public virtual string ResponseGeneration(bool filterRequired = false)
+ {
+ if (ReturnTypeJv.NeedsConversion)
+ {
+ IndentedStringBuilder builder= new IndentedStringBuilder();
+ builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());",
+ ReturnTypeJv.GenericBodyWireTypeString, this.Name.ToCamelCase());
+ builder.AppendLine("{0} body = null;", ReturnTypeJv.BodyClientType.Name)
+ .AppendLine("if (response.body() != null) {")
+ .Indent().AppendLine("{0}", ReturnTypeJv.ConvertBodyToClientType("response.body()", "body"))
+ .Outdent().AppendLine("}");
+ return builder.ToString();
+ }
+ return "";
+ }
+
+ [JsonIgnore]
+ public virtual string ReturnValue
+ {
+ get
+ {
+ if (ReturnTypeJv.NeedsConversion)
+ {
+ return "new ServiceResponse<" + ReturnTypeJv.GenericBodyClientTypeString + ">(body, response.response())";
+ }
+ return this.Name + "Delegate(call.execute())";
+ }
+ }
+
+ public virtual string SuccessCallback(bool filterRequired = false)
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ if (ReturnTypeJv.NeedsConversion)
+ {
+ builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeJv.GenericBodyWireTypeString, this.Name);
+ builder.AppendLine("{0} body = null;", ReturnTypeJv.BodyClientType.Name)
+ .AppendLine("if (result.body() != null) {")
+ .Indent().AppendLine("{0}", ReturnTypeJv.ConvertBodyToClientType("result.body()", "body"))
+ .Outdent().AppendLine("}");
+ builder.AppendLine("ServiceResponse<{0}> clientResponse = new ServiceResponse<{0}>(body, result.response());",
+ ReturnTypeJv.GenericBodyClientTypeString);
+ builder.AppendLine("if (serviceCallback != null) {")
+ .Indent().AppendLine("serviceCallback.success(clientResponse);", ReturnTypeJv.GenericBodyClientTypeString)
+ .Outdent().AppendLine("}");
+ builder.AppendLine("serviceFuture.success(clientResponse);");
+ }
+ else
+ {
+ builder.AppendLine("{0} clientResponse = {1}Delegate(response);", ReturnTypeJv.WireResponseTypeString, this.Name);
+ builder.AppendLine("if (serviceCallback != null) {")
+ .Indent().AppendLine("serviceCallback.success(clientResponse);", this.Name)
+ .Outdent().AppendLine("}");
+ builder.AppendLine("serviceFuture.success(clientResponse);");
+ }
+ return builder.ToString();
+ }
+
+ public virtual string ClientResponse(bool filterRequired = false)
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ if (ReturnTypeJv.NeedsConversion)
+ {
+ builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeJv.GenericBodyWireTypeString, this.Name);
+ builder.AppendLine("{0} body = null;", ReturnTypeJv.BodyClientType.Name)
+ .AppendLine("if (result.body() != null) {")
+ .Indent().AppendLine("{0}", ReturnTypeJv.ConvertBodyToClientType("result.body()", "body"))
+ .Outdent().AppendLine("}");
+ builder.AppendLine("ServiceResponse<{0}> clientResponse = new ServiceResponse<{0}>(body, result.response());",
+ ReturnTypeJv.GenericBodyClientTypeString);
+ }
+ else
+ {
+ builder.AppendLine("{0} clientResponse = {1}Delegate(response);", ReturnTypeJv.WireResponseTypeString, this.Name);
+ }
+ return builder.ToString();
+ }
+
+ [JsonIgnore]
+ public virtual string ServiceFutureFactoryMethod
+ {
+ get
+ {
+ string factoryMethod = "fromResponse";
+ if (ReturnType.Headers != null)
+ {
+ factoryMethod = "fromHeaderResponse";
+ }
+ return factoryMethod;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string CallbackDocumentation
+ {
+ get
+ {
+ return " * @param serviceCallback the async ServiceCallback to handle successful and failed responses.";
+ }
+ }
+
+ [JsonIgnore]
+ public virtual List InterfaceImports
+ {
+ get
+ {
+ HashSet imports = new HashSet();
+ // static imports
+ imports.Add("rx.Observable");
+ imports.Add("com.microsoft.rest.ServiceFuture");
+ imports.Add("com.microsoft.rest." + ReturnTypeJv.ClientResponseType);
+ imports.Add("com.microsoft.rest.ServiceCallback");
+ // parameter types
+ this.Parameters.OfType().ForEach(p => imports.AddRange(p.InterfaceImports));
+ // return type
+ imports.AddRange(this.ReturnTypeJv.InterfaceImports);
+ // exceptions
+ this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
+ .ForEach(ex =>
+ {
+ string exceptionImport = CodeNamerJv.GetJavaException(ex, CodeModel);
+ if (exceptionImport != null) imports.Add(CodeNamerJv.GetJavaException(ex, CodeModel));
+ }); return imports.ToList();
+ }
+ }
+
+ [JsonIgnore]
+ public virtual List ImplImports
+ {
+ get
+ {
+ HashSet imports = new HashSet();
+ // static imports
+ imports.Add("rx.Observable");
+ imports.Add("rx.functions.Func1");
+ if (RequestContentType == "multipart/form-data" || RequestContentType == "application/x-www-form-urlencoded")
+ {
+ imports.Add("retrofit2.http.Multipart");
+ }
+ else
+ {
+ imports.Add("retrofit2.http.Headers");
+ }
+ imports.Add("retrofit2.Response");
+ if (this.HttpMethod != HttpMethod.Head)
+ {
+ imports.Add("okhttp3.ResponseBody");
+ }
+ imports.Add("com.microsoft.rest.ServiceFuture");
+ imports.Add("com.microsoft.rest." + ReturnTypeJv.ClientResponseType);
+ imports.Add("com.microsoft.rest.ServiceCallback");
+ this.RetrofitParameters.ForEach(p => imports.AddRange(p.RetrofitImports));
+ // Http verb annotations
+ imports.Add(this.HttpMethod.ImportFrom());
+ // response type conversion
+ if (this.Responses.Any())
+ {
+ imports.Add("com.google.common.reflect.TypeToken");
+ }
+ // validation
+ if (!ParametersToValidate.IsNullOrEmpty())
+ {
+ imports.Add("com.microsoft.rest.Validator");
+ }
+ // parameters
+ this.LocalParameters.Concat(this.LogicalParameters.OfType())
+ .ForEach(p => imports.AddRange(p.ClientImplImports));
+ this.RetrofitParameters.ForEach(p => imports.AddRange(p.WireImplImports));
+ // return type
+ imports.AddRange(this.ReturnTypeJv.ImplImports);
+ if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream))
+ {
+ imports.Add("retrofit2.http.Streaming");
+ }
+ // response type (can be different from return type)
+ this.Responses.ForEach(r => imports.AddRange((r.Value as ResponseJv).ImplImports));
+ // exceptions
+ this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
+ .ForEach(ex =>
+ {
+ string exceptionImport = CodeNamerJv.GetJavaException(ex, CodeModel);
+ if (exceptionImport != null) imports.Add(CodeNamerJv.GetJavaException(ex, CodeModel));
+ });
+ // parameterized host
+ if (IsParameterizedHost)
+ {
+ imports.Add("com.google.common.base.Joiner");
+ }
+ return imports.ToList();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/Model/PackageInfoTemplateModel.cs b/src/vanilla/Model/PackageInfoTemplateModel.cs
new file mode 100644
index 0000000000..6f72b0a5f6
--- /dev/null
+++ b/src/vanilla/Model/PackageInfoTemplateModel.cs
@@ -0,0 +1,22 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+
+namespace AutoRest.Java.Model
+{
+ public class PackageInfoTemplateModel
+ {
+ public string Title { get; private set; }
+ public string Description { get; private set; }
+ public string SubPackage { get; private set; }
+
+ public PackageInfoTemplateModel(CodeModel cm, string subPackage = null)
+ {
+ Title = cm.Name;
+ Description = cm.Documentation;
+ SubPackage = subPackage;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/vanilla/Model/ParameterJv.cs b/src/vanilla/Model/ParameterJv.cs
new file mode 100644
index 0000000000..5b5611de94
--- /dev/null
+++ b/src/vanilla/Model/ParameterJv.cs
@@ -0,0 +1,304 @@
+using System.Collections.Generic;
+using System.Globalization;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class ParameterJv : Parameter
+ {
+ public ParameterJv()
+ : base()
+ {
+ _implImports = new List();
+ Name.OnGet += name => !IsClientProperty
+ ? name
+ : string.Format(CultureInfo.InvariantCulture,
+ "{0}.{1}()",
+ Method != null && true == Method.Group.IsNullOrEmpty() ? "this" : "this.client",
+ ClientProperty.Name.ToCamelCase());
+ }
+
+ [JsonIgnore]
+ public bool WantNullable => IsXNullable ?? !IsRequired;
+
+ public override IModelType ModelType
+ {
+ get
+ {
+ if (base.ModelType == null)
+ {
+ return null;
+ }
+ return WantNullable
+ ? base.ModelType
+ : (base.ModelType as IModelTypeJv).NonNullableVariant;
+ }
+ set
+ {
+ base.ModelType = value;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ClientType
+ {
+ get
+ {
+ return ((IModelTypeJv)ModelType).ParameterVariant;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv WireType
+ {
+ get
+ {
+ if (ModelType.IsPrimaryType(KnownPrimaryType.Stream))
+ {
+ var res = new PrimaryTypeJv(KnownPrimaryType.Stream);
+ res.Name.FixedValue = "RequestBody";
+ return res;
+ }
+ else if (!ModelType.IsPrimaryType(KnownPrimaryType.Base64Url) &&
+ Location != Core.Model.ParameterLocation.Body &&
+ Location != Core.Model.ParameterLocation.FormData &&
+ NeedsSpecialSerialization(ClientType))
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.String);
+ }
+ else
+ {
+ return (IModelTypeJv) ModelType;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public string WireName => NeedsConversion ? this.Name.ToCamelCase() + "Converted" : this.Name.ToString();
+
+ [JsonIgnore]
+ public bool NeedsConversion => !ClientType.StructurallyEquals(WireType);
+
+ public string ConvertToWireType(string source, string clientReference)
+ {
+ if (Location != Core.Model.ParameterLocation.Body &&
+ Location != Core.Model.ParameterLocation.FormData &&
+ NeedsSpecialSerialization(ModelType))
+ {
+ var primary = ClientType as PrimaryTypeJv;
+ var sequence = ClientType as SequenceTypeJv;
+ if (primary != null && primary.IsPrimaryType(KnownPrimaryType.ByteArray))
+ {
+ if (WireType.IsPrimaryType(KnownPrimaryType.String))
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0} {1} = Base64.encodeBase64String({2});", WireType.Name, WireName, source);
+ }
+ else
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0} {1} = Base64Url.encode({2});", WireType.Name, WireName, source);
+ }
+ }
+ else if (sequence != null)
+ {
+ return string.Format(CultureInfo.InvariantCulture,
+ "{0} {1} = {2}.serializerAdapter().serializeList({3}, CollectionFormat.{4});",
+ WireType.Name,
+ WireName,
+ clientReference,
+ source,
+ CollectionFormat.ToString().ToUpperInvariant());
+ }
+ }
+
+ return convertClientTypeToWireType(WireType, source, WireName, clientReference);
+ }
+
+ private string convertClientTypeToWireType(IModelTypeJv wireType, string source, string target, string clientReference, int level = 0)
+ {
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+ if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("DateTimeRfc1123 {0} = {1};", target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ builder.AppendLine("{0}{1} = new DateTimeRfc1123({2});", IsRequired ? "DateTimeRfc1123 " : "", target, source);
+ if (!IsRequired)
+ {
+ builder.Outdent().AppendLine("}");
+ }
+ }
+ else if (wireType.IsPrimaryType(KnownPrimaryType.UnixTime))
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("Long {0} = {1};", target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ builder.AppendLine("{0}{1} = {2}.toDateTime(DateTimeZone.UTC).getMillis() / 1000;", IsRequired ? "Long " : "", target, source);
+ }
+ else if (wireType.IsPrimaryType(KnownPrimaryType.Base64Url))
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("Base64Url {0} = {1};", target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ builder.AppendLine("{0}{1} = Base64Url.encode({2});", IsRequired ? "Base64Url " : "", target, source);
+ if (!IsRequired)
+ {
+ builder.Outdent().AppendLine("}");
+ }
+ }
+ else if (wireType.IsPrimaryType(KnownPrimaryType.Stream))
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("RequestBody {0} = {1};", target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ builder.AppendLine("{0}{1} = RequestBody.create(MediaType.parse(\"{2}\"), {3});",
+ IsRequired ? "RequestBody " : "", target, Method.RequestContentType, source);
+ if (!IsRequired)
+ {
+ builder.Outdent().AppendLine("}");
+ }
+ }
+ else if (wireType is SequenceTypeJv)
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ var sequenceType = wireType as SequenceTypeJv;
+ var elementType = sequenceType.ElementType as IModelTypeJv;
+ var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ builder.AppendLine("{0}{1} = new ArrayList<{2}>();", IsRequired ? wireType.Name + " " : "", target, elementType.Name)
+ .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source)
+ .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1))
+ .AppendLine("{0}.add({1});", target, itemTarget)
+ .Outdent().Append("}");
+ _implImports.Add("java.util.ArrayList");
+ if (!IsRequired)
+ {
+ builder.Outdent().AppendLine("}");
+ }
+ }
+ else if (wireType is DictionaryTypeJv)
+ {
+ if (!IsRequired)
+ {
+ builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.GetDefaultValue(Method) ?? "null")
+ .AppendLine("if ({0} != null) {{", source).Indent();
+ }
+ var dictionaryType = wireType as DictionaryTypeJv;
+ var valueType = dictionaryType.ValueType as IModelTypeJv;
+ var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ builder.AppendLine("{0}{1} = new HashMap();", IsRequired ? wireType.Name + " " : "", target, valueType.Name)
+ .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source)
+ .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1))
+ .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
+ .Outdent().Append("}");
+ _implImports.Add("java.util.HashMap");
+ if (!IsRequired)
+ {
+ builder.Outdent().AppendLine("}");
+ }
+ }
+ return builder.ToString();
+ }
+
+ [JsonIgnore]
+ public IEnumerable InterfaceImports
+ {
+ get
+ {
+ return ClientType.Imports;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable RetrofitImports
+ {
+ get
+ {
+ var imports = new List();
+ // type imports
+ if (this.Location == Core.Model.ParameterLocation.Body || !NeedsSpecialSerialization(ModelType))
+ {
+ imports.AddRange(WireType.Imports);
+ }
+ // parameter location
+ imports.Add(LocationImport(this.Location));
+ return imports;
+ }
+ }
+
+ private List _implImports;
+
+ [JsonIgnore]
+ public IEnumerable ClientImplImports
+ {
+ get
+ {
+ return ClientType.Imports;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable WireImplImports
+ {
+ get
+ {
+ var imports = new List(WireType.Imports);
+ if (Location != Core.Model.ParameterLocation.Body)
+ {
+ if (this.ModelType.IsPrimaryType(KnownPrimaryType.ByteArray))
+ {
+ imports.Add("org.apache.commons.codec.binary.Base64");
+ }
+ else if (this.ModelType is SequenceType)
+ {
+ imports.Add("com.microsoft.rest.CollectionFormat");
+ }
+ }
+ if (ModelType.IsPrimaryType(KnownPrimaryType.Stream) && Location == Core.Model.ParameterLocation.Body)
+ {
+ imports.Add("okhttp3.RequestBody");
+ imports.Add("okhttp3.MediaType");
+ }
+ return imports;
+ }
+ }
+
+ private string LocationImport(ParameterLocation parameterLocation)
+ {
+ if (parameterLocation == Core.Model.ParameterLocation.FormData)
+ {
+ return "retrofit2.http.Part";
+ }
+ else if (parameterLocation != Core.Model.ParameterLocation.None)
+ {
+ return "retrofit2.http." + parameterLocation.ToString();
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ private bool NeedsSpecialSerialization(IModelType type)
+ {
+ var known = type as PrimaryType;
+ return known != null &&
+ type.IsPrimaryType(KnownPrimaryType.ByteArray) ||
+ type is SequenceType;
+ }
+ }
+}
diff --git a/src/vanilla/Model/PrimaryTypeJv.cs b/src/vanilla/Model/PrimaryTypeJv.cs
new file mode 100644
index 0000000000..d705864943
--- /dev/null
+++ b/src/vanilla/Model/PrimaryTypeJv.cs
@@ -0,0 +1,223 @@
+using System;
+using System.Collections.Generic;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class PrimaryTypeJv : PrimaryType, IModelTypeJv
+ {
+ public PrimaryTypeJv()
+ {
+ Name.OnGet += v => ImplementationName;
+ }
+
+ public PrimaryTypeJv(KnownPrimaryType type)
+ : base(type)
+ {
+ Name.OnGet += v => ImplementationName;
+ }
+
+ public bool WantNullable { get; private set; } = true;
+
+ [JsonIgnore]
+ public bool Nullable
+ {
+ get
+ {
+ if (WantNullable)
+ {
+ return true;
+ }
+ switch (KnownPrimaryType)
+ {
+ case KnownPrimaryType.None:
+ case KnownPrimaryType.Boolean:
+ case KnownPrimaryType.Double:
+ case KnownPrimaryType.Int:
+ case KnownPrimaryType.Long:
+ case KnownPrimaryType.UnixTime:
+ return false;
+ }
+ return true;
+ }
+ }
+
+ [JsonIgnore]
+ public override string DefaultValue
+ {
+ get
+ {
+ if (Name == "byte[]")
+ {
+ return "new byte[0]";
+ }
+ else if (Name == "Byte[]")
+ {
+ return "new Byte[0]";
+ }
+ else if (Nullable)
+ {
+ return null;
+ }
+ else
+ {
+ throw new NotSupportedException(this.Name + " does not have default value!");
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ParameterVariant
+ {
+ get
+ {
+ if (KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.DateTime);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.UnixTime)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.DateTime);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.Base64Url)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.ByteArray);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.Stream)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.ByteArray);
+ }
+ else
+ {
+ return this;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ResponseVariant
+ {
+ get
+ {
+ if (KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.DateTime);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.UnixTime)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.DateTime);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.Base64Url)
+ {
+ return new PrimaryTypeJv(KnownPrimaryType.ByteArray);
+ }
+ else if (KnownPrimaryType == KnownPrimaryType.None)
+ {
+ return NonNullableVariant;
+ }
+ return this;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable Imports
+ {
+ get
+ {
+ switch (KnownPrimaryType)
+ {
+ case KnownPrimaryType.Base64Url:
+ yield return "com.microsoft.rest.Base64Url";
+ break;
+ case KnownPrimaryType.Date:
+ yield return "org.joda.time.LocalDate";
+ break;
+ case KnownPrimaryType.DateTime:
+ yield return "org.joda.time.DateTime";
+ break;
+ case KnownPrimaryType.DateTimeRfc1123:
+ yield return "com.microsoft.rest.DateTimeRfc1123";
+ break;
+ case KnownPrimaryType.Decimal:
+ yield return "java.math.BigDecimal";
+ break;
+ case KnownPrimaryType.Stream:
+ yield return "java.io.InputStream";
+ break;
+ case KnownPrimaryType.TimeSpan:
+ yield return "org.joda.time.Period";
+ break;
+ case KnownPrimaryType.UnixTime:
+ yield return "org.joda.time.DateTime";
+ yield return "org.joda.time.DateTimeZone";
+ break;
+ case KnownPrimaryType.Uuid:
+ yield return "java.util.UUID";
+ break;
+ case KnownPrimaryType.Credentials:
+ yield return "com.microsoft.rest.ServiceClientCredentials";
+ break;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv NonNullableVariant =>
+ new PrimaryTypeJv
+ {
+ KnownPrimaryType = KnownPrimaryType,
+ Format = Format,
+ WantNullable = false
+ };
+
+ [JsonIgnore]
+ public virtual string ImplementationName
+ {
+ get
+ {
+ switch (KnownPrimaryType)
+ {
+ case KnownPrimaryType.None:
+ return WantNullable ? "Void" : "void";
+ case KnownPrimaryType.Base64Url:
+ return "Base64Url";
+ case KnownPrimaryType.Boolean:
+ return WantNullable ? "Boolean" : "boolean";
+ case KnownPrimaryType.ByteArray:
+ return "byte[]";
+ case KnownPrimaryType.Date:
+ return "LocalDate";
+ case KnownPrimaryType.DateTime:
+ return "DateTime";
+ case KnownPrimaryType.DateTimeRfc1123:
+ return "DateTimeRfc1123";
+ case KnownPrimaryType.Double:
+ return WantNullable ? "Double" : "double";
+ case KnownPrimaryType.Decimal:
+ return "BigDecimal";
+ case KnownPrimaryType.Int:
+ return WantNullable ? "Integer" : "int";
+ case KnownPrimaryType.Long:
+ return WantNullable ? "Long" : "long";
+ case KnownPrimaryType.Stream:
+ return "InputStream";
+ case KnownPrimaryType.String:
+ return "String";
+ case KnownPrimaryType.TimeSpan:
+ return "Period";
+ case KnownPrimaryType.UnixTime:
+ return WantNullable ? "Long" : "long";
+ case KnownPrimaryType.Uuid:
+ return "UUID";
+ case KnownPrimaryType.Object:
+ return "Object";
+ case KnownPrimaryType.Credentials:
+ return "ServiceClientCredentials";
+ }
+ throw new NotImplementedException($"Primary type {KnownPrimaryType} is not implemented in {GetType().Name}");
+ }
+ }
+ }
+}
diff --git a/src/vanilla/Model/PropertyJv.cs b/src/vanilla/Model/PropertyJv.cs
new file mode 100644
index 0000000000..bba3475229
--- /dev/null
+++ b/src/vanilla/Model/PropertyJv.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using AutoRest.Extensions;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class PropertyJv : Property
+ {
+ public PropertyJv()
+ {
+ }
+
+ public override string SerializedName
+ {
+ get => Extensions.ContainsKey(SwaggerExtensions.FlattenOriginalTypeName) ? base.SerializedName : base.SerializedName?.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\");
+ set => base.SerializedName = value;
+ }
+
+
+ [JsonIgnore]
+ public bool WantNullable => IsXNullable ?? !IsRequired;
+
+ public override IModelType ModelType
+ {
+ get
+ {
+ if (base.ModelType == null)
+ {
+ return null;
+ }
+ return WantNullable
+ ? base.ModelType
+ : (base.ModelType as IModelTypeJv).NonNullableVariant;
+ }
+ set
+ {
+ base.ModelType = value;
+ }
+ }
+
+ [JsonIgnore]
+ public string ClientForm
+ {
+ get
+ {
+ if (ModelType.IsPrimaryType(KnownPrimaryType.Base64Url))
+ {
+ return string.Format("this.{0}.decodedBytes()", Name, CultureInfo.InvariantCulture);
+ }
+ else if (ModelType.IsPrimaryType(KnownPrimaryType.UnixTime))
+ {
+ return "new DateTime(this." + Name + " * 1000L, DateTimeZone.UTC)";
+ }
+ else if (ModelType.Name != ((IModelTypeJv)ModelType).ResponseVariant.Name)
+ {
+ return string.Format("this.{0}.{1}()", Name, ((IModelTypeJv)ModelType).ResponseVariant.Name.ToCamelCase(), CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ return Name;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public string FromClientForm
+ {
+ get
+ {
+ if (ModelType.IsPrimaryType(KnownPrimaryType.Base64Url))
+ {
+ return string.Format("Base64Url.encode({0})", Name, CultureInfo.InvariantCulture);
+ }
+ else if (ModelType.IsPrimaryType(KnownPrimaryType.UnixTime))
+ {
+ return string.Format("{0}.toDateTime(DateTimeZone.UTC).getMillis() / 1000", Name, CultureInfo.InvariantCulture);
+ }
+ else if (ModelType.Name != ((IModelTypeJv)ModelType).ResponseVariant.Name)
+ {
+ return string.Format("new {0}({1})", ModelType.Name, Name, CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ return Name;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IEnumerable Imports
+ {
+ get
+ {
+ var imports = new List(ModelType.ImportSafe()
+ .Where(c => !c.StartsWith(
+ string.Join(
+ ".",
+ Parent?.CodeModel?.Namespace.ToLowerInvariant(),
+ "models"),
+ StringComparison.OrdinalIgnoreCase)));
+ if (ModelType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)
+ || ModelType.IsPrimaryType(KnownPrimaryType.Base64Url))
+ {
+ imports.AddRange(ModelType.ImportSafe());
+ imports.AddRange(((IModelTypeJv)ModelType).ResponseVariant.ImportSafe());
+ }
+ return imports;
+ }
+ }
+ }
+}
diff --git a/src/vanilla/Model/ResponseJv.cs b/src/vanilla/Model/ResponseJv.cs
new file mode 100644
index 0000000000..86e0d290a7
--- /dev/null
+++ b/src/vanilla/Model/ResponseJv.cs
@@ -0,0 +1,381 @@
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class ResponseJv : Response
+ {
+ protected List _interfaceImports = new List();
+ protected List _implImports = new List();
+
+ public ResponseJv()
+ {
+ }
+
+ public ResponseJv(IModelTypeJv body, IModelTypeJv headers)
+ : base(body, headers)
+ {
+ }
+
+ #region types
+
+ [JsonIgnore]
+ public bool NeedsConversion
+ {
+ get
+ {
+ return
+ ((BodyWireType == null ? BodyClientType != null : !BodyWireType.StructurallyEquals(BodyClientType)) && BodyClientType.Name != "void") ||
+ (HeaderWireType == null ? HeaderClientType != null : !HeaderWireType.StructurallyEquals(HeaderClientType));
+ }
+ }
+
+ [JsonIgnore]
+ public virtual IModelTypeJv BodyClientType
+ {
+ get
+ {
+ return BodyWireType.ResponseVariant;
+ }
+ }
+
+ private IModelTypeJv _bodyWireType;
+
+ [JsonIgnore]
+ public IModelTypeJv BodyWireType
+ {
+ get
+ {
+ if (_bodyWireType == null)
+ {
+ if (Body == null)
+ {
+ _bodyWireType = new PrimaryTypeJv(KnownPrimaryType.None);
+ }
+ else
+ {
+ _bodyWireType = (IModelTypeJv) Body;
+ }
+ }
+ return _bodyWireType;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv HeaderClientType
+ {
+ get
+ {
+ if (Headers == null)
+ {
+ return null;
+ }
+ else
+ {
+ return HeaderWireType.ResponseVariant;
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv HeaderWireType
+ {
+ get
+ {
+ if (Headers == null)
+ {
+ return null;
+ }
+ return (IModelTypeJv)Headers;
+ }
+ }
+
+ public string ConvertBodyToClientType(string source, string target)
+ {
+ return convertToClientType(BodyWireType, source, target);
+ }
+
+ public string ConvertHeaderToClientType(string source, string target)
+ {
+ return convertToClientType(HeaderWireType, source, target);
+ }
+
+ #endregion
+
+ #region template strings
+
+ [JsonIgnore]
+ public string ClientResponseType
+ {
+ get
+ {
+ if (Headers == null)
+ {
+ return "ServiceResponse";
+ }
+ else
+ {
+ return "ServiceResponseWithHeaders";
+ }
+ }
+ }
+
+ public string WrapResponse(string responseTypeString)
+ {
+ if (Headers == null)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, responseTypeString);
+ }
+ else
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, responseTypeString, GenericHeaderClientTypeString);
+ }
+ }
+
+ [JsonIgnore]
+ public string ClientResponseTypeString
+ {
+ get
+ {
+ return WrapResponse(GenericBodyClientTypeString);
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ObservableClientResponseTypeString
+ {
+ get
+ {
+ return ClientResponseTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ClientCallbackTypeString
+ {
+ get
+ {
+ return GenericBodyClientTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public string WireResponseTypeString
+ {
+ get
+ {
+ if (Headers == null)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, GenericBodyWireTypeString);
+ }
+ else
+ {
+ return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, GenericBodyWireTypeString, GenericHeaderWireTypeString);
+ }
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string GenericBodyClientTypeString
+ {
+ get
+ {
+ var respvariant = BodyWireType.ResponseVariant;
+ if ((respvariant as PrimaryTypeJv)?.Nullable != false)
+ {
+ return respvariant.Name;
+ }
+ return BodyWireType.Name;
+ }
+ }
+
+ [JsonIgnore]
+ public string GenericBodyClientTypeStringWrapped
+ {
+ get
+ {
+ return WrapResponse(GenericBodyClientTypeString);
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ServiceFutureGenericParameterString
+ {
+ get
+ {
+ return GenericBodyClientTypeString;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string ServiceResponseGenericParameterString
+ {
+ get
+ {
+ return ServiceFutureGenericParameterString;
+ }
+ }
+
+ [JsonIgnore]
+ public string ServiceResponseGenericParameterStringWrapped
+ {
+ get
+ {
+ return WrapResponse(ServiceResponseGenericParameterString);
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string GenericHeaderClientTypeString
+ {
+ get
+ {
+ return HeaderClientType.ResponseVariant.Name;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string GenericBodyWireTypeString
+ {
+ get
+ {
+ return BodyWireType.Name;
+ }
+ }
+
+ [JsonIgnore]
+ public string GenericBodyWireTypeStringWrapped
+ {
+ get
+ {
+ return WrapResponse(GenericBodyWireTypeString);
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string GenericHeaderWireTypeString
+ {
+ get
+ {
+ return HeaderWireType.Name;
+ }
+ }
+
+ [JsonIgnore]
+ public virtual string SequenceElementTypeString
+ {
+ get
+ {
+ var sequenceType = Body as SequenceTypeJv;
+ return sequenceType != null ? sequenceType.ElementType.Name.ToString() : "Void";
+ }
+ }
+
+ public string ServiceResponseCreation(string serviceResponse, string body, string response)
+ {
+ string format;
+ if (Headers == null)
+ {
+ format = "new {0}({1}, {2}.response())";
+ }
+ else
+ {
+ format = "new {0}({1}, {2}.headers(), {2}.response())";
+ }
+ return string.Format(format, serviceResponse, body, response);
+ }
+
+ #endregion
+
+ [JsonIgnore]
+ public IEnumerable InterfaceImports
+ {
+ get
+ {
+ return _interfaceImports.Concat(BodyClientType.ImportSafe()).Concat(HeaderClientType.ImportSafe());
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable ImplImports
+ {
+ get
+ {
+ var imports = new List(InterfaceImports);
+ imports.AddRange(BodyWireType.ImportSafe());
+ imports.AddRange(HeaderWireType.ImportSafe());
+ if (this.NeedsConversion && (Body is SequenceType || Headers is SequenceType))
+ {
+ imports.Add("java.util.ArrayList");
+ }
+ if (this.NeedsConversion && (Body is DictionaryType || Headers is DictionaryType))
+ {
+ imports.Add("java.util.HashMap");
+ }
+ return imports;
+ }
+ }
+
+ private string convertToClientType(IModelTypeJv type, string source, string target, int level = 0)
+ {
+ if (type == null)
+ {
+ return target + " = " + source + ";";
+ }
+
+ IndentedStringBuilder builder = new IndentedStringBuilder();
+
+ var sequenceType = type as SequenceTypeJv;
+ var dictionaryType = type as DictionaryTypeJv;
+
+ if (sequenceType != null)
+ {
+ var elementType = sequenceType.ElementType as IModelTypeJv;
+ var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name)
+ .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source)
+ .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget)
+ .AppendLine(convertToClientType(elementType, itemName, itemTarget, level + 1))
+ .AppendLine("{0}.add({1});", target, itemTarget)
+ .Outdent().Append("}");
+ _implImports.Add("java.util.ArrayList");
+ return builder.ToString();
+ }
+ else if (dictionaryType != null)
+ {
+ var valueType = dictionaryType.ValueType as IModelTypeJv;
+ var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
+ builder.AppendLine("{0} = new HashMap();", target, valueType.ResponseVariant.Name)
+ .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.Name, itemName, source)
+ .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget)
+ .AppendLine(convertToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1))
+ .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
+ .Outdent().Append("}");
+ _implImports.Add("java.util.HashMap");
+ return builder.ToString();
+ }
+ else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
+ {
+ return target + " = " + source + ".dateTime();";
+ }
+ else if (type.IsPrimaryType(KnownPrimaryType.UnixTime))
+ {
+ return target + " = new DateTime(" + source + " * 1000L, DateTimeZone.UTC);";
+ }
+ else if (type.IsPrimaryType(KnownPrimaryType.Base64Url))
+ {
+ return target + " = " + source + ".decodedBytes();";
+ }
+ else
+ {
+ return target + " = " + source + ";";
+ }
+ }
+ }
+}
diff --git a/src/vanilla/Model/SequenceTypeJv.cs b/src/vanilla/Model/SequenceTypeJv.cs
new file mode 100644
index 0000000000..03e4e6d7b7
--- /dev/null
+++ b/src/vanilla/Model/SequenceTypeJv.cs
@@ -0,0 +1,57 @@
+using System.Collections.Generic;
+using System.Linq;
+using AutoRest.Core.Utilities;
+using AutoRest.Core.Model;
+using Newtonsoft.Json;
+
+namespace AutoRest.Java.Model
+{
+ public class SequenceTypeJv : SequenceType, IModelTypeJv
+ {
+ public SequenceTypeJv()
+ {
+ Name.OnGet += v => $"List<{ElementType.Name}>";
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ResponseVariant
+ {
+ get
+ {
+ var respvariant = (ElementType as IModelTypeJv).ResponseVariant;
+ if (respvariant != ElementType && (respvariant as PrimaryTypeJv)?.Nullable != false)
+ {
+ return new SequenceTypeJv { ElementType = respvariant };
+ }
+ return this;
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv ParameterVariant
+ {
+ get
+ {
+ var respvariant = (ElementType as IModelTypeJv).ParameterVariant;
+ if (respvariant != ElementType && (respvariant as PrimaryTypeJv)?.Nullable != false)
+ {
+ return new SequenceTypeJv { ElementType = respvariant };
+ }
+ return this;
+ }
+ }
+
+ [JsonIgnore]
+ public IEnumerable Imports
+ {
+ get
+ {
+ List imports = new List { "java.util.List" };
+ return imports.Concat(((IModelTypeJv) this.ElementType).Imports);
+ }
+ }
+
+ [JsonIgnore]
+ public IModelTypeJv NonNullableVariant => this;
+ }
+}
diff --git a/src/vanilla/PluginJv.cs b/src/vanilla/PluginJv.cs
new file mode 100644
index 0000000000..153d0f5911
--- /dev/null
+++ b/src/vanilla/PluginJv.cs
@@ -0,0 +1,38 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License. See License.txt in the project root for license information.
+//
+
+using AutoRest.Core;
+using AutoRest.Core.Extensibility;
+using AutoRest.Core.Model;
+using AutoRest.Core.Utilities;
+using AutoRest.Java.Model;
+using static AutoRest.Core.Utilities.DependencyInjection;
+
+namespace AutoRest.Java
+{
+ public sealed class PluginJv : Plugin
+ {
+ public PluginJv()
+ {
+ Context = new Context
+ {
+ // inherit base settings
+ Context,
+
+ // set code model implementations our own implementations
+ new Factory(),
+ new Factory(),
+ new Factory