# Generated by API Builder - https://www.apibuilder.io # Service version: 0.0.1 # User agent: apibuilder app.apibuilder.io/nccloud/reporting-api/0.0.1/ruby_client require 'cgi' require 'net/http' require 'net/https' require 'uri' require 'base64' require 'date' require 'rubygems' require 'json' require 'bigdecimal' # Reporting service which aggregates events from dedicated Kafka topics. module De module Nccloud module Reporting module Api module V0 class Client module Constants NAMESPACE = 'de.nccloud.reporting.api.v0' unless defined?(Constants::NAMESPACE) USER_AGENT = 'apibuilder app.apibuilder.io/nccloud/reporting-api/0.0.1/ruby_client' unless defined?(Constants::USER_AGENT) VERSION = '0.0.1' unless defined?(Constants::VERSION) VERSION_MAJOR = 0 unless defined?(VERSION_MAJOR) end attr_reader :url def initialize(url, opts={}) @url = HttpClient::Preconditions.assert_class('url', url, String) @base_url = URI(url) @authorization = HttpClient::Preconditions.assert_class_or_nil('authorization', opts.delete(:authorization), HttpClient::Authorization) @default_headers = HttpClient::Preconditions.assert_class('default_headers', opts.delete(:default_headers) || {}, Hash) @http_handler = opts.delete(:http_handler) || HttpClient::DefaultHttpHandler.new HttpClient::Preconditions.assert_empty_opts(opts) HttpClient::Preconditions.check_state(url.match(/http.+/i), "URL[%s] must start with http" % url) end def request(path=nil) HttpClient::Preconditions.assert_class_or_nil('path', path, String) request = HttpClient::Request.new(@http_handler, @base_url, path.to_s).with_header('User-Agent', Constants::USER_AGENT).with_header('X-Apidoc-Version', Constants::VERSION).with_header('X-Apidoc-Version-Major', Constants::VERSION_MAJOR) @default_headers.each do |key, value| request = request.with_header(key, value) end if @authorization request = request.with_auth(@authorization) end request end def query_responses @query_responses ||= ::De::Nccloud::Reporting::Api::V0::Clients::QueryResponses.new(self) end def topics @topics ||= ::De::Nccloud::Reporting::Api::V0::Clients::Topics.new(self) end def views @views ||= ::De::Nccloud::Reporting::Api::V0::Clients::Views.new(self) end end module Clients class QueryResponses def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::De::Nccloud::Reporting::Api::V0::Client) end def post(query_form) (x = query_form; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::QueryForm) ? x : ::De::Nccloud::Reporting::Api::V0::Models::QueryForm.new(x)) r = @client.request("/query").with_json(query_form.to_json).post ::De::Nccloud::Reporting::Api::V0::Models::QueryResponse.new(r) end end class Topics def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::De::Nccloud::Reporting::Api::V0::Client) end def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :offset => HttpClient::Preconditions.assert_class('offset', (x = opts.delete(:offset); x.nil? ? 0 : x), Integer), :limit => HttpClient::Preconditions.assert_class('limit', (x = opts.delete(:limit); x.nil? ? 25 : x), Integer), :sort_by => HttpClient::Preconditions.assert_class('sort_by', (x = opts.delete(:sort_by); x.nil? ? "name" : x), String), :direction => (x = (x = opts.delete(:direction); x.nil? ? "asc" : x); x.is_a?(::De::Nccloud::Common::V0::Models::SortDirection) ? x : ::De::Nccloud::Common::V0::Models::SortDirection.apply(x)).value }.delete_if { |k, v| v.nil? } r = @client.request("/topics").with_query(query).get ::De::Nccloud::Reporting::Api::V0::Models::TopicResponse.new(r) end def get_by_guid(guid) HttpClient::Preconditions.assert_class('guid', guid, String) r = @client.request("/topics/#{CGI.escape(guid)}").get ::De::Nccloud::Reporting::Api::V0::Models::Topic.new(r) end end class Views def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::De::Nccloud::Reporting::Api::V0::Client) end def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :offset => HttpClient::Preconditions.assert_class('offset', (x = opts.delete(:offset); x.nil? ? 0 : x), Integer), :limit => HttpClient::Preconditions.assert_class('limit', (x = opts.delete(:limit); x.nil? ? 25 : x), Integer), :sort_by => HttpClient::Preconditions.assert_class('sort_by', (x = opts.delete(:sort_by); x.nil? ? "name" : x), String), :direction => (x = (x = opts.delete(:direction); x.nil? ? "asc" : x); x.is_a?(::De::Nccloud::Common::V0::Models::SortDirection) ? x : ::De::Nccloud::Common::V0::Models::SortDirection.apply(x)).value }.delete_if { |k, v| v.nil? } r = @client.request("/views").with_query(query).get ::De::Nccloud::Reporting::Api::V0::Models::ViewResponse.new(r) end def get_by_guid(guid) HttpClient::Preconditions.assert_class('guid', HttpClient::Helper.to_uuid(guid), String) r = @client.request("/views/#{guid}").get ::De::Nccloud::Reporting::Api::V0::Models::View.new(r) end def post(view_form) (x = view_form; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ViewForm) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ViewForm.new(x)) r = @client.request("/views").with_json(view_form.to_json).post ::De::Nccloud::Reporting::Api::V0::Models::View.new(r) end def put_by_guid(guid, view_form) HttpClient::Preconditions.assert_class('guid', HttpClient::Helper.to_uuid(guid), String) (x = view_form; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ViewForm) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ViewForm.new(x)) r = @client.request("/views/#{guid}").with_json(view_form.to_json).put ::De::Nccloud::Reporting::Api::V0::Models::View.new(r) end def delete_by_guid(guid) HttpClient::Preconditions.assert_class('guid', HttpClient::Helper.to_uuid(guid), String) r = @client.request("/views/#{guid}").delete nil end end end module Models class ReportingEvent module Types UPDATE_EVENT = 'update_event' unless defined?(UPDATE_EVENT) DELETE_EVENT = 'delete_event' unless defined?(DELETE_EVENT) end attr_reader :type def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:type], 'ReportingEvent') @type = HttpClient::Preconditions.assert_class('type', opts.delete(:type), String) end def subtype_to_hash raise 'Cannot serialize an instance of reporting_event directly - must use one of the specific types: update_event, delete_event' end def to_hash subtype_to_hash.merge(:type => @type) end def ReportingEvent.from_json(hash) HttpClient::Preconditions.assert_class('hash', hash, Hash) discriminator = HttpClient::Helper.symbolize_keys(hash)[:type].to_s.strip if discriminator.empty? raise "Union type[reporting_event] requires a field named 'type'" end case discriminator when Types::UPDATE_EVENT; UpdateEvent.new(hash) when Types::DELETE_EVENT; DeleteEvent.new(hash) else ReportingEventUndefinedType.new(:type => discriminator) end end end class ReportingEventUndefinedType < ReportingEvent attr_reader :name def initialize(incoming={}) super(:type => 'undefined_type') opts = HttpClient::Helper.symbolize_keys(incoming) @name = HttpClient::Preconditions.assert_class('name', opts.delete(:type), String) end def subtype_to_hash raise 'Unable to serialize undefined type to json' end def copy(incoming={}) raise 'Operation not supported for undefined type' end def to_hash raise 'Operation not supported for undefined type' end end class ScalarType attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of ScalarType for this value, creating a new instance for an unknown value def ScalarType.apply(value) if value.instance_of?(ScalarType) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || ScalarType.new(value)) end end # Returns the instance of ScalarType for this value, or nil if not found def ScalarType.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) ScalarType.ALL.find { |v| v.value == value } end def ScalarType.ALL @@all ||= [ScalarType.boolean, ScalarType.date_iso8601, ScalarType.date_time_iso8601, ScalarType.decimal, ScalarType.double, ScalarType.integer, ScalarType.long, ScalarType.string, ScalarType.uuid, ScalarType.object] end def ScalarType.boolean @@_boolean ||= ScalarType.new('boolean') end def ScalarType.date_iso8601 @@_date_iso8601 ||= ScalarType.new('date-iso8601') end def ScalarType.date_time_iso8601 @@_date_time_iso8601 ||= ScalarType.new('date-time-iso8601') end def ScalarType.decimal @@_decimal ||= ScalarType.new('decimal') end def ScalarType.double @@_double ||= ScalarType.new('double') end def ScalarType.integer @@_integer ||= ScalarType.new('integer') end def ScalarType.long @@_long ||= ScalarType.new('long') end def ScalarType.string @@_string ||= ScalarType.new('string') end def ScalarType.uuid @@_uuid ||= ScalarType.new('uuid') end # Note: when a type is set to `object`, the additional fields **must** be # defined in the schema. def ScalarType.object @@_object ||= ScalarType.new('object') end def to_hash value end end # Deletes a reporting entity defined by its `tracking_id`. class DeleteEvent < ReportingEvent attr_reader :tracking_id, :audit def initialize(incoming={}) super(:type => ReportingEvent::Types::DELETE_EVENT) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:tracking_id, :audit], 'DeleteEvent') @tracking_id = HttpClient::Preconditions.assert_class('tracking_id', opts.delete(:tracking_id), String) @audit = (x = opts.delete(:audit); x.is_a?(::De::Nccloud::Common::V0::Models::Audit) ? x : ::De::Nccloud::Common::V0::Models::Audit.new(x)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) DeleteEvent.new(subtype_to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def subtype_to_hash { :tracking_id => tracking_id, :audit => audit.to_hash } end end # Single field of a topic schema. A field can be used for projecting, filtering # and sorting in reports. class Field attr_reader :type, :is_array, :fields, :label, :description def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:type, :is_array], 'Field') @type = (x = opts.delete(:type); x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ScalarType) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ScalarType.apply(x)) @is_array = HttpClient::Preconditions.assert_boolean('is_array', opts.delete(:is_array)) @fields = (x = opts.delete(:fields); x.nil? ? nil : HttpClient::Preconditions.assert_class('fields', x, Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::Field) ? x : ::De::Nccloud::Reporting::Api::V0::Models::Field.new(x)); h }) @label = (x = opts.delete(:label); x.nil? ? nil : HttpClient::Preconditions.assert_class('label', x, String)) @description = (x = opts.delete(:description); x.nil? ? nil : HttpClient::Preconditions.assert_class('description', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Field.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :type => type.value, :is_array => is_array, :fields => fields.nil? ? nil : fields.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash }, :label => label, :description => description } end end # Defines a condition for values. class Filter attr_reader :expression, :variables def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @expression = (x = opts.delete(:expression); x.nil? ? nil : HttpClient::Preconditions.assert_class('expression', x, String)) @variables = (x = opts.delete(:variables); x.nil? ? nil : HttpClient::Preconditions.assert_class('variables', x, Hash).inject({}) { |h, d| h[d[0]] = HttpClient::Preconditions.assert_class('variables', d[1], BasicObject); h }) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Filter.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :expression => expression, :variables => variables.nil? ? nil : variables } end end # A single field of a projection schema. class ProjectionField attr_reader :label, :description, :source, :fields def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @label = (x = opts.delete(:label); x.nil? ? nil : HttpClient::Preconditions.assert_class('label', x, String)) @description = (x = opts.delete(:description); x.nil? ? nil : HttpClient::Preconditions.assert_class('description', x, String)) @source = (x = opts.delete(:source); x.nil? ? nil : (x = x; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ProjectionFieldSource) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ProjectionFieldSource.new(x))) @fields = (x = opts.delete(:fields); x.nil? ? nil : HttpClient::Preconditions.assert_class('fields', x, Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ProjectionField) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ProjectionField.new(x)); h }) end def to_json JSON.dump(to_hash) end def copy(incoming={}) ProjectionField.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :label => label, :description => description, :source => source.nil? ? nil : source.to_hash, :fields => fields.nil? ? nil : fields.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash } } end end # Represents the source for a single projection field from a topic's schema. class ProjectionFieldSource attr_reader :topic, :path, :filter def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:topic, :path, :filter], 'ProjectionFieldSource') @topic = HttpClient::Preconditions.assert_class('topic', opts.delete(:topic), String) @path = HttpClient::Preconditions.assert_class('path', opts.delete(:path), String) @filter = HttpClient::Preconditions.assert_class('filter', opts.delete(:filter), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) ProjectionFieldSource.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :topic => topic, :path => path, :filter => filter } end end # Form for querying and projecting data. class QueryForm attr_reader :view, :projection, :variables, :sort def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:variables], 'QueryForm') @view = (x = opts.delete(:view); x.nil? ? nil : HttpClient::Preconditions.assert_class('view', x, String)) @projection = (x = opts.delete(:projection); x.nil? ? nil : HttpClient::Preconditions.assert_class('projection', x, Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ProjectionField) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ProjectionField.new(x)); h }) @variables = HttpClient::Preconditions.assert_class('variables', opts.delete(:variables), Hash).inject({}) { |h, d| h[d[0]] = HttpClient::Preconditions.assert_class('variables', d[1], BasicObject); h } @sort = (x = opts.delete(:sort); x.nil? ? nil : HttpClient::Preconditions.assert_class('sort', x, Array).map { |v| (x = v; x.is_a?(::De::Nccloud::Common::V0::Models::Sort) ? x : ::De::Nccloud::Common::V0::Models::Sort.new(x)) }) end def to_json JSON.dump(to_hash) end def copy(incoming={}) QueryForm.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :view => view, :projection => projection.nil? ? nil : projection.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash }, :variables => variables, :sort => sort.nil? ? nil : sort.map { |o| o.to_hash } } end end # The result of a query, returning data in a projected form. class QueryResponse attr_reader :page, :data def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:page, :data], 'QueryResponse') @page = (x = opts.delete(:page); x.is_a?(::De::Nccloud::Common::V0::Models::PageResponse) ? x : ::De::Nccloud::Common::V0::Models::PageResponse.new(x)) @data = HttpClient::Preconditions.assert_class('data', HttpClient::Helper.to_object(opts.delete(:data)), Hash) end def to_json JSON.dump(to_hash) end def copy(incoming={}) QueryResponse.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :page => page.to_hash, :data => data } end end # Represents a single topic, which will be consumed by the reporting service. class Topic attr_reader :name, :service, :schema def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :service, :schema], 'Topic') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @service = (x = opts.delete(:service); x.is_a?(::De::Nccloud::Common::V0::Models::ServiceInfo) ? x : ::De::Nccloud::Common::V0::Models::ServiceInfo.new(x)) @schema = HttpClient::Preconditions.assert_class('schema', opts.delete(:schema), Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::Field) ? x : ::De::Nccloud::Reporting::Api::V0::Models::Field.new(x)); h } end def to_json JSON.dump(to_hash) end def copy(incoming={}) Topic.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :service => service.to_hash, :schema => schema.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash } } end end class TopicResponse attr_reader :page, :data def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:page, :data], 'TopicResponse') @page = (x = opts.delete(:page); x.is_a?(::De::Nccloud::Common::V0::Models::PageResponse) ? x : ::De::Nccloud::Common::V0::Models::PageResponse.new(x)) @data = HttpClient::Preconditions.assert_class('data', opts.delete(:data), Array).map { |v| (x = v; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::Topic) ? x : ::De::Nccloud::Reporting::Api::V0::Models::Topic.new(x)) } end def to_json JSON.dump(to_hash) end def copy(incoming={}) TopicResponse.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :page => page.to_hash, :data => data.map { |o| o.to_hash } } end end # Updates one or more data fields. class UpdateEvent < ReportingEvent attr_reader :tracking_id, :payload, :audit def initialize(incoming={}) super(:type => ReportingEvent::Types::UPDATE_EVENT) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:tracking_id, :payload, :audit], 'UpdateEvent') @tracking_id = HttpClient::Preconditions.assert_class('tracking_id', opts.delete(:tracking_id), String) @payload = HttpClient::Preconditions.assert_class('payload', HttpClient::Helper.to_object(opts.delete(:payload)), Hash) @audit = (x = opts.delete(:audit); x.is_a?(::De::Nccloud::Common::V0::Models::Audit) ? x : ::De::Nccloud::Common::V0::Models::Audit.new(x)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) UpdateEvent.new(subtype_to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def subtype_to_hash { :tracking_id => tracking_id, :payload => payload, :audit => audit.to_hash } end end # A stored view containing data from one or more topics. class View attr_reader :guid, :name, :projection, :variables def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:guid, :name, :projection, :variables], 'View') @guid = HttpClient::Preconditions.assert_class('guid', HttpClient::Helper.to_uuid(opts.delete(:guid)), String) @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @projection = HttpClient::Preconditions.assert_class('projection', opts.delete(:projection), Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ProjectionField) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ProjectionField.new(x)); h } @variables = HttpClient::Preconditions.assert_class('variables', opts.delete(:variables), Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ScalarType) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ScalarType.apply(x)); h } end def to_json JSON.dump(to_hash) end def copy(incoming={}) View.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :guid => guid, :name => name, :projection => projection.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash }, :variables => variables.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].value; hash } } end end # Form for creating a new `view`. class ViewForm attr_reader :name, :projection, :variables def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :projection, :variables], 'ViewForm') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @projection = HttpClient::Preconditions.assert_class('projection', opts.delete(:projection), Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ProjectionField) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ProjectionField.new(x)); h } @variables = HttpClient::Preconditions.assert_class('variables', opts.delete(:variables), Hash).inject({}) { |h, d| h[d[0]] = (x = d[1]; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::ScalarType) ? x : ::De::Nccloud::Reporting::Api::V0::Models::ScalarType.apply(x)); h } end def to_json JSON.dump(to_hash) end def copy(incoming={}) ViewForm.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :projection => projection.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].to_hash; hash }, :variables => variables.inject({}) { |hash, o| hash[o[0]] = o[1].nil? ? nil : o[1].value; hash } } end end class ViewResponse attr_reader :page, :data def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:page, :data], 'ViewResponse') @page = (x = opts.delete(:page); x.is_a?(::De::Nccloud::Common::V0::Models::PageResponse) ? x : ::De::Nccloud::Common::V0::Models::PageResponse.new(x)) @data = HttpClient::Preconditions.assert_class('data', opts.delete(:data), Array).map { |v| (x = v; x.is_a?(::De::Nccloud::Reporting::Api::V0::Models::View) ? x : ::De::Nccloud::Reporting::Api::V0::Models::View.new(x)) } end def to_json JSON.dump(to_hash) end def copy(incoming={}) ViewResponse.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :page => page.to_hash, :data => data.map { |o| o.to_hash } } end end end # ===== END OF SERVICE DEFINITION ===== module HttpClient class HttpHandler # Returns a client instance to use # # @param base_uri The base URI for this API # @param path the Requested full http path (including any query strings) def instance(base_uri, path) raise "Override in subclass" end end class HttpHandlerInstance # Executes a request. The provided request object will be an # instance of Net::HTTP (e.g. Net::HTTP::Get) def execute(request) raise "Override in subclass" end end class DefaultHttpHandler < HttpHandler def instance(base_uri, path) DefaultHttpHandlerInstance.new(base_uri) end end class DefaultHttpHandlerInstance < HttpHandlerInstance attr_reader :client def initialize(base_uri) @base_uri = Preconditions.assert_class('base_uri', base_uri, URI) @client = Net::HTTP.new(@base_uri.host, @base_uri.port) if @base_uri.scheme == "https" configure_ssl end end def execute(request) response = begin @client.request(request) rescue SocketError => e raise StandardError.new("Error accessing uri[#{full_uri(request.path)}]: #{e}") end case response when Net::HTTPSuccess response.body else body = response.body rescue nil raise HttpClient::ServerError.new(response.code.to_i, response.message, :body => body, :uri => full_uri(request.path).to_s) end end def full_uri(path) path.start_with?(@base_uri.to_s) ? path : File.join(@base_uri.to_s, path) end # Called to configure SSL if the base uri requires it def configure_ssl @client.use_ssl = true @client.verify_mode = OpenSSL::SSL::VERIFY_PEER @client.cert_store = OpenSSL::X509::Store.new @client.cert_store.set_default_paths end end class Request attr_reader :base_uri, :path, :full_uri def initialize(http_handler, base_uri, path) @http_handler = http_handler @base_uri = Preconditions.assert_class('base_uri', base_uri, URI) @path = Preconditions.assert_class('path', path, String) @full_uri = @base_uri.to_s + @path @params = nil @body = nil @auth = nil @headers = {} @header_keys_lower_case = [] end def with_header(name, value) Preconditions.check_not_blank('name', name, "Header name is required") Preconditions.check_not_blank('value', value, "Header value is required") Preconditions.check_state(!@headers.has_key?(name), "Duplicate header named[%s]" % name) @headers[name] = value @header_keys_lower_case << name.downcase self end def with_auth(auth) Preconditions.assert_class('auth', auth, HttpClient::Authorization) Preconditions.check_state(@auth.nil?, "auth previously set") if auth.scheme.name == AuthScheme::BASIC.name @auth = auth else raise "Auth Scheme[#{auth.scheme.name}] not supported" end self end def with_query(params) Preconditions.assert_class('params', params, Hash) Preconditions.check_state(@params.nil?, "Already have query parameters") @params = params self end # Wrapper to set Content-Type header to application/json and set # the provided json document as the body def with_json(json) @headers['Content-Type'] ||= 'application/json; charset=UTF-8' with_body(json) end def with_body(body) Preconditions.check_not_blank('body', body) @body = body self end def get(&block) do_request(Net::HTTP::Get, &block) end def delete(&block) do_request(Net::HTTP::Delete, &block) end def options(&block) do_request(Net::HTTP::Options, &block) end def post(&block) do_request(Net::HTTP::Post, &block) end def put(&block) do_request(Net::HTTP::Put, &block) end class PATCH < Net::HTTP::Put METHOD = "PATCH" end def patch(&block) do_request(PATCH, &block) end def do_request(klass) Preconditions.assert_class('klass', klass, Class) uri = @full_uri.dup if q = to_query(@params) uri += "?%s" % q end request = klass.send(:new, uri) # DEBUG curl = ['curl'] # DEBUG if klass != Net::HTTP::Get # DEBUG curl << "-X%s" % klass.name.split("::").last.upcase # DEBUG end if @body # DEBUG tmpfile = "/tmp/rest_client.tmp" # DEBUG File.open(tmpfile, "w") { |os| os << @body.to_s } # DEBUG curl << "-d@%s" % tmpfile request.body = @body end if @auth # DEBUG curl << "-u \"%s:%s\"" % [@auth.username, @auth.password] Preconditions.check_state(!@header_keys_lower_case.include?("authorization"), "Cannot specify both an Authorization header and an auth instance") user_pass = "%s:%s" % [@auth.username, @auth.password] encoded = Base64.encode64(user_pass).to_s.split("\n").map(&:strip).join request.add_field("Authorization", "Basic %s" % encoded) end @headers.each { |key, value| # DEBUG curl << "-H \"%s: %s\"" % [key, value] request.add_field(key, value) } # DEBUG curl << "'%s%s'" % [@base_uri, path] # DEBUG puts curl.join(" ") raw_response = @http_handler.instance(@base_uri, request.path).execute(request) response = raw_response.to_s == "" ? nil : JSON.parse(raw_response) if block_given? yield response else response end end private def to_query(params={}) parts = (params || {}).map { |k,v| if v.is_a?(Enumerable) v.map { |el| "%s=%s" % [k, CGI.escape(el.to_s)] } else "%s=%s" % [k, CGI.escape(v.to_s)] end } parts.empty? ? nil : parts.join("&") end end class ServerError < StandardError attr_reader :code, :details, :body, :uri def initialize(code, details, incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @code = HttpClient::Preconditions.assert_class('code', code, Integer) @details = HttpClient::Preconditions.assert_class('details', details, String) @body = HttpClient::Preconditions.assert_class_or_nil('body', opts.delete(:body), String) @uri = HttpClient::Preconditions.assert_class_or_nil('uri', opts.delete(:uri), String) HttpClient::Preconditions.assert_empty_opts(opts) super(self.message) end def message m = "%s %s" % [@code, @details] if @body m << ": %s" % @body end m end def body_json @body ? JSON.parse(@body) : nil end end class PreconditionException < StandardError attr_reader :message def initialize(message) super(message) @message = message end end module Preconditions def Preconditions.check_argument(expression, error_message=nil) if !expression raise PreconditionException.new(error_message || "check_argument failed") end nil end def Preconditions.check_state(expression, error_message=nil) if !expression raise PreconditionException.new(error_message || "check_state failed") end nil end def Preconditions.check_not_nil(field_name, reference, error_message=nil) if reference.nil? raise PreconditionException.new(error_message || "argument for %s cannot be nil" % field_name) end reference end def Preconditions.check_not_blank(field_name, reference, error_message=nil) if reference.to_s.strip == "" raise PreconditionException.new(error_message || "argument for %s cannot be blank" % field_name) end reference end # Throws an error if opts is not empty. Useful when parsing # arguments to a function def Preconditions.assert_empty_opts(opts) if !opts.empty? raise PreconditionException.new("Invalid opts: #{opts.keys.inspect}\n#{opts.inspect}") end end # Requires that the provided hash has the specified keys. # @param fields A list of symbols def Preconditions.require_keys(hash, fields, error_prefix=nil) missing = fields.select { |f| !hash.has_key?(f) } if !missing.empty? msg = "Missing required fields: " + missing.join(", ") raise PreconditionException.new(error_prefix.empty? ? msg : "#{error_prefix}: #{msg}") end end # Asserts that value is not nill and is_?(klass). Returns # value. Common use is # # amount = Preconditions.assert_class('amount', amount, BigDecimal) def Preconditions.assert_class(field_name, value, klass) Preconditions.check_not_nil('field_name', field_name) Preconditions.check_not_nil('klass', klass) Preconditions.check_not_nil('value', value, "Value for %s cannot be nil. Expected an instance of class %s" % [field_name, klass.name]) Preconditions.check_state(value.is_a?(klass), "Value for #{field_name} is of type[#{value.class}] - class[#{klass}] is required. value[#{value.inspect.to_s}]") value end def Preconditions.assert_class_or_nil(field_name, value, klass) if !value.nil? Preconditions.assert_class(field_name, value, klass) end end def Preconditions.assert_boolean(field_name, value) Preconditions.check_not_nil('field_name', field_name) Preconditions.check_not_nil('value', value, "Value for %s cannot be nil. Expected an instance of TrueClass or FalseClass" % field_name) Preconditions.check_state(value.is_a?(TrueClass) || value.is_a?(FalseClass), "Value for #{field_name} is of type[#{value.class}] - class[TrueClass or FalseClass] is required. value[#{value.inspect.to_s}]") value end def Preconditions.assert_boolean_or_nil(field_name, value) if !value.nil? Preconditions.assert_boolean(field_name, value) end end def Preconditions.assert_collection_of_class(field_name, values, klass) Preconditions.assert_class(field_name, values, Array) values.each { |v| Preconditions.assert_class(field_name, v, klass) } end def Preconditions.assert_hash_of_class(field_name, hash, klass) Preconditions.assert_class(field_name, hash, Hash) values.each { |k, v| Preconditions.assert_class(field_name, v, klass) } end end class AuthScheme attr_reader :name def initialize(name) @name = HttpClient::Preconditions.check_not_blank('name', name) end BASIC = AuthScheme.new("basic") unless defined?(BASIC) end class Authorization attr_reader :scheme, :username, :password def initialize(scheme, username, opts={}) @scheme = HttpClient::Preconditions.assert_class('schema', scheme, AuthScheme) @username = HttpClient::Preconditions.check_not_blank('username', username, "username is required") @password = HttpClient::Preconditions.assert_class_or_nil('password', opts.delete(:password), String) HttpClient::Preconditions.assert_empty_opts(opts) end def Authorization.basic(username, password=nil) Authorization.new(AuthScheme::BASIC, username, :password => password) end end module Helper def Helper.symbolize_keys(hash) Preconditions.assert_class('hash', hash, Hash) new_hash = {} hash.each { |k, v| new_hash[k.to_sym] = v } new_hash end def Helper.to_big_decimal(value) value ? BigDecimal(value.to_s) : nil end def Helper.to_object(value) value ? (value.is_a?(Hash) ? value : JSON.parse(value)) : nil end def Helper.to_uuid(value) Preconditions.check_state(value.nil? || value.match(/^\w\w\w\w\w\w\w\w\-\w\w\w\w\-\w\w\w\w\-\w\w\w\w\-\w\w\w\w\w\w\w\w\w\w\w\w$/), "Invalid guid[%s]" % value) value end def Helper.to_date_iso8601(value) if value.is_a?(Date) value elsif value Date.parse(value.to_s) else nil end end def Helper.to_date_time_iso8601(value) if value.is_a?(DateTime) value elsif value DateTime.parse(value.to_s) else nil end end def Helper.date_iso8601_to_string(value) value.nil? ? nil : value.strftime('%Y-%m-%d') end def Helper.date_time_iso8601_to_string(value) value.nil? ? nil : value.strftime('%Y-%m-%dT%H:%M:%S%z') end TRUE_STRINGS = ['t', 'true', 'y', 'yes', 'on', '1', 'trueclass'] unless defined?(TRUE_STRINGS) FALSE_STRINGS = ['f', 'false', 'n', 'no', 'off', '0', 'falseclass'] unless defined?(FALSE_STRINGS) def Helper.to_boolean(field_name, value) string = value.to_s.strip.downcase if TRUE_STRINGS.include?(string) true elsif FALSE_STRINGS.include?(string) false elsif string != "" raise PreconditionException.new("Unsupported boolean value[#{string}]. For true, must be one of: #{TRUE_STRINGS.inspect}. For false, must be one of: #{FALSE_STRINGS.inspect}") else nil end end end end end end end end end