iron_titan 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,332 @@
1
+ =begin
2
+ Titan API
3
+
4
+ The ultimate, language agnostic, container based job processing framework.
5
+
6
+ OpenAPI spec version: 0.0.1
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'typhoeus'
18
+ require 'uri'
19
+
20
+ module IronTitan
21
+ class ApiClient
22
+ # The Configuration object holding settings to be used in the API client.
23
+ attr_accessor :config
24
+
25
+ # Defines the headers to be used in HTTP requests of all API calls by default.
26
+ #
27
+ # @return [Hash]
28
+ attr_accessor :default_headers
29
+
30
+ def initialize(config = Configuration.default)
31
+ @config = config
32
+ @user_agent = "ruby-swagger-#{VERSION}"
33
+ @default_headers = {
34
+ 'Content-Type' => "application/json",
35
+ 'User-Agent' => @user_agent
36
+ }
37
+ end
38
+
39
+ def self.default
40
+ @@default ||= ApiClient.new
41
+ end
42
+
43
+ # Call an API with given options.
44
+ #
45
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
46
+ # the data deserialized from response body (could be nil), response status code and response headers.
47
+ def call_api(http_method, path, opts = {})
48
+ request = build_request(http_method, path, opts)
49
+ response = request.run
50
+
51
+ if @config.debugging
52
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
53
+ end
54
+
55
+ unless response.success?
56
+ fail ApiError.new(:code => response.code,
57
+ :response_headers => response.headers,
58
+ :response_body => response.body),
59
+ response.status_message
60
+ end
61
+
62
+ if opts[:return_type]
63
+ data = deserialize(response, opts[:return_type])
64
+ else
65
+ data = nil
66
+ end
67
+ return data, response.code, response.headers
68
+ end
69
+
70
+ def build_request(http_method, path, opts = {})
71
+ url = build_request_url(path)
72
+ http_method = http_method.to_sym.downcase
73
+
74
+ header_params = @default_headers.merge(opts[:header_params] || {})
75
+ query_params = opts[:query_params] || {}
76
+ form_params = opts[:form_params] || {}
77
+
78
+
79
+
80
+ req_opts = {
81
+ :method => http_method,
82
+ :headers => header_params,
83
+ :params => query_params,
84
+ :timeout => @config.timeout,
85
+ :ssl_verifypeer => @config.verify_ssl,
86
+ :sslcert => @config.cert_file,
87
+ :sslkey => @config.key_file,
88
+ :verbose => @config.debugging
89
+ }
90
+
91
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
92
+
93
+ if [:post, :patch, :put, :delete].include?(http_method)
94
+ req_body = build_request_body(header_params, form_params, opts[:body])
95
+ req_opts.update :body => req_body
96
+ if @config.debugging
97
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
98
+ end
99
+ end
100
+
101
+ Typhoeus::Request.new(url, req_opts)
102
+ end
103
+
104
+ # Check if the given MIME is a JSON MIME.
105
+ # JSON MIME examples:
106
+ # application/json
107
+ # application/json; charset=UTF8
108
+ # APPLICATION/JSON
109
+ def json_mime?(mime)
110
+ !!(mime =~ /\Aapplication\/json(;.*)?\z/i)
111
+ end
112
+
113
+ # Deserialize the response to the given return type.
114
+ #
115
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
116
+ def deserialize(response, return_type)
117
+ body = response.body
118
+ return nil if body.nil? || body.empty?
119
+
120
+ # return response body directly for String return type
121
+ return body if return_type == 'String'
122
+
123
+ # handle file downloading - save response body into a tmp file and return the File instance
124
+ return download_file(response) if return_type == 'File'
125
+
126
+ # ensuring a default content type
127
+ content_type = response.headers['Content-Type'] || 'application/json'
128
+
129
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
130
+
131
+ begin
132
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
133
+ rescue JSON::ParserError => e
134
+ if %w(String Date DateTime).include?(return_type)
135
+ data = body
136
+ else
137
+ raise e
138
+ end
139
+ end
140
+
141
+ convert_to_type data, return_type
142
+ end
143
+
144
+ # Convert data to the given return type.
145
+ def convert_to_type(data, return_type)
146
+ return nil if data.nil?
147
+ case return_type
148
+ when 'String'
149
+ data.to_s
150
+ when 'Integer'
151
+ data.to_i
152
+ when 'Float'
153
+ data.to_f
154
+ when 'BOOLEAN'
155
+ data == true
156
+ when 'DateTime'
157
+ # parse date time (expecting ISO 8601 format)
158
+ DateTime.parse data
159
+ when 'Date'
160
+ # parse date time (expecting ISO 8601 format)
161
+ Date.parse data
162
+ when 'Object'
163
+ # generic object, return directly
164
+ data
165
+ when /\AArray<(.+)>\z/
166
+ # e.g. Array<Pet>
167
+ sub_type = $1
168
+ data.map {|item| convert_to_type(item, sub_type) }
169
+ when /\AHash\<String, (.+)\>\z/
170
+ # e.g. Hash<String, Integer>
171
+ sub_type = $1
172
+ {}.tap do |hash|
173
+ data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
174
+ end
175
+ else
176
+ # models, e.g. Pet
177
+ IronTitan.const_get(return_type).new.tap do |model|
178
+ model.build_from_hash data
179
+ end
180
+ end
181
+ end
182
+
183
+ # Save response body into a file in (the defined) temporary folder, using the filename
184
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
185
+ #
186
+ # @see Configuration#temp_folder_path
187
+ # @return [Tempfile] the file downloaded
188
+ def download_file(response)
189
+ content_disposition = response.headers['Content-Disposition']
190
+ if content_disposition
191
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
192
+ prefix = sanitize_filename(filename)
193
+ else
194
+ prefix = 'download-'
195
+ end
196
+ prefix = prefix + '-' unless prefix.end_with?('-')
197
+
198
+ tempfile = nil
199
+ encoding = response.body.encoding
200
+ Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) do |file|
201
+ file.write(response.body)
202
+ tempfile = file
203
+ end
204
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
205
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
206
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
207
+ "explicitly with `tempfile.delete`"
208
+ tempfile
209
+ end
210
+
211
+ # Sanitize filename by removing path.
212
+ # e.g. ../../sun.gif becomes sun.gif
213
+ #
214
+ # @param [String] filename the filename to be sanitized
215
+ # @return [String] the sanitized filename
216
+ def sanitize_filename(filename)
217
+ filename.gsub /.*[\/\\]/, ''
218
+ end
219
+
220
+ def build_request_url(path)
221
+ # Add leading and trailing slashes to path
222
+ path = "/#{path}".gsub(/\/+/, '/')
223
+ URI.encode(@config.base_url + path)
224
+ end
225
+
226
+ def build_request_body(header_params, form_params, body)
227
+ # http form
228
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
229
+ header_params['Content-Type'] == 'multipart/form-data'
230
+ data = {}
231
+ form_params.each do |key, value|
232
+ case value
233
+ when File, Array, nil
234
+ # let typhoeus handle File, Array and nil parameters
235
+ data[key] = value
236
+ else
237
+ data[key] = value.to_s
238
+ end
239
+ end
240
+ elsif body
241
+ data = body.is_a?(String) ? body : body.to_json
242
+ else
243
+ data = nil
244
+ end
245
+ data
246
+ end
247
+
248
+ # Update hearder and query params based on authentication settings.
249
+ def update_params_for_auth!(header_params, query_params, auth_names)
250
+ Array(auth_names).each do |auth_name|
251
+ auth_setting = @config.auth_settings[auth_name]
252
+ next unless auth_setting
253
+ case auth_setting[:in]
254
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
255
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
256
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
257
+ end
258
+ end
259
+ end
260
+
261
+ def user_agent=(user_agent)
262
+ @user_agent = user_agent
263
+ @default_headers['User-Agent'] = @user_agent
264
+ end
265
+
266
+ # Return Accept header based on an array of accepts provided.
267
+ # @param [Array] accepts array for Accept
268
+ # @return [String] the Accept header (e.g. application/json)
269
+ def select_header_accept(accepts)
270
+ return nil if accepts.nil? || accepts.empty?
271
+ # use JSON when present, otherwise use all of the provided
272
+ json_accept = accepts.find { |s| json_mime?(s) }
273
+ return json_accept || accepts.join(',')
274
+ end
275
+
276
+ # Return Content-Type header based on an array of content types provided.
277
+ # @param [Array] content_types array for Content-Type
278
+ # @return [String] the Content-Type header (e.g. application/json)
279
+ def select_header_content_type(content_types)
280
+ # use application/json by default
281
+ return 'application/json' if content_types.nil? || content_types.empty?
282
+ # use JSON when present, otherwise use the first one
283
+ json_content_type = content_types.find { |s| json_mime?(s) }
284
+ return json_content_type || content_types.first
285
+ end
286
+
287
+ # Convert object (array, hash, object, etc) to JSON string.
288
+ # @param [Object] model object to be converted into JSON string
289
+ # @return [String] JSON string representation of the object
290
+ def object_to_http_body(model)
291
+ return model if model.nil? || model.is_a?(String)
292
+ _body = nil
293
+ if model.is_a?(Array)
294
+ _body = model.map{|m| object_to_hash(m) }
295
+ else
296
+ _body = object_to_hash(model)
297
+ end
298
+ _body.to_json
299
+ end
300
+
301
+ # Convert object(non-array) to hash.
302
+ # @param [Object] obj object to be converted into JSON string
303
+ # @return [String] JSON string representation of the object
304
+ def object_to_hash(obj)
305
+ if obj.respond_to?(:to_hash)
306
+ obj.to_hash
307
+ else
308
+ obj
309
+ end
310
+ end
311
+
312
+ # Build parameter value according to the given collection format.
313
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
314
+ def build_collection_param(param, collection_format)
315
+ case collection_format
316
+ when :csv
317
+ param.join(',')
318
+ when :ssv
319
+ param.join(' ')
320
+ when :tsv
321
+ param.join("\t")
322
+ when :pipes
323
+ param.join('|')
324
+ when :multi
325
+ # return the array directly as typhoeus will handle it as expected
326
+ param
327
+ else
328
+ fail "unknown collection format: #{collection_format.inspect}"
329
+ end
330
+ end
331
+ end
332
+ end
@@ -0,0 +1,36 @@
1
+ =begin
2
+ Titan API
3
+
4
+ The ultimate, language agnostic, container based job processing framework.
5
+
6
+ OpenAPI spec version: 0.0.1
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+
11
+ =end
12
+
13
+ module IronTitan
14
+ class ApiError < StandardError
15
+ attr_reader :code, :response_headers, :response_body
16
+
17
+ # Usage examples:
18
+ # ApiError.new
19
+ # ApiError.new("message")
20
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
21
+ # ApiError.new(:code => 404, :message => "Not Found")
22
+ def initialize(arg = nil)
23
+ if arg.is_a? Hash
24
+ arg.each do |k, v|
25
+ if k.to_s == 'message'
26
+ super v
27
+ else
28
+ instance_variable_set "@#{k}", v
29
+ end
30
+ end
31
+ else
32
+ super arg
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,163 @@
1
+ require 'uri'
2
+
3
+ module IronTitan
4
+ class Configuration
5
+ # Defines url scheme
6
+ attr_accessor :scheme
7
+
8
+ # Defines url host
9
+ attr_accessor :host
10
+
11
+ # Defines url base path
12
+ attr_accessor :base_path
13
+
14
+ # Defines API keys used with API Key authentications.
15
+ #
16
+ # @return [Hash] key: parameter name, value: parameter value (API key)
17
+ #
18
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
19
+ # config.api_key['api_key'] = 'xxx'
20
+ attr_accessor :api_key
21
+
22
+ # Defines API key prefixes used with API Key authentications.
23
+ #
24
+ # @return [Hash] key: parameter name, value: API key prefix
25
+ #
26
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
27
+ # config.api_key_prefix['api_key'] = 'Token'
28
+ attr_accessor :api_key_prefix
29
+
30
+ # Defines the username used with HTTP basic authentication.
31
+ #
32
+ # @return [String]
33
+ attr_accessor :username
34
+
35
+ # Defines the password used with HTTP basic authentication.
36
+ #
37
+ # @return [String]
38
+ attr_accessor :password
39
+
40
+ # Defines the access token (Bearer) used with OAuth2.
41
+ attr_accessor :access_token
42
+
43
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
44
+ # details will be logged with `logger.debug` (see the `logger` attribute).
45
+ # Default to false.
46
+ #
47
+ # @return [true, false]
48
+ attr_accessor :debugging
49
+
50
+ # Defines the logger used for debugging.
51
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
52
+ #
53
+ # @return [#debug]
54
+ attr_accessor :logger
55
+
56
+ # Defines the temporary folder to store downloaded files
57
+ # (for API endpoints that have file response).
58
+ # Default to use `Tempfile`.
59
+ #
60
+ # @return [String]
61
+ attr_accessor :temp_folder_path
62
+
63
+ # The time limit for HTTP request in seconds.
64
+ # Default to 0 (never times out).
65
+ attr_accessor :timeout
66
+
67
+ ### TLS/SSL
68
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
69
+ # Default to true.
70
+ #
71
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
72
+ #
73
+ # @return [true, false]
74
+ attr_accessor :verify_ssl
75
+
76
+ # Set this to customize the certificate file to verify the peer.
77
+ #
78
+ # @return [String] the path to the certificate file
79
+ #
80
+ # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
81
+ # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
82
+ attr_accessor :ssl_ca_cert
83
+
84
+ # Client certificate file (for client certificate)
85
+ attr_accessor :cert_file
86
+
87
+ # Client private key file (for client certificate)
88
+ attr_accessor :key_file
89
+
90
+ attr_accessor :inject_format
91
+
92
+ attr_accessor :force_ending_format
93
+
94
+ def initialize
95
+ @scheme = 'https'
96
+ @host = '192.168.99.100:8080'
97
+ @base_path = '/v1'
98
+ @api_key = {}
99
+ @api_key_prefix = {}
100
+ @timeout = 0
101
+ @verify_ssl = true
102
+ @cert_file = nil
103
+ @key_file = nil
104
+ @debugging = false
105
+ @inject_format = false
106
+ @force_ending_format = false
107
+ @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
108
+
109
+ yield(self) if block_given?
110
+ end
111
+
112
+ # The default Configuration object.
113
+ def self.default
114
+ @@default ||= Configuration.new
115
+ end
116
+
117
+ def configure
118
+ yield(self) if block_given?
119
+ end
120
+
121
+ def scheme=(scheme)
122
+ # remove :// from scheme
123
+ @scheme = scheme.sub(/:\/\//, '')
124
+ end
125
+
126
+ def host=(host)
127
+ # remove http(s):// and anything after a slash
128
+ @host = host.sub(/https?:\/\//, '').split('/').first
129
+ end
130
+
131
+ def base_path=(base_path)
132
+ # Add leading and trailing slashes to base_path
133
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
134
+ @base_path = "" if @base_path == "/"
135
+ end
136
+
137
+ def base_url
138
+ url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
139
+ URI.encode(url)
140
+ end
141
+
142
+ # Gets API key (with prefix if set).
143
+ # @param [String] param_name the parameter name of API key auth
144
+ def api_key_with_prefix(param_name)
145
+ if @api_key_prefix[param_name]
146
+ "#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
147
+ else
148
+ @api_key[param_name]
149
+ end
150
+ end
151
+
152
+ # Gets Basic Auth token string
153
+ def basic_auth_token
154
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
155
+ end
156
+
157
+ # Returns Auth Settings hash for api client.
158
+ def auth_settings
159
+ {
160
+ }
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,158 @@
1
+ =begin
2
+ Titan API
3
+
4
+ The ultimate, language agnostic, container based job processing framework.
5
+
6
+ OpenAPI spec version: 0.0.1
7
+
8
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
9
+
10
+
11
+ =end
12
+
13
+ require 'date'
14
+
15
+ module IronTitan
16
+ class Error
17
+ attr_accessor :error
18
+
19
+ # Attribute mapping from ruby-style variable name to JSON key.
20
+ def self.attribute_map
21
+ {
22
+
23
+ :'error' => :'error'
24
+
25
+ }
26
+ end
27
+
28
+ # Attribute type mapping.
29
+ def self.swagger_types
30
+ {
31
+ :'error' => :'ErrorBody'
32
+
33
+ }
34
+ end
35
+
36
+ def initialize(attributes = {})
37
+ return unless attributes.is_a?(Hash)
38
+
39
+ # convert string to symbol for hash key
40
+ attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
41
+
42
+
43
+ if attributes[:'error']
44
+ self.error = attributes[:'error']
45
+ end
46
+
47
+ end
48
+
49
+ # Check equality by comparing each attribute.
50
+ def ==(o)
51
+ return true if self.equal?(o)
52
+ self.class == o.class &&
53
+ error == o.error
54
+ end
55
+
56
+ # @see the `==` method
57
+ def eql?(o)
58
+ self == o
59
+ end
60
+
61
+ # Calculate hash code according to all attributes.
62
+ def hash
63
+ [error].hash
64
+ end
65
+
66
+ # build the object from hash
67
+ def build_from_hash(attributes)
68
+ return nil unless attributes.is_a?(Hash)
69
+ self.class.swagger_types.each_pair do |key, type|
70
+ if type =~ /^Array<(.*)>/i
71
+ if attributes[self.class.attribute_map[key]].is_a?(Array)
72
+ self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
73
+ else
74
+ #TODO show warning in debug mode
75
+ end
76
+ elsif !attributes[self.class.attribute_map[key]].nil?
77
+ self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
78
+ else
79
+ # data not found in attributes(hash), not an issue as the data can be optional
80
+ end
81
+ end
82
+
83
+ self
84
+ end
85
+
86
+ def _deserialize(type, value)
87
+ case type.to_sym
88
+ when :DateTime
89
+ DateTime.parse(value)
90
+ when :Date
91
+ Date.parse(value)
92
+ when :String
93
+ value.to_s
94
+ when :Integer
95
+ value.to_i
96
+ when :Float
97
+ value.to_f
98
+ when :BOOLEAN
99
+ if value =~ /^(true|t|yes|y|1)$/i
100
+ true
101
+ else
102
+ false
103
+ end
104
+ when /\AArray<(?<inner_type>.+)>\z/
105
+ inner_type = Regexp.last_match[:inner_type]
106
+ value.map { |v| _deserialize(inner_type, v) }
107
+ when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
108
+ k_type = Regexp.last_match[:k_type]
109
+ v_type = Regexp.last_match[:v_type]
110
+ {}.tap do |hash|
111
+ value.each do |k, v|
112
+ hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
113
+ end
114
+ end
115
+ else # model
116
+ _model = IronTitan.const_get(type).new
117
+ _model.build_from_hash(value)
118
+ end
119
+ end
120
+
121
+ def to_s
122
+ to_hash.to_s
123
+ end
124
+
125
+ # to_body is an alias to to_body (backward compatibility))
126
+ def to_body
127
+ to_hash
128
+ end
129
+
130
+ # return the object in the form of hash
131
+ def to_hash
132
+ hash = {}
133
+ self.class.attribute_map.each_pair do |attr, param|
134
+ value = self.send(attr)
135
+ next if value.nil?
136
+ hash[param] = _to_hash(value)
137
+ end
138
+ hash
139
+ end
140
+
141
+ # Method to output non-array value in the form of hash
142
+ # For object, use to_hash. Otherwise, just return the value
143
+ def _to_hash(value)
144
+ if value.is_a?(Array)
145
+ value.compact.map{ |v| _to_hash(v) }
146
+ elsif value.is_a?(Hash)
147
+ {}.tap do |hash|
148
+ value.each { |k, v| hash[k] = _to_hash(v) }
149
+ end
150
+ elsif value.respond_to? :to_hash
151
+ value.to_hash
152
+ else
153
+ value
154
+ end
155
+ end
156
+
157
+ end
158
+ end