# Generated by API Builder - https://www.apibuilder.io # Service version: 0.0.13 # User agent: apibuilder app.apibuilder.io/trifectalabs/roadquality/0.0.13/ruby_client require 'cgi' require 'net/http' require 'net/https' require 'uri' require 'base64' require 'date' require 'rubygems' require 'json' require 'bigdecimal' # Crowd-sourced road quality data module Com module Trifectalabs module Roadquality module V0 class Client module Constants NAMESPACE = 'com.trifectalabs.roadquality.v0' unless defined?(Constants::NAMESPACE) USER_AGENT = 'apibuilder app.apibuilder.io/trifectalabs/roadquality/0.0.13/ruby_client' unless defined?(Constants::USER_AGENT) VERSION = '0.0.13' 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 map_routes @map_routes ||= ::Com::Trifectalabs::Roadquality::V0::Clients::MapRoutes.new(self) end def segments @segments ||= ::Com::Trifectalabs::Roadquality::V0::Clients::Segments.new(self) end def segment_ratings @segment_ratings ||= ::Com::Trifectalabs::Roadquality::V0::Clients::SegmentRatings.new(self) end def users @users ||= ::Com::Trifectalabs::Roadquality::V0::Clients::Users.new(self) end def info @info ||= ::Com::Trifectalabs::Roadquality::V0::Clients::Info.new(self) end end module Clients class MapRoutes def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Trifectalabs::Roadquality::V0::Client) end def get_snap(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :lat => HttpClient::Preconditions.assert_class('lat', opts.delete(:lat), Numeric), :lng => HttpClient::Preconditions.assert_class('lng', opts.delete(:lng), Numeric) }.delete_if { |k, v| v.nil? } r = @client.request("/mapRoutes/snap").with_query(query).get ::Com::Trifectalabs::Roadquality::V0::Models::Point.new(r) end def get_by_points(points) HttpClient::Preconditions.assert_class('points', points, String) r = @client.request("/mapRoutes/#{CGI.escape(points)}").get ::Com::Trifectalabs::Roadquality::V0::Models::MapRoute.new(r) end end class Segments def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Trifectalabs::Roadquality::V0::Client) end # Search all segments def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :segmentId => (x = opts.delete(:segmentId); x.nil? ? nil : HttpClient::Preconditions.assert_class('segmentId', HttpClient::Helper.to_uuid(x), String)) }.delete_if { |k, v| v.nil? } r = @client.request("/segments").with_query(query).get r.map { |x| ::Com::Trifectalabs::Roadquality::V0::Models::Segment.new(x) } end # Search all segments within a bounding box def get_boundingbox(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :xmin => (x = opts.delete(:xmin); x.nil? ? nil : HttpClient::Preconditions.assert_class('xmin', x, Numeric)), :ymin => (x = opts.delete(:ymin); x.nil? ? nil : HttpClient::Preconditions.assert_class('ymin', x, Numeric)), :xmax => (x = opts.delete(:xmax); x.nil? ? nil : HttpClient::Preconditions.assert_class('xmax', x, Numeric)), :ymax => (x = opts.delete(:ymax); x.nil? ? nil : HttpClient::Preconditions.assert_class('ymax', x, Numeric)) }.delete_if { |k, v| v.nil? } r = @client.request("/segments/boundingbox").with_query(query).get r.map { |x| ::Com::Trifectalabs::Roadquality::V0::Models::Segment.new(x) } end def post(segment_create_form, incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :currentZoomLevel => (x = opts.delete(:currentZoomLevel); x.nil? ? nil : HttpClient::Preconditions.assert_class('currentZoomLevel', x, Integer)), :hidden => (x = opts.delete(:hidden); x.nil? ? nil : HttpClient::Preconditions.assert_boolean('hidden', x)) }.delete_if { |k, v| v.nil? } (x = segment_create_form; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SegmentCreateForm) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SegmentCreateForm.new(x)) r = @client.request("/segments").with_query(query).with_json(segment_create_form.to_json).post ::Com::Trifectalabs::Roadquality::V0::Models::Segment.new(r) end def put(segment_update_form, incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :segmentId => HttpClient::Preconditions.assert_class('segmentId', HttpClient::Helper.to_uuid(opts.delete(:segmentId)), String) }.delete_if { |k, v| v.nil? } (x = segment_update_form; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SegmentUpdateForm) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SegmentUpdateForm.new(x)) r = @client.request("/segments").with_query(query).with_json(segment_update_form.to_json).put ::Com::Trifectalabs::Roadquality::V0::Models::Segment.new(r) end end class SegmentRatings def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Trifectalabs::Roadquality::V0::Client) end def get(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :id => HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String) }.delete_if { |k, v| v.nil? } r = @client.request("/segmentRatings").with_query(query).get ::Com::Trifectalabs::Roadquality::V0::Models::SegmentRating.new(r) end def post(segment_create_form, incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :id => HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String), :currentZoomLevel => (x = opts.delete(:currentZoomLevel); x.nil? ? nil : HttpClient::Preconditions.assert_class('currentZoomLevel', x, Integer)) }.delete_if { |k, v| v.nil? } (x = segment_create_form; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SegmentCreateForm) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SegmentCreateForm.new(x)) r = @client.request("/segmentRatings").with_query(query).with_json(segment_create_form.to_json).post ::Com::Trifectalabs::Roadquality::V0::Models::Segment.new(r) end def delete(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :id => HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String) }.delete_if { |k, v| v.nil? } r = @client.request("/segmentRatings").with_query(query).delete r end end class Users def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Trifectalabs::Roadquality::V0::Client) end def get r = @client.request("/users").get r.map { |x| ::Com::Trifectalabs::Roadquality::V0::Models::User.new(x) } end def put(user_update_form, incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :userId => HttpClient::Preconditions.assert_class('userId', HttpClient::Helper.to_uuid(opts.delete(:userId)), String) }.delete_if { |k, v| v.nil? } (x = user_update_form; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::UserUpdateForm) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::UserUpdateForm.new(x)) r = @client.request("/users").with_query(query).with_json(user_update_form.to_json).put ::Com::Trifectalabs::Roadquality::V0::Models::User.new(r) end def delete(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) query = { :userId => HttpClient::Preconditions.assert_class('userId', HttpClient::Helper.to_uuid(opts.delete(:userId)), String) }.delete_if { |k, v| v.nil? } r = @client.request("/users").with_query(query).delete ::Com::Trifectalabs::Roadquality::V0::Models::User.new(r) end end class Info def initialize(client) @client = HttpClient::Preconditions.assert_class('client', client, ::Com::Trifectalabs::Roadquality::V0::Client) end def get r = @client.request("/info").get ::Com::Trifectalabs::Roadquality::V0::Models::VersionInfo.new(r) end end end module Models class PathType attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of PathType for this value, creating a new instance for an unknown value def PathType.apply(value) if value.instance_of?(PathType) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || PathType.new(value)) end end # Returns the instance of PathType for this value, or nil if not found def PathType.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) PathType.ALL.find { |v| v.value == value } end def PathType.ALL @@all ||= [PathType.shared, PathType.dedicated_lane, PathType.bike_path] end # A shared road for cars and bikes (road shoulder) def PathType.shared @@_shared ||= PathType.new('shared') end # A dedicated bike lane on the road def PathType.dedicated_lane @@_dedicated_lane ||= PathType.new('dedicatedLane') end # A completely isolated bike lane (a natural barrier from road traffic) def PathType.bike_path @@_bike_path ||= PathType.new('bikePath') end def to_hash value end end class SurfaceType attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of SurfaceType for this value, creating a new instance for an unknown value def SurfaceType.apply(value) if value.instance_of?(SurfaceType) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || SurfaceType.new(value)) end end # Returns the instance of SurfaceType for this value, or nil if not found def SurfaceType.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) SurfaceType.ALL.find { |v| v.value == value } end def SurfaceType.ALL @@all ||= [SurfaceType.gravel, SurfaceType.asphalt, SurfaceType.dirt] end # Road consisting of small rocks def SurfaceType.gravel @@_gravel ||= SurfaceType.new('gravel') end # Road consisting of paved asphalt def SurfaceType.asphalt @@_asphalt ||= SurfaceType.new('asphalt') end # Road consisting of cleared dirt def SurfaceType.dirt @@_dirt ||= SurfaceType.new('dirt') end def to_hash value end end class UserRole attr_reader :value def initialize(value) @value = HttpClient::Preconditions.assert_class('value', value, String) end # Returns the instance of UserRole for this value, creating a new instance for an unknown value def UserRole.apply(value) if value.instance_of?(UserRole) value else HttpClient::Preconditions.assert_class_or_nil('value', value, String) value.nil? ? nil : (from_string(value) || UserRole.new(value)) end end # Returns the instance of UserRole for this value, or nil if not found def UserRole.from_string(value) HttpClient::Preconditions.assert_class('value', value, String) UserRole.ALL.find { |v| v.value == value } end def UserRole.ALL @@all ||= [UserRole.user, UserRole.admin] end # A standard consumer of the service def UserRole.user @@_user ||= UserRole.new('user') end # An administrator of the application def UserRole.admin @@_admin ||= UserRole.new('admin') end def to_hash value end end # A routable path on a map - not necessarily a segment class MapRoute attr_reader :polyline, :distance def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:polyline, :distance], 'MapRoute') @polyline = HttpClient::Preconditions.assert_class('polyline', opts.delete(:polyline), String) @distance = HttpClient::Preconditions.assert_class('distance', opts.delete(:distance), Numeric) end def to_json JSON.dump(to_hash) end def copy(incoming={}) MapRoute.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :polyline => polyline, :distance => distance } end end # A longitudinal or latitudinal coordatine class Point attr_reader :lat, :lng def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:lat, :lng], 'Point') @lat = HttpClient::Preconditions.assert_class('lat', opts.delete(:lat), Numeric) @lng = HttpClient::Preconditions.assert_class('lng', opts.delete(:lng), Numeric) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Point.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :lat => lat, :lng => lng } end end # A segment of road which will be rated and tagged class Segment attr_reader :id, :name, :description, :polyline, :created_by, :hidden def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:id, :polyline, :created_by, :hidden], 'Segment') @id = HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String) @name = (x = opts.delete(:name); x.nil? ? nil : HttpClient::Preconditions.assert_class('name', x, String)) @description = (x = opts.delete(:description); x.nil? ? nil : HttpClient::Preconditions.assert_class('description', x, String)) @polyline = HttpClient::Preconditions.assert_class('polyline', opts.delete(:polyline), String) @created_by = HttpClient::Preconditions.assert_class('created_by', HttpClient::Helper.to_uuid(opts.delete(:created_by)), String) @hidden = HttpClient::Preconditions.assert_boolean('hidden', opts.delete(:hidden)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) Segment.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :id => id, :name => name, :description => description, :polyline => polyline, :created_by => created_by, :hidden => hidden } end end # Form the client uses to create a segment class SegmentCreateForm attr_reader :name, :description, :polylines, :surfaceRating, :trafficRating, :surfaceType, :pathType def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:polylines, :surfaceRating, :trafficRating, :surfaceType, :pathType], 'SegmentCreateForm') @name = (x = opts.delete(:name); x.nil? ? nil : HttpClient::Preconditions.assert_class('name', x, String)) @description = (x = opts.delete(:description); x.nil? ? nil : HttpClient::Preconditions.assert_class('description', x, String)) @polylines = HttpClient::Preconditions.assert_class('polylines', opts.delete(:polylines), Array).map { |v| HttpClient::Preconditions.assert_class('polylines', v, String) } @surfaceRating = HttpClient::Preconditions.assert_class('surfaceRating', opts.delete(:surfaceRating), Integer) @trafficRating = HttpClient::Preconditions.assert_class('trafficRating', opts.delete(:trafficRating), Integer) @surfaceType = (x = opts.delete(:surfaceType); x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType.apply(x)) @pathType = (x = opts.delete(:pathType); x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::PathType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::PathType.apply(x)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) SegmentCreateForm.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :description => description, :polylines => polylines, :surfaceRating => surfaceRating, :trafficRating => trafficRating, :surfaceType => surfaceType.value, :pathType => pathType.value } end end # A rating that is supplied with the segment class SegmentRating attr_reader :id, :segmentId, :userId, :trafficRating, :surfaceRating, :surfaceType, :pathType, :createdAt, :updatedAt, :deletedAt def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:id, :segmentId, :userId, :trafficRating, :surfaceRating, :surfaceType, :pathType, :createdAt, :updatedAt], 'SegmentRating') @id = HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String) @segmentId = HttpClient::Preconditions.assert_class('segmentId', HttpClient::Helper.to_uuid(opts.delete(:segmentId)), String) @userId = HttpClient::Preconditions.assert_class('userId', HttpClient::Helper.to_uuid(opts.delete(:userId)), String) @trafficRating = HttpClient::Preconditions.assert_class('trafficRating', opts.delete(:trafficRating), Integer) @surfaceRating = HttpClient::Preconditions.assert_class('surfaceRating', opts.delete(:surfaceRating), Integer) @surfaceType = (x = opts.delete(:surfaceType); x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType.apply(x)) @pathType = (x = opts.delete(:pathType); x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::PathType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::PathType.apply(x)) @createdAt = HttpClient::Preconditions.assert_class('createdAt', HttpClient::Helper.to_date_time_iso8601(opts.delete(:createdAt)), DateTime) @updatedAt = HttpClient::Preconditions.assert_class('updatedAt', HttpClient::Helper.to_date_time_iso8601(opts.delete(:updatedAt)), DateTime) @deletedAt = (x = opts.delete(:deletedAt); x.nil? ? nil : HttpClient::Preconditions.assert_class('deletedAt', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) SegmentRating.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :id => id, :segmentId => segmentId, :userId => userId, :trafficRating => trafficRating, :surfaceRating => surfaceRating, :surfaceType => surfaceType.value, :pathType => pathType.value, :createdAt => createdAt, :updatedAt => updatedAt, :deletedAt => deletedAt } end end # Form to modify an existing segment class SegmentUpdateForm attr_reader :name, :description, :surfaceRating, :trafficRating, :surfaceType, :pathType def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @name = (x = opts.delete(:name); x.nil? ? nil : HttpClient::Preconditions.assert_class('name', x, String)) @description = (x = opts.delete(:description); x.nil? ? nil : HttpClient::Preconditions.assert_class('description', x, String)) @surfaceRating = (x = opts.delete(:surfaceRating); x.nil? ? nil : HttpClient::Preconditions.assert_class('surfaceRating', x, Integer)) @trafficRating = (x = opts.delete(:trafficRating); x.nil? ? nil : HttpClient::Preconditions.assert_class('trafficRating', x, Integer)) @surfaceType = (x = opts.delete(:surfaceType); x.nil? ? nil : (x = x; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::SurfaceType.apply(x))) @pathType = (x = opts.delete(:pathType); x.nil? ? nil : (x = x; x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::PathType) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::PathType.apply(x))) end def to_json JSON.dump(to_hash) end def copy(incoming={}) SegmentUpdateForm.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :description => description, :surfaceRating => surfaceRating, :trafficRating => trafficRating, :surfaceType => surfaceType.nil? ? nil : surfaceType.value, :pathType => pathType.nil? ? nil : pathType.value } end end # A user of the service class User attr_reader :id, :firstName, :lastName, :email, :city, :province, :country, :birthdate, :sex, :role, :stravaToken, :createdAt, :updatedAt, :deletedAt def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:id, :firstName, :lastName, :email, :role, :stravaToken, :createdAt, :updatedAt], 'User') @id = HttpClient::Preconditions.assert_class('id', HttpClient::Helper.to_uuid(opts.delete(:id)), String) @firstName = HttpClient::Preconditions.assert_class('firstName', opts.delete(:firstName), String) @lastName = HttpClient::Preconditions.assert_class('lastName', opts.delete(:lastName), String) @email = HttpClient::Preconditions.assert_class('email', opts.delete(:email), String) @city = (x = opts.delete(:city); x.nil? ? nil : HttpClient::Preconditions.assert_class('city', x, String)) @province = (x = opts.delete(:province); x.nil? ? nil : HttpClient::Preconditions.assert_class('province', x, String)) @country = (x = opts.delete(:country); x.nil? ? nil : HttpClient::Preconditions.assert_class('country', x, String)) @birthdate = (x = opts.delete(:birthdate); x.nil? ? nil : HttpClient::Preconditions.assert_class('birthdate', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) @sex = (x = opts.delete(:sex); x.nil? ? nil : HttpClient::Preconditions.assert_class('sex', x, String)) @role = (x = opts.delete(:role); x.is_a?(::Com::Trifectalabs::Roadquality::V0::Models::UserRole) ? x : ::Com::Trifectalabs::Roadquality::V0::Models::UserRole.apply(x)) @stravaToken = HttpClient::Preconditions.assert_class('stravaToken', opts.delete(:stravaToken), String) @createdAt = HttpClient::Preconditions.assert_class('createdAt', HttpClient::Helper.to_date_time_iso8601(opts.delete(:createdAt)), DateTime) @updatedAt = HttpClient::Preconditions.assert_class('updatedAt', HttpClient::Helper.to_date_time_iso8601(opts.delete(:updatedAt)), DateTime) @deletedAt = (x = opts.delete(:deletedAt); x.nil? ? nil : HttpClient::Preconditions.assert_class('deletedAt', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) User.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :id => id, :firstName => firstName, :lastName => lastName, :email => email, :city => city, :province => province, :country => country, :birthdate => birthdate, :sex => sex, :role => role.value, :stravaToken => stravaToken, :createdAt => createdAt, :updatedAt => updatedAt, :deletedAt => deletedAt } end end # A form to update attributes about a user class UserUpdateForm attr_reader :birthdate, :sex def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) @birthdate = (x = opts.delete(:birthdate); x.nil? ? nil : HttpClient::Preconditions.assert_class('birthdate', HttpClient::Helper.to_date_time_iso8601(x), DateTime)) @sex = (x = opts.delete(:sex); x.nil? ? nil : HttpClient::Preconditions.assert_class('sex', x, String)) end def to_json JSON.dump(to_hash) end def copy(incoming={}) UserUpdateForm.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :birthdate => birthdate, :sex => sex } end end class VersionInfo attr_reader :name, :version, :scalaVersion, :sbtVersion def initialize(incoming={}) opts = HttpClient::Helper.symbolize_keys(incoming) HttpClient::Preconditions.require_keys(opts, [:name, :version, :scalaVersion, :sbtVersion], 'VersionInfo') @name = HttpClient::Preconditions.assert_class('name', opts.delete(:name), String) @version = HttpClient::Preconditions.assert_class('version', opts.delete(:version), String) @scalaVersion = HttpClient::Preconditions.assert_class('scalaVersion', opts.delete(:scalaVersion), String) @sbtVersion = HttpClient::Preconditions.assert_class('sbtVersion', opts.delete(:sbtVersion), String) end def to_json JSON.dump(to_hash) end def copy(incoming={}) VersionInfo.new(to_hash.merge(HttpClient::Helper.symbolize_keys(incoming))) end def to_hash { :name => name, :version => version, :scalaVersion => scalaVersion, :sbtVersion => sbtVersion } 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