# Generated by API Builder - https://www.apibuilder.io # Service version: 1.0.0 # User agent: apibuilder app.apibuilder.io/teambytes/hipchat-sns-bridge/1.0.0/ruby_client require 'cgi' require 'net/http' require 'net/https' require 'uri' require 'base64' require 'date' require 'rubygems' require 'json' require 'bigdecimal' # Hipchat to Amazon SNS bridge. module Com module Teambytes module Hipchat module Sns module Bridge module V1 class Client module Constants BASE_URL = 'http://hipchat-sns-bridge.common.giltaws.com' unless defined?(Constants::BASE_URL) NAMESPACE = 'com.teambytes.hipchat.sns.bridge.v1' unless defined?(Constants::NAMESPACE) USER_AGENT = 'apibuilder app.apibuilder.io/teambytes/hipchat-sns-bridge/1.0.0/ruby_client' unless defined?(Constants::USER_AGENT) VERSION = '1.0.0' unless defined?(Constants::VERSION) VERSION_MAJOR = 1 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 # Creates an instance of the client using the base url specified in the API spec. def Client.at_base_url(opts={}) Client.new(Constants::BASE_URL, opts) 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 hipchat_capabilities_descriptors @hipchat_capabilities_descriptors ||= ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Clients::HipchatCapabilitiesDescriptors.new(self) end def hipchat_install_data @hipchat_install_data ||= ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Clients::HipchatInstallData.new(self) end def service_info @service_info ||= ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Clients::ServiceInfo.new(self) end def sns_notifications @sns_notifications ||= ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Clients::SnsNotifications.new(self) end end module Clients class HipchatCapabilitiesDescriptors def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Client) end def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :redirect_to_hipchat_install => HttpClient::Preconditions.assert_boolean('redirect_to_hipchat_install', (x = opts.delete(:redirect_to_hipchat_install); x.nil? ? false : x)) }.delete_if { |k, v| v.nil? } r = @client.request("/hipchat/capabilities").with_query(query).get ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatCapabilitiesDescriptor.new(r) end end class HipchatInstallData def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Client) end def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :installable_url => HttpClient::Preconditions.assert_class('installable_url', opts.delete(:installable_url), String), :redirect_url => HttpClient::Preconditions.assert_class('redirect_url', opts.delete(:redirect_url), String) }.delete_if { |k, v| v.nil? } r = @client.request("/hipchat/installable").with_query(query).get ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatCapabilitiesDescriptor.new(r) end def post(hipchat_install_data) (x = hipchat_install_data; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatInstallData) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatInstallData.new(x)) r = @client.request("/hipchat/installable").with_json(hipchat_install_data.to_json).post nil end def delete_by_oauth_id(oauth_id) HttpClient::Preconditions.assert_class('oauth_id', oauth_id, String) r = @client.request("/hipchat/installable/#{CGI.escape(oauth_id)}").delete nil end end class ServiceInfo def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Client) end def get r = @client.request("/info").get ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::ServiceInfo.new(r) end end class SnsNotifications def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Client) end def post(room_id, sns_notification) HttpClient::Preconditions.assert_class('room_id', room_id, String) (x = sns_notification; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::SnsNotification) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::SnsNotification.new(x)) r = @client.request("/hipchat/room/#{CGI.escape(room_id)}/notification").with_json(sns_notification.to_json).post r end end end module Models class HipchatScope attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of HipchatScope for this value, creating a new instance for an unknown value def HipchatScope.apply(value) if value.instance_of?(HipchatScope) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || HipchatScope.new(value)) end end # Returns the instance of HipchatScope for this value, or nil if not found def HipchatScope.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) HipchatScope.ALL.find { |v| v.value == value } end def HipchatScope.ALL @@all ||= [HipchatScope.send_message, HipchatScope.send_notification] end def HipchatScope.send_message @@_send_message ||= HipchatScope.new('send_message') end def HipchatScope.send_notification @@_send_notification ||= HipchatScope.new('send_notification') end def to_hash value end end # A request semantic failure reason. class Error attr_reader :description def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:description], 'Error') @description = HttpClient::Preconditions.assert_class('description', opts.delete(:description), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Error.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :description => description } end end class HipchatApiConsumer attr_reader :scopes, :fromName def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:scopes], 'HipchatApiConsumer') @scopes = HttpClient::Preconditions.assert_class('scopes', opts.delete(:scopes), Array).map { |v| (x = v; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatScope) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatScope.apply(x)) } @fromName = (x = opts.delete(:fromName); x.nil? ? nil : HttpClient::Preconditions.assert_class('fromName', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatApiConsumer.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :scopes => scopes.map { |o| o.value }, :fromName => fromName } end end class HipchatCapabilities attr_reader :configurable, :hipchatApiConsumer, :installable, :oauth2Provider def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @configurable = (x = opts.delete(:configurable); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatConfigurationPage) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatConfigurationPage.new(x))) @hipchatApiConsumer = (x = opts.delete(:hipchatApiConsumer); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatApiConsumer) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatApiConsumer.new(x))) @installable = (x = opts.delete(:installable); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatInstallable) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatInstallable.new(x))) @oauth2Provider = (x = opts.delete(:oauth2Provider); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatOauth2Provider) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatOauth2Provider.new(x))) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatCapabilities.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :configurable => configurable.nil? ? nil : configurable.to_hash, :hipchatApiConsumer => hipchatApiConsumer.nil? ? nil : hipchatApiConsumer.to_hash, :installable => installable.nil? ? nil : installable.to_hash, :oauth2Provider => oauth2Provider.nil? ? nil : oauth2Provider.to_hash } end end class HipchatCapabilitiesDescriptor attr_reader :name, :description, :key, :apiVersion, :capabilities, :links, :vendor def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :description, :key, :links], 'HipchatCapabilitiesDescriptor') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @description = HttpClient::Preconditions.assert_class('description', opts.delete(:description), String) @key = HttpClient::Preconditions.assert_class('key', opts.delete(:key), String) @apiVersion = (x = opts.delete(:apiVersion); x.nil? ? nil : HttpClient::Preconditions.assert_class('apiVersion', x, String)) @capabilities = (x = opts.delete(:capabilities); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatCapabilities) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatCapabilities.new(x))) @links = (x = opts.delete(:links); x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatLinks) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatLinks.new(x)) @vendor = (x = opts.delete(:vendor); x.nil? ? nil : (x = x; x.is_a?(::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatVendor) ? x : ::Com::Teambytes::Hipchat::Sns::Bridge::V1::Models::HipchatVendor.new(x))) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatCapabilitiesDescriptor.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :description => description, :key => key, :apiVersion => apiVersion, :capabilities => capabilities.nil? ? nil : capabilities.to_hash, :links => links.to_hash, :vendor => vendor.nil? ? nil : vendor.to_hash } end end class HipchatConfigurationPage attr_reader :allowAccessToRoomAdmins, :url def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:url], 'HipchatConfigurationPage') @allowAccessToRoomAdmins = (x = opts.delete(:allowAccessToRoomAdmins); x.nil? ? nil : HttpClient::Preconditions.assert_class('allowAccessToRoomAdmins', x, String)) @url = HttpClient::Preconditions.assert_class('url', opts.delete(:url), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatConfigurationPage.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :allowAccessToRoomAdmins => allowAccessToRoomAdmins, :url => url } end end class HipchatInstallData attr_reader :capabilitiesUrl, :oauthId, :oauthSecret, :groupId, :roomId def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:capabilitiesUrl, :oauthId, :oauthSecret, :groupId], 'HipchatInstallData') @capabilitiesUrl = HttpClient::Preconditions.assert_class('capabilitiesUrl', opts.delete(:capabilitiesUrl), String) @oauthId = HttpClient::Preconditions.assert_class('oauthId', opts.delete(:oauthId), String) @oauthSecret = HttpClient::Preconditions.assert_class('oauthSecret', opts.delete(:oauthSecret), String) @groupId = HttpClient::Preconditions.assert_class('groupId', opts.delete(:groupId), Integer) @roomId = (x = opts.delete(:roomId); x.nil? ? nil : HttpClient::Preconditions.assert_class('roomId', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatInstallData.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :capabilitiesUrl => capabilitiesUrl, :oauthId => oauthId, :oauthSecret => oauthSecret, :groupId => groupId, :roomId => roomId } end end class HipchatInstallable attr_reader :callbackUrl, :installedUrl, :allowGlobal, :allowRoom def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @callbackUrl = (x = opts.delete(:callbackUrl); x.nil? ? nil : HttpClient::Preconditions.assert_class('callbackUrl', x, String)) @installedUrl = (x = opts.delete(:installedUrl); x.nil? ? nil : HttpClient::Preconditions.assert_class('installedUrl', x, String)) @allowGlobal = (x = opts.delete(:allowGlobal); x.nil? ? nil : HttpClient::Preconditions.assert_boolean('allowGlobal', x)) @allowRoom = (x = opts.delete(:allowRoom); x.nil? ? nil : HttpClient::Preconditions.assert_boolean('allowRoom', x)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatInstallable.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :callbackUrl => callbackUrl, :installedUrl => installedUrl, :allowGlobal => allowGlobal, :allowRoom => allowRoom } end end class HipchatLinks attr_reader :homepage, :api, :self def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:self], 'HipchatLinks') @homepage = (x = opts.delete(:homepage); x.nil? ? nil : HttpClient::Preconditions.assert_class('homepage', x, String)) @api = (x = opts.delete(:api); x.nil? ? nil : HttpClient::Preconditions.assert_class('api', x, String)) @self = HttpClient::Preconditions.assert_class('self', opts.delete(:self), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatLinks.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :homepage => homepage, :api => api, :self => self } end end class HipchatOauth2Provider attr_reader :tokenUrl, :authorizationUrl def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @tokenUrl = (x = opts.delete(:tokenUrl); x.nil? ? nil : HttpClient::Preconditions.assert_class('tokenUrl', x, String)) @authorizationUrl = (x = opts.delete(:authorizationUrl); x.nil? ? nil : HttpClient::Preconditions.assert_class('authorizationUrl', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatOauth2Provider.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :tokenUrl => tokenUrl, :authorizationUrl => authorizationUrl } end end class HipchatVendor attr_reader :name, :url def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :url], 'HipchatVendor') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @url = HttpClient::Preconditions.assert_class('url', opts.delete(:url), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) HipchatVendor.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :url => url } end end class ServiceInfo attr_reader :name, :version, :scala_version, :sbt_version, :build_time def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :version, :scala_version, :sbt_version, :build_time], 'ServiceInfo') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @version = HttpClient::Preconditions.assert_class('version', opts.delete(:version), String) @scala_version = HttpClient::Preconditions.assert_class('scala_version', opts.delete(:scala_version), String) @sbt_version = HttpClient::Preconditions.assert_class('sbt_version', opts.delete(:sbt_version), String) @build_time = HttpClient::Preconditions.assert_class('build_time', HttpClient::Helper.to_date_time_iso8601(opts.delete(:build_time)), DateTime) end def to_json JSON.dump(to_hash) end def copy(incoming={}) ServiceInfo.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :version => version, :scala_version => scala_version, :sbt_version => sbt_version, :build_time => build_time } end end class SnsNotification attr_reader :Type, :MessageId, :TopicArn, :Message, :Timestamp, :SignatureVersion, :Signature, :SigningCertURL, :Token, :Subject, :SubscribeURL, :UnsubscribeURL def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:Type, :MessageId, :TopicArn, :Message, :Timestamp, :SignatureVersion, :Signature, :SigningCertURL], 'SnsNotification') @Type = HttpClient::Preconditions.assert_class('Type', opts.delete(:Type), String) @MessageId = HttpClient::Preconditions.assert_class('MessageId', opts.delete(:MessageId), String) @TopicArn = HttpClient::Preconditions.assert_class('TopicArn', opts.delete(:TopicArn), String) @Message = HttpClient::Preconditions.assert_class('Message', opts.delete(:Message), String) @Timestamp = HttpClient::Preconditions.assert_class('Timestamp', opts.delete(:Timestamp), String) @SignatureVersion = HttpClient::Preconditions.assert_class('SignatureVersion', opts.delete(:SignatureVersion), String) @Signature = HttpClient::Preconditions.assert_class('Signature', opts.delete(:Signature), String) @SigningCertURL = HttpClient::Preconditions.assert_class('SigningCertURL', opts.delete(:SigningCertURL), String) @Token = (x = opts.delete(:Token); x.nil? ? nil : HttpClient::Preconditions.assert_class('Token', x, String)) @Subject = (x = opts.delete(:Subject); x.nil? ? nil : HttpClient::Preconditions.assert_class('Subject', x, String)) @SubscribeURL = (x = opts.delete(:SubscribeURL); x.nil? ? nil : HttpClient::Preconditions.assert_class('SubscribeURL', x, String)) @UnsubscribeURL = (x = opts.delete(:UnsubscribeURL); x.nil? ? nil : HttpClient::Preconditions.assert_class('UnsubscribeURL', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) SnsNotification.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :Type => Type, :MessageId => MessageId, :TopicArn => TopicArn, :Message => Message, :Timestamp => Timestamp, :SignatureVersion => SignatureVersion, :Signature => Signature, :SigningCertURL => SigningCertURL, :Token => Token, :Subject => Subject, :SubscribeURL => SubscribeURL, :UnsubscribeURL => UnsubscribeURL } 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