# Generated by API Builder - https://www.apibuilder.io # Service version: 0.0.1-dev # User agent: apibuilder app.apibuilder.io/sullis/email-markup/0.0.1-dev/ruby_client require 'cgi' require 'net/http' require 'net/https' require 'uri' require 'base64' require 'date' require 'rubygems' require 'json' require 'bigdecimal' module Com module Github module Sullis module Email module Markup module V0 class Client module Constants NAMESPACE = 'com.github.sullis.email.markup.v0' unless defined?(Constants::NAMESPACE) USER_AGENT = 'apibuilder app.apibuilder.io/sullis/email-markup/0.0.1-dev/ruby_client' unless defined?(Constants::USER_AGENT) VERSION = '0.0.1-dev' 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 end module Clients end module Models class ActionTypes attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of ActionTypes for this value, creating a new instance for an unknown value def ActionTypes.apply(value) if value.instance_of?(ActionTypes) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || ActionTypes.new(value)) end end # Returns the instance of ActionTypes for this value, or nil if not found def ActionTypes.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) ActionTypes.ALL.find { |v| v.value == value } end def ActionTypes.ALL @@all ||= [ActionTypes.confirm_action, ActionTypes.save_action, ActionTypes.track_action, ActionTypes.view_action] end def ActionTypes.confirm_action @@_confirm_action ||= ActionTypes.new('ConfirmAction') end def ActionTypes.save_action @@_save_action ||= ActionTypes.new('SaveAction') end def ActionTypes.track_action @@_track_action ||= ActionTypes.new('TrackAction') end def ActionTypes.view_action @@_view_action ||= ActionTypes.new('ViewAction') end def to_hash value end end class ActionHandler attr_reader :at_type, :url def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:url], 'ActionHandler') @at_type = HttpClient::Preconditions.assert_class('at_type', (x = opts.delete(:at_type); x.nil? ? "HttpActionHandler" : x), String) @url = HttpClient::Preconditions.assert_class('url', opts.delete(:url), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) ActionHandler.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :at_type => at_type, :url => url } end end class Address attr_reader :addressCountry, :addressLocality, :addressRegion, :postalCode, :postOfficeBoxNumber, :streetAddress def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:addressCountry, :addressLocality, :addressRegion, :postalCode, :postOfficeBoxNumber, :streetAddress], 'Address') @addressCountry = HttpClient::Preconditions.assert_class('addressCountry', opts.delete(:addressCountry), String) @addressLocality = HttpClient::Preconditions.assert_class('addressLocality', opts.delete(:addressLocality), String) @addressRegion = HttpClient::Preconditions.assert_class('addressRegion', opts.delete(:addressRegion), String) @postalCode = HttpClient::Preconditions.assert_class('postalCode', opts.delete(:postalCode), String) @postOfficeBoxNumber = HttpClient::Preconditions.assert_class('postOfficeBoxNumber', opts.delete(:postOfficeBoxNumber), String) @streetAddress = HttpClient::Preconditions.assert_class('streetAddress', opts.delete(:streetAddress), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Address.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :addressCountry => addressCountry, :addressLocality => addressLocality, :addressRegion => addressRegion, :postalCode => postalCode, :postOfficeBoxNumber => postOfficeBoxNumber, :streetAddress => streetAddress } end end class Customer attr_reader :name def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name], 'Customer') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Customer.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name } end end class GotoAction attr_reader :at_context, :at_type, :potentialAction, :description def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:potentialAction, :description], 'GotoAction') @at_context = HttpClient::Preconditions.assert_class('at_context', (x = opts.delete(:at_context); x.nil? ? "http://schema.org" : x), String) @at_type = HttpClient::Preconditions.assert_class('at_type', (x = opts.delete(:at_type); x.nil? ? "EmailMessage" : x), String) @potentialAction = (x = opts.delete(:potentialAction); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PotentialAction) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PotentialAction.new(x)) @description = HttpClient::Preconditions.assert_class('description', opts.delete(:description), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) GotoAction.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :at_context => at_context, :at_type => at_type, :potentialAction => potentialAction.to_hash, :description => description } end end class Merchant attr_reader :name def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name], 'Merchant') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Merchant.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name } end end class Offer attr_reader :acceptedPaymentMethod, :addOn, :advanceBookingRequirement, :aggregateRating, :availability, :availabilityEnds, :availabilityStarts, :availableAtOrFrom, :availableDeliveryMethod, :businessFunction, :category, :deliveryLeadTime, :eligibleCustomerType, :eligibleDuration, :eligibleQuantity, :eligibleRegion, :eligibleTransactionVolume, :gtin13, :gtin14, :gtin8, :includesObject, :ineligibleRegion, :inventoryLevel, :itemCondition, :itemOffered, :mpn, :name, :price, :priceCurrency, :priceSpecification, :priceValidUntil, :seller, :serialNumber, :sku, :validFrom, :validThrough def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:itemOffered, :name, :price, :priceCurrency], 'Offer') @acceptedPaymentMethod = (x = opts.delete(:acceptedPaymentMethod); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PaymentMethod) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PaymentMethod.new(x))) @addOn = (x = opts.delete(:addOn); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Offer) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Offer.new(x))) @advanceBookingRequirement = (x = opts.delete(:advanceBookingRequirement); x.nil? ? nil : HttpClient::Preconditions.assert_class('advanceBookingRequirement', x, String)) @aggregateRating = (x = opts.delete(:aggregateRating); x.nil? ? nil : HttpClient::Preconditions.assert_class('aggregateRating', x, String)) @availability = (x = opts.delete(:availability); x.nil? ? nil : HttpClient::Preconditions.assert_class('availability', x, String)) @availabilityEnds = (x = opts.delete(:availabilityEnds); x.nil? ? nil : HttpClient::Preconditions.assert_class('availabilityEnds', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) @availabilityStarts = (x = opts.delete(:availabilityStarts); x.nil? ? nil : HttpClient::Preconditions.assert_class('availabilityStarts', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) @availableAtOrFrom = (x = opts.delete(:availableAtOrFrom); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Place) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Place.new(x))) @availableDeliveryMethod = (x = opts.delete(:availableDeliveryMethod); x.nil? ? nil : HttpClient::Preconditions.assert_class('availableDeliveryMethod', x, String)) @businessFunction = (x = opts.delete(:businessFunction); x.nil? ? nil : HttpClient::Preconditions.assert_class('businessFunction', x, String)) @category = (x = opts.delete(:category); x.nil? ? nil : HttpClient::Preconditions.assert_class('category', x, String)) @deliveryLeadTime = (x = opts.delete(:deliveryLeadTime); x.nil? ? nil : HttpClient::Preconditions.assert_class('deliveryLeadTime', x, String)) @eligibleCustomerType = (x = opts.delete(:eligibleCustomerType); x.nil? ? nil : HttpClient::Preconditions.assert_class('eligibleCustomerType', x, String)) @eligibleDuration = (x = opts.delete(:eligibleDuration); x.nil? ? nil : HttpClient::Preconditions.assert_class('eligibleDuration', x, String)) @eligibleQuantity = (x = opts.delete(:eligibleQuantity); x.nil? ? nil : HttpClient::Preconditions.assert_class('eligibleQuantity', x, String)) @eligibleRegion = (x = opts.delete(:eligibleRegion); x.nil? ? nil : HttpClient::Preconditions.assert_class('eligibleRegion', x, String)) @eligibleTransactionVolume = (x = opts.delete(:eligibleTransactionVolume); x.nil? ? nil : HttpClient::Preconditions.assert_class('eligibleTransactionVolume', x, String)) @gtin13 = (x = opts.delete(:gtin13); x.nil? ? nil : HttpClient::Preconditions.assert_class('gtin13', x, String)) @gtin14 = (x = opts.delete(:gtin14); x.nil? ? nil : HttpClient::Preconditions.assert_class('gtin14', x, String)) @gtin8 = (x = opts.delete(:gtin8); x.nil? ? nil : HttpClient::Preconditions.assert_class('gtin8', x, String)) @includesObject = (x = opts.delete(:includesObject); x.nil? ? nil : HttpClient::Preconditions.assert_class('includesObject', x, String)) @ineligibleRegion = (x = opts.delete(:ineligibleRegion); x.nil? ? nil : HttpClient::Preconditions.assert_class('ineligibleRegion', x, String)) @inventoryLevel = (x = opts.delete(:inventoryLevel); x.nil? ? nil : HttpClient::Preconditions.assert_class('inventoryLevel', x, String)) @itemCondition = (x = opts.delete(:itemCondition); x.nil? ? nil : HttpClient::Preconditions.assert_class('itemCondition', x, String)) @itemOffered = (x = opts.delete(:itemOffered); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Product) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Product.new(x)) @mpn = (x = opts.delete(:mpn); x.nil? ? nil : HttpClient::Preconditions.assert_class('mpn', x, String)) @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @price = HttpClient::Preconditions.assert_class('price', HttpClient::Helper.to_big_decimal(opts.delete(:price)), BigDecimal) @priceCurrency = HttpClient::Preconditions.assert_class('priceCurrency', opts.delete(:priceCurrency), String) @priceSpecification = (x = opts.delete(:priceSpecification); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PriceSpecification) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PriceSpecification.new(x))) @priceValidUntil = (x = opts.delete(:priceValidUntil); x.nil? ? nil : HttpClient::Preconditions.assert_class('priceValidUntil', x, String)) @seller = (x = opts.delete(:seller); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Organization) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Organization.new(x))) @serialNumber = (x = opts.delete(:serialNumber); x.nil? ? nil : HttpClient::Preconditions.assert_class('serialNumber', x, String)) @sku = (x = opts.delete(:sku); x.nil? ? nil : HttpClient::Preconditions.assert_class('sku', x, String)) @validFrom = (x = opts.delete(:validFrom); x.nil? ? nil : HttpClient::Preconditions.assert_class('validFrom', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) @validThrough = (x = opts.delete(:validThrough); x.nil? ? nil : HttpClient::Preconditions.assert_class('validThrough', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Offer.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :acceptedPaymentMethod => acceptedPaymentMethod.nil? ? nil : acceptedPaymentMethod.to_hash, :addOn => addOn.nil? ? nil : addOn.to_hash, :advanceBookingRequirement => advanceBookingRequirement, :aggregateRating => aggregateRating, :availability => availability, :availabilityEnds => availabilityEnds, :availabilityStarts => availabilityStarts, :availableAtOrFrom => availableAtOrFrom.nil? ? nil : availableAtOrFrom.to_hash, :availableDeliveryMethod => availableDeliveryMethod, :businessFunction => businessFunction, :category => category, :deliveryLeadTime => deliveryLeadTime, :eligibleCustomerType => eligibleCustomerType, :eligibleDuration => eligibleDuration, :eligibleQuantity => eligibleQuantity, :eligibleRegion => eligibleRegion, :eligibleTransactionVolume => eligibleTransactionVolume, :gtin13 => gtin13, :gtin14 => gtin14, :gtin8 => gtin8, :includesObject => includesObject, :ineligibleRegion => ineligibleRegion, :inventoryLevel => inventoryLevel, :itemCondition => itemCondition, :itemOffered => itemOffered.to_hash, :mpn => mpn, :name => name, :price => price.to_f.to_s, :priceCurrency => priceCurrency, :priceSpecification => priceSpecification.nil? ? nil : priceSpecification.to_hash, :priceValidUntil => priceValidUntil, :seller => seller.nil? ? nil : seller.to_hash, :serialNumber => serialNumber, :sku => sku, :validFrom => validFrom, :validThrough => validThrough } end end class OneClickAction attr_reader :at_context, :at_type, :potentialAction, :description def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:potentialAction, :description], 'OneClickAction') @at_context = HttpClient::Preconditions.assert_class('at_context', (x = opts.delete(:at_context); x.nil? ? "http://schema.org" : x), String) @at_type = HttpClient::Preconditions.assert_class('at_type', (x = opts.delete(:at_type); x.nil? ? "EmailMessage" : x), String) @potentialAction = (x = opts.delete(:potentialAction); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PotentialAction) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PotentialAction.new(x)) @description = HttpClient::Preconditions.assert_class('description', opts.delete(:description), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) OneClickAction.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :at_context => at_context, :at_type => at_type, :potentialAction => potentialAction.to_hash, :description => description } end end class Order attr_reader :billingAddress, :customer, :discount, :discountCurrency, :isGift, :merchant, :orderNumber, :priceCurrency, :priceSpecification, :price, :acceptedOffer, :url, :orderStatus, :paymentMethod, :paymentMethodId, :orderDate def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:customer, :merchant, :orderNumber, :priceCurrency, :price, :acceptedOffer, :url, :orderStatus, :paymentMethod, :paymentMethodId, :orderDate], 'Order') @billingAddress = (x = opts.delete(:billingAddress); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Address) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Address.new(x))) @customer = (x = opts.delete(:customer); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Customer) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Customer.new(x)) @discount = (x = opts.delete(:discount); x.nil? ? nil : HttpClient::Preconditions.assert_class('discount', HttpClient::Helper.to_big_decimal(x), BigDecimal)) @discountCurrency = (x = opts.delete(:discountCurrency); x.nil? ? nil : HttpClient::Preconditions.assert_class('discountCurrency', x, String)) @isGift = HttpClient::Preconditions.assert_boolean('isGift', (x = opts.delete(:isGift); x.nil? ? false : x)) @merchant = (x = opts.delete(:merchant); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Merchant) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Merchant.new(x)) @orderNumber = HttpClient::Preconditions.assert_class('orderNumber', opts.delete(:orderNumber), String) @priceCurrency = HttpClient::Preconditions.assert_class('priceCurrency', opts.delete(:priceCurrency), String) @priceSpecification = (x = opts.delete(:priceSpecification); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PriceSpecification) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PriceSpecification.new(x))) @price = HttpClient::Preconditions.assert_class('price', HttpClient::Helper.to_big_decimal(opts.delete(:price)), BigDecimal) @acceptedOffer = HttpClient::Preconditions.assert_class('acceptedOffer', opts.delete(:acceptedOffer), Array).map { |v| (x = v; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Offer) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Offer.new(x)) } @url = HttpClient::Preconditions.assert_class('url', opts.delete(:url), String) @orderStatus = HttpClient::Preconditions.assert_class('orderStatus', opts.delete(:orderStatus), String) @paymentMethod = (x = opts.delete(:paymentMethod); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::PaymentMethod) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::PaymentMethod.new(x)) @paymentMethodId = HttpClient::Preconditions.assert_class('paymentMethodId', opts.delete(:paymentMethodId), String) @orderDate = HttpClient::Preconditions.assert_class('orderDate', HttpClient::Helper.to_date_time_iso8601(opts.delete(:orderDate)), DateTime) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Order.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :billingAddress => billingAddress.nil? ? nil : billingAddress.to_hash, :customer => customer.to_hash, :discount => discount.to_f.to_s, :discountCurrency => discountCurrency, :isGift => isGift, :merchant => merchant.to_hash, :orderNumber => orderNumber, :priceCurrency => priceCurrency, :priceSpecification => priceSpecification.nil? ? nil : priceSpecification.to_hash, :price => price.to_f.to_s, :acceptedOffer => acceptedOffer.map { |o| o.to_hash }, :url => url, :orderStatus => orderStatus, :paymentMethod => paymentMethod.to_hash, :paymentMethodId => paymentMethodId, :orderDate => orderDate } end end class Organization attr_reader :address, :legal_name def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:address, :legal_name], 'Organization') @address = (x = opts.delete(:address); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Address) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Address.new(x)) @legal_name = HttpClient::Preconditions.assert_class('legal_name', opts.delete(:legal_name), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Organization.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :address => address.to_hash, :legal_name => legal_name } end end class PaymentMethod attr_reader :name def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @name = HttpClient::Preconditions.assert_class('name', (x = opts.delete(:name); x.nil? ? "http://schema.org/CreditCard" : x), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) PaymentMethod.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name } end end class Place attr_reader :address, :logo, :map, :telephone def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:address, :logo, :map, :telephone], 'Place') @address = (x = opts.delete(:address); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Address) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Address.new(x)) @logo = HttpClient::Preconditions.assert_class('logo', opts.delete(:logo), String) @map = HttpClient::Preconditions.assert_class('map', opts.delete(:map), String) @telephone = HttpClient::Preconditions.assert_class('telephone', opts.delete(:telephone), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Place.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :address => address.to_hash, :logo => logo, :map => map, :telephone => telephone } end end class PotentialAction attr_reader :at_type, :handler, :name, :target def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:at_type, :name, :target], 'PotentialAction') @at_type = (x = opts.delete(:at_type); x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::ActionTypes) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::ActionTypes.apply(x)) @handler = (x = opts.delete(:handler); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::ActionHandler) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::ActionHandler.new(x))) @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @target = HttpClient::Preconditions.assert_class('target', opts.delete(:target), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) PotentialAction.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :at_type => at_type.value, :handler => handler.nil? ? nil : handler.to_hash, :name => name, :target => target } end end class PriceSpecification attr_reader :eligibleQuantity, :eligibleTransactionVolume, :maxPrice, :minPrice, :price, :priceCurrency, :validFrom, :validThrough, :valueAddedTaxIncluded def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:eligibleQuantity, :eligibleTransactionVolume, :maxPrice, :minPrice, :price, :priceCurrency, :validFrom, :validThrough], 'PriceSpecification') @eligibleQuantity = HttpClient::Preconditions.assert_class('eligibleQuantity', opts.delete(:eligibleQuantity), String) @eligibleTransactionVolume = HttpClient::Preconditions.assert_class('eligibleTransactionVolume', opts.delete(:eligibleTransactionVolume), String) @maxPrice = HttpClient::Preconditions.assert_class('maxPrice', HttpClient::Helper.to_big_decimal(opts.delete(:maxPrice)), BigDecimal) @minPrice = HttpClient::Preconditions.assert_class('minPrice', HttpClient::Helper.to_big_decimal(opts.delete(:minPrice)), BigDecimal) @price = HttpClient::Preconditions.assert_class('price', HttpClient::Helper.to_big_decimal(opts.delete(:price)), BigDecimal) @priceCurrency = HttpClient::Preconditions.assert_class('priceCurrency', opts.delete(:priceCurrency), String) @validFrom = HttpClient::Preconditions.assert_class('validFrom', HttpClient::Helper.to_date_time_iso8601(opts.delete(:validFrom)), DateTime) @validThrough = HttpClient::Preconditions.assert_class('validThrough', HttpClient::Helper.to_date_time_iso8601(opts.delete(:validThrough)), DateTime) @valueAddedTaxIncluded = HttpClient::Preconditions.assert_boolean('valueAddedTaxIncluded', (x = opts.delete(:valueAddedTaxIncluded); x.nil? ? false : x)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) PriceSpecification.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :eligibleQuantity => eligibleQuantity, :eligibleTransactionVolume => eligibleTransactionVolume, :maxPrice => maxPrice.to_f.to_s, :minPrice => minPrice.to_f.to_s, :price => price.to_f.to_s, :priceCurrency => priceCurrency, :validFrom => validFrom, :validThrough => validThrough, :valueAddedTaxIncluded => valueAddedTaxIncluded } end end class Product attr_reader :productID, :sku, :brand, :manufacturer, :color def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:productID, :sku], 'Product') @productID = HttpClient::Preconditions.assert_class('productID', opts.delete(:productID), String) @sku = HttpClient::Preconditions.assert_class('sku', opts.delete(:sku), String) @brand = (x = opts.delete(:brand); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Organization) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Organization.new(x))) @manufacturer = (x = opts.delete(:manufacturer); x.nil? ? nil : (x = x; x.is_a?(::Com::Github::Sullis::Email::Markup::V0::Models::Organization) ? x : ::Com::Github::Sullis::Email::Markup::V0::Models::Organization.new(x))) @color = (x = opts.delete(:color); x.nil? ? nil : HttpClient::Preconditions.assert_class('color', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Product.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :productID => productID, :sku => sku, :brand => brand.nil? ? nil : brand.to_hash, :manufacturer => manufacturer.nil? ? nil : manufacturer.to_hash, :color => color } 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 end