swagger_aem 0.9.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,387 @@
1
+ =begin
2
+ #Adobe Experience Manager (AEM) API
3
+
4
+ #Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
5
+
6
+ OpenAPI spec version: 1.0
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+ Licensed under the Apache License, Version 2.0 (the "License");
11
+ you may not use this file except in compliance with the License.
12
+ You may obtain a copy of the License at
13
+
14
+ http://www.apache.org/licenses/LICENSE-2.0
15
+
16
+ Unless required by applicable law or agreed to in writing, software
17
+ distributed under the License is distributed on an "AS IS" BASIS,
18
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ See the License for the specific language governing permissions and
20
+ limitations under the License.
21
+
22
+ =end
23
+
24
+ require 'date'
25
+ require 'json'
26
+ require 'logger'
27
+ require 'tempfile'
28
+ require 'typhoeus'
29
+ require 'uri'
30
+
31
+ module SwaggerAemClient
32
+ class ApiClient
33
+ # The Configuration object holding settings to be used in the API client.
34
+ attr_accessor :config
35
+
36
+ # Defines the headers to be used in HTTP requests of all API calls by default.
37
+ #
38
+ # @return [Hash]
39
+ attr_accessor :default_headers
40
+
41
+ # Initializes the ApiClient
42
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
43
+ def initialize(config = Configuration.default)
44
+ @config = config
45
+ @user_agent = "Swagger-Codegen/#{VERSION}/ruby"
46
+ @default_headers = {
47
+ 'Content-Type' => "application/json",
48
+ 'User-Agent' => @user_agent
49
+ }
50
+ end
51
+
52
+ def self.default
53
+ @@default ||= ApiClient.new
54
+ end
55
+
56
+ # Call an API with given options.
57
+ #
58
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
59
+ # the data deserialized from response body (could be nil), response status code and response headers.
60
+ def call_api(http_method, path, opts = {})
61
+ request = build_request(http_method, path, opts)
62
+ response = request.run
63
+
64
+ if @config.debugging
65
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
66
+ end
67
+
68
+ unless response.success?
69
+ if response.timed_out?
70
+ fail ApiError.new('Connection timed out')
71
+ elsif response.code == 0
72
+ # Errors from libcurl will be made visible here
73
+ fail ApiError.new(:code => 0,
74
+ :message => response.return_message)
75
+ else
76
+ fail ApiError.new(:code => response.code,
77
+ :response_headers => response.headers,
78
+ :response_body => response.body),
79
+ response.status_message
80
+ end
81
+ end
82
+
83
+ if opts[:return_type]
84
+ data = deserialize(response, opts[:return_type])
85
+ else
86
+ data = nil
87
+ end
88
+ return data, response.code, response.headers
89
+ end
90
+
91
+ # Builds the HTTP request
92
+ #
93
+ # @param [String] http_method HTTP method/verb (e.g. POST)
94
+ # @param [String] path URL path (e.g. /account/new)
95
+ # @option opts [Hash] :header_params Header parameters
96
+ # @option opts [Hash] :query_params Query parameters
97
+ # @option opts [Hash] :form_params Query parameters
98
+ # @option opts [Object] :body HTTP body (JSON/XML)
99
+ # @return [Typhoeus::Request] A Typhoeus Request
100
+ def build_request(http_method, path, opts = {})
101
+ url = build_request_url(path)
102
+ http_method = http_method.to_sym.downcase
103
+
104
+ header_params = @default_headers.merge(opts[:header_params] || {})
105
+ query_params = opts[:query_params] || {}
106
+ form_params = opts[:form_params] || {}
107
+
108
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
109
+
110
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
111
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
112
+
113
+ req_opts = {
114
+ :method => http_method,
115
+ :headers => header_params,
116
+ :params => query_params,
117
+ :params_encoding => @config.params_encoding,
118
+ :timeout => @config.timeout,
119
+ :ssl_verifypeer => @config.verify_ssl,
120
+ :ssl_verifyhost => _verify_ssl_host,
121
+ :sslcert => @config.cert_file,
122
+ :sslkey => @config.key_file,
123
+ :verbose => @config.debugging
124
+ }
125
+
126
+ # set custom cert, if provided
127
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
128
+
129
+ if [:post, :patch, :put, :delete].include?(http_method)
130
+ req_body = build_request_body(header_params, form_params, opts[:body])
131
+ req_opts.update :body => req_body
132
+ if @config.debugging
133
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
134
+ end
135
+ end
136
+
137
+ Typhoeus::Request.new(url, req_opts)
138
+ end
139
+
140
+ # Check if the given MIME is a JSON MIME.
141
+ # JSON MIME examples:
142
+ # application/json
143
+ # application/json; charset=UTF8
144
+ # APPLICATION/JSON
145
+ # @param [String] mime MIME
146
+ # @return [Boolean] True if the MIME is application/json
147
+ def json_mime?(mime)
148
+ !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil?
149
+ end
150
+
151
+ # Deserialize the response to the given return type.
152
+ #
153
+ # @param [Response] response HTTP response
154
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
155
+ def deserialize(response, return_type)
156
+ body = response.body
157
+ return nil if body.nil? || body.empty?
158
+
159
+ # return response body directly for String return type
160
+ return body if return_type == 'String'
161
+
162
+ # handle file downloading - save response body into a tmp file and return the File instance
163
+ return download_file(response) if return_type == 'File'
164
+
165
+ # ensuring a default content type
166
+ content_type = response.headers['Content-Type'] || 'application/json'
167
+
168
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
169
+
170
+ begin
171
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
172
+ rescue JSON::ParserError => e
173
+ if %w(String Date DateTime).include?(return_type)
174
+ data = body
175
+ else
176
+ raise e
177
+ end
178
+ end
179
+
180
+ convert_to_type data, return_type
181
+ end
182
+
183
+ # Convert data to the given return type.
184
+ # @param [Object] data Data to be converted
185
+ # @param [String] return_type Return type
186
+ # @return [Mixed] Data in a particular type
187
+ def convert_to_type(data, return_type)
188
+ return nil if data.nil?
189
+ case return_type
190
+ when 'String'
191
+ data.to_s
192
+ when 'Integer'
193
+ data.to_i
194
+ when 'Float'
195
+ data.to_f
196
+ when 'BOOLEAN'
197
+ data == true
198
+ when 'DateTime'
199
+ # parse date time (expecting ISO 8601 format)
200
+ DateTime.parse data
201
+ when 'Date'
202
+ # parse date time (expecting ISO 8601 format)
203
+ Date.parse data
204
+ when 'Object'
205
+ # generic object (usually a Hash), return directly
206
+ data
207
+ when /\AArray<(.+)>\z/
208
+ # e.g. Array<Pet>
209
+ sub_type = $1
210
+ data.map {|item| convert_to_type(item, sub_type) }
211
+ when /\AHash\<String, (.+)\>\z/
212
+ # e.g. Hash<String, Integer>
213
+ sub_type = $1
214
+ {}.tap do |hash|
215
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
216
+ end
217
+ else
218
+ # models, e.g. Pet
219
+ SwaggerAemClient.const_get(return_type).new.tap do |model|
220
+ model.build_from_hash data
221
+ end
222
+ end
223
+ end
224
+
225
+ # Save response body into a file in (the defined) temporary folder, using the filename
226
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
227
+ #
228
+ # @see Configuration#temp_folder_path
229
+ # @return [Tempfile] the file downloaded
230
+ def download_file(response)
231
+ content_disposition = response.headers['Content-Disposition']
232
+ if content_disposition and content_disposition =~ /filename=/i
233
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
234
+ prefix = sanitize_filename(filename)
235
+ else
236
+ prefix = 'download-'
237
+ end
238
+ prefix = prefix + '-' unless prefix.end_with?('-')
239
+
240
+ tempfile = nil
241
+ encoding = response.body.encoding
242
+ Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) do |file|
243
+ file.write(response.body)
244
+ tempfile = file
245
+ end
246
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
247
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
248
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
249
+ "explicitly with `tempfile.delete`"
250
+ tempfile
251
+ end
252
+
253
+ # Sanitize filename by removing path.
254
+ # e.g. ../../sun.gif becomes sun.gif
255
+ #
256
+ # @param [String] filename the filename to be sanitized
257
+ # @return [String] the sanitized filename
258
+ def sanitize_filename(filename)
259
+ filename.gsub(/.*[\/\\]/, '')
260
+ end
261
+
262
+ def build_request_url(path)
263
+ # Add leading and trailing slashes to path
264
+ path = "/#{path}".gsub(/\/+/, '/')
265
+ URI.encode(@config.base_url + path)
266
+ end
267
+
268
+ # Builds the HTTP request body
269
+ #
270
+ # @param [Hash] header_params Header parameters
271
+ # @param [Hash] form_params Query parameters
272
+ # @param [Object] body HTTP body (JSON/XML)
273
+ # @return [String] HTTP body data in the form of string
274
+ def build_request_body(header_params, form_params, body)
275
+ # http form
276
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
277
+ header_params['Content-Type'] == 'multipart/form-data'
278
+ data = {}
279
+ form_params.each do |key, value|
280
+ case value
281
+ when File, Array, nil
282
+ # let typhoeus handle File, Array and nil parameters
283
+ data[key] = value
284
+ else
285
+ data[key] = value.to_s
286
+ end
287
+ end
288
+ elsif body
289
+ data = body.is_a?(String) ? body : body.to_json
290
+ else
291
+ data = nil
292
+ end
293
+ data
294
+ end
295
+
296
+ # Update hearder and query params based on authentication settings.
297
+ #
298
+ # @param [Hash] header_params Header parameters
299
+ # @param [Hash] query_params Query parameters
300
+ # @param [String] auth_names Authentication scheme name
301
+ def update_params_for_auth!(header_params, query_params, auth_names)
302
+ Array(auth_names).each do |auth_name|
303
+ auth_setting = @config.auth_settings[auth_name]
304
+ next unless auth_setting
305
+ case auth_setting[:in]
306
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
307
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
308
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
309
+ end
310
+ end
311
+ end
312
+
313
+ # Sets user agent in HTTP header
314
+ #
315
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
316
+ def user_agent=(user_agent)
317
+ @user_agent = user_agent
318
+ @default_headers['User-Agent'] = @user_agent
319
+ end
320
+
321
+ # Return Accept header based on an array of accepts provided.
322
+ # @param [Array] accepts array for Accept
323
+ # @return [String] the Accept header (e.g. application/json)
324
+ def select_header_accept(accepts)
325
+ return nil if accepts.nil? || accepts.empty?
326
+ # use JSON when present, otherwise use all of the provided
327
+ json_accept = accepts.find { |s| json_mime?(s) }
328
+ return json_accept || accepts.join(',')
329
+ end
330
+
331
+ # Return Content-Type header based on an array of content types provided.
332
+ # @param [Array] content_types array for Content-Type
333
+ # @return [String] the Content-Type header (e.g. application/json)
334
+ def select_header_content_type(content_types)
335
+ # use application/json by default
336
+ return 'application/json' if content_types.nil? || content_types.empty?
337
+ # use JSON when present, otherwise use the first one
338
+ json_content_type = content_types.find { |s| json_mime?(s) }
339
+ return json_content_type || content_types.first
340
+ end
341
+
342
+ # Convert object (array, hash, object, etc) to JSON string.
343
+ # @param [Object] model object to be converted into JSON string
344
+ # @return [String] JSON string representation of the object
345
+ def object_to_http_body(model)
346
+ return model if model.nil? || model.is_a?(String)
347
+ local_body = nil
348
+ if model.is_a?(Array)
349
+ local_body = model.map{|m| object_to_hash(m) }
350
+ else
351
+ local_body = object_to_hash(model)
352
+ end
353
+ local_body.to_json
354
+ end
355
+
356
+ # Convert object(non-array) to hash.
357
+ # @param [Object] obj object to be converted into JSON string
358
+ # @return [String] JSON string representation of the object
359
+ def object_to_hash(obj)
360
+ if obj.respond_to?(:to_hash)
361
+ obj.to_hash
362
+ else
363
+ obj
364
+ end
365
+ end
366
+
367
+ # Build parameter value according to the given collection format.
368
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
369
+ def build_collection_param(param, collection_format)
370
+ case collection_format
371
+ when :csv
372
+ param.join(',')
373
+ when :ssv
374
+ param.join(' ')
375
+ when :tsv
376
+ param.join("\t")
377
+ when :pipes
378
+ param.join('|')
379
+ when :multi
380
+ # return the array directly as typhoeus will handle it as expected
381
+ param
382
+ else
383
+ fail "unknown collection format: #{collection_format.inspect}"
384
+ end
385
+ end
386
+ end
387
+ end
@@ -0,0 +1,47 @@
1
+ =begin
2
+ #Adobe Experience Manager (AEM) API
3
+
4
+ #Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
5
+
6
+ OpenAPI spec version: 1.0
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+ Licensed under the Apache License, Version 2.0 (the "License");
11
+ you may not use this file except in compliance with the License.
12
+ You may obtain a copy of the License at
13
+
14
+ http://www.apache.org/licenses/LICENSE-2.0
15
+
16
+ Unless required by applicable law or agreed to in writing, software
17
+ distributed under the License is distributed on an "AS IS" BASIS,
18
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ See the License for the specific language governing permissions and
20
+ limitations under the License.
21
+
22
+ =end
23
+
24
+ module SwaggerAemClient
25
+ class ApiError < StandardError
26
+ attr_reader :code, :response_headers, :response_body
27
+
28
+ # Usage examples:
29
+ # ApiError.new
30
+ # ApiError.new("message")
31
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
32
+ # ApiError.new(:code => 404, :message => "Not Found")
33
+ def initialize(arg = nil)
34
+ if arg.is_a? Hash
35
+ arg.each do |k, v|
36
+ if k.to_s == 'message'
37
+ super v
38
+ else
39
+ instance_variable_set "@#{k}", v
40
+ end
41
+ end
42
+ else
43
+ super arg
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,214 @@
1
+ =begin
2
+ #Adobe Experience Manager (AEM) API
3
+
4
+ #Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
5
+
6
+ OpenAPI spec version: 1.0
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+ Licensed under the Apache License, Version 2.0 (the "License");
11
+ you may not use this file except in compliance with the License.
12
+ You may obtain a copy of the License at
13
+
14
+ http://www.apache.org/licenses/LICENSE-2.0
15
+
16
+ Unless required by applicable law or agreed to in writing, software
17
+ distributed under the License is distributed on an "AS IS" BASIS,
18
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ See the License for the specific language governing permissions and
20
+ limitations under the License.
21
+
22
+ =end
23
+
24
+ require 'uri'
25
+
26
+ module SwaggerAemClient
27
+ class Configuration
28
+ # Defines url scheme
29
+ attr_accessor :scheme
30
+
31
+ # Defines url host
32
+ attr_accessor :host
33
+
34
+ # Defines url base path
35
+ attr_accessor :base_path
36
+
37
+ # Defines API keys used with API Key authentications.
38
+ #
39
+ # @return [Hash] key: parameter name, value: parameter value (API key)
40
+ #
41
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
42
+ # config.api_key['api_key'] = 'xxx'
43
+ attr_accessor :api_key
44
+
45
+ # Defines API key prefixes used with API Key authentications.
46
+ #
47
+ # @return [Hash] key: parameter name, value: API key prefix
48
+ #
49
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
50
+ # config.api_key_prefix['api_key'] = 'Token'
51
+ attr_accessor :api_key_prefix
52
+
53
+ # Defines the username used with HTTP basic authentication.
54
+ #
55
+ # @return [String]
56
+ attr_accessor :username
57
+
58
+ # Defines the password used with HTTP basic authentication.
59
+ #
60
+ # @return [String]
61
+ attr_accessor :password
62
+
63
+ # Defines the access token (Bearer) used with OAuth2.
64
+ attr_accessor :access_token
65
+
66
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
67
+ # details will be logged with `logger.debug` (see the `logger` attribute).
68
+ # Default to false.
69
+ #
70
+ # @return [true, false]
71
+ attr_accessor :debugging
72
+
73
+ # Defines the logger used for debugging.
74
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
75
+ #
76
+ # @return [#debug]
77
+ attr_accessor :logger
78
+
79
+ # Defines the temporary folder to store downloaded files
80
+ # (for API endpoints that have file response).
81
+ # Default to use `Tempfile`.
82
+ #
83
+ # @return [String]
84
+ attr_accessor :temp_folder_path
85
+
86
+ # The time limit for HTTP request in seconds.
87
+ # Default to 0 (never times out).
88
+ attr_accessor :timeout
89
+
90
+ ### TLS/SSL setting
91
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
92
+ # Default to true.
93
+ #
94
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
95
+ #
96
+ # @return [true, false]
97
+ attr_accessor :verify_ssl
98
+
99
+ ### TLS/SSL setting
100
+ # Set this to false to skip verifying SSL host name
101
+ # Default to true.
102
+ #
103
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
104
+ #
105
+ # @return [true, false]
106
+ attr_accessor :verify_ssl_host
107
+
108
+ ### TLS/SSL setting
109
+ # Set this to customize the certificate file to verify the peer.
110
+ #
111
+ # @return [String] the path to the certificate file
112
+ #
113
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
114
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
115
+ attr_accessor :ssl_ca_cert
116
+
117
+ ### TLS/SSL setting
118
+ # Client certificate file (for client certificate)
119
+ attr_accessor :cert_file
120
+
121
+ ### TLS/SSL setting
122
+ # Client private key file (for client certificate)
123
+ attr_accessor :key_file
124
+
125
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
126
+ # Default to nil.
127
+ #
128
+ # @see The params_encoding option of Ethon. Related source code:
129
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
130
+ attr_accessor :params_encoding
131
+
132
+ attr_accessor :inject_format
133
+
134
+ attr_accessor :force_ending_format
135
+
136
+ def initialize
137
+ @scheme = 'http'
138
+ @host = ''
139
+ @base_path = '/'
140
+ @api_key = {}
141
+ @api_key_prefix = {}
142
+ @timeout = 0
143
+ @verify_ssl = true
144
+ @verify_ssl_host = true
145
+ @params_encoding = nil
146
+ @cert_file = nil
147
+ @key_file = nil
148
+ @debugging = false
149
+ @inject_format = false
150
+ @force_ending_format = false
151
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
152
+
153
+ yield(self) if block_given?
154
+ end
155
+
156
+ # The default Configuration object.
157
+ def self.default
158
+ @@default ||= Configuration.new
159
+ end
160
+
161
+ def configure
162
+ yield(self) if block_given?
163
+ end
164
+
165
+ def scheme=(scheme)
166
+ # remove :// from scheme
167
+ @scheme = scheme.sub(/:\/\//, '')
168
+ end
169
+
170
+ def host=(host)
171
+ # remove http(s):// and anything after a slash
172
+ @host = host.sub(/https?:\/\//, '').split('/').first
173
+ end
174
+
175
+ def base_path=(base_path)
176
+ # Add leading and trailing slashes to base_path
177
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
178
+ @base_path = "" if @base_path == "/"
179
+ end
180
+
181
+ def base_url
182
+ url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
183
+ URI.encode(url)
184
+ end
185
+
186
+ # Gets API key (with prefix if set).
187
+ # @param [String] param_name the parameter name of API key auth
188
+ def api_key_with_prefix(param_name)
189
+ if @api_key_prefix[param_name]
190
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
191
+ else
192
+ @api_key[param_name]
193
+ end
194
+ end
195
+
196
+ # Gets Basic Auth token string
197
+ def basic_auth_token
198
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
199
+ end
200
+
201
+ # Returns Auth Settings hash for api client.
202
+ def auth_settings
203
+ {
204
+ 'aemAuth' =>
205
+ {
206
+ type: 'basic',
207
+ in: 'header',
208
+ key: 'Authorization',
209
+ value: basic_auth_token
210
+ },
211
+ }
212
+ end
213
+ end
214
+ end