Class: RightScaleSelfService::Api::Client
- Inherits:
-
Object
- Object
- RightScaleSelfService::Api::Client
- Defined in:
- lib/rightscale_selfservice/api/client.rb
Instance Attribute Summary collapse
-
#account_id ⇒ String
A RightScale account id.
-
#api_url ⇒ String
URL to use for Cloud Management API requests.
-
#interface ⇒ Hash
readonly
Interface A hash containing details about the services, resources, and actions available in this client.
-
#logger ⇒ Logger
A logger which will be used, mostly for debug purposes.
-
#selfservice_url ⇒ String
URL to use for Self Service API requests.
Class Method Summary collapse
-
.format_error(error) ⇒ Object
Accepts various possible responses and formats it into useful error text.
-
.get_known_account_id_tokens ⇒ Array<String>
A list of tokens which might appear in hrefs which need to be replaced with the RightScale account_id.
-
.get_resource_id_from_href(url_href_or_id) ⇒ String
Accepts a full URL with protocol and hostname, or a relative href and returns the ID which is the last token in the path.
Instance Method Summary collapse
-
#get_authorized_rest_client_request(request_params) ⇒ RestClient::Request
Accepts request parameters and returns a Rest Client Request which has necessary authentication details appended.
-
#get_relative_href(url) ⇒ String
Converts the input param to a relative href.
-
#initialize(params) ⇒ Client
constructor
A new instance of Client.
-
#method_missing(name, *args) ⇒ RightScaleSelfService::Api::Service
Returns a service of the specified (or newest) version.
Constructor Details
#initialize(params) ⇒ Client
Returns a new instance of Client.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/rightscale_selfservice/api/client.rb', line 73 def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ RightScaleSelfService::Api::Service
Returns a service of the specified (or newest) version
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/rightscale_selfservice/api/client.rb', line 206 def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end |
Instance Attribute Details
#account_id ⇒ String
Returns A RightScale account id.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/rightscale_selfservice/api/client.rb', line 38 class Client # A list of tokens which might appear in hrefs which need to be replaced # with the RightScale account_id. This will likely change over time and # some of these will likely go away or change meaning # # @return [Array<String>] def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end attr_accessor :selfservice_url attr_accessor :api_url attr_accessor :logger attr_accessor :account_id attr_reader :interface # @param params [Hash] a hash of parameters where the possible values are # * account_id [String] (required) A RightScale account id # * selfservice_url [String] (required) URL to use for Self Service API # requests. I.E. https://selfservice-4.rightscale.com # * api_url [String] (required) URL to use for Cloud Management API # requests. Only used once to authenticate. # I.E. https://us-4.rightscale.com # * access_token [String] A RightScale API OAuth Access Token # * refresh_token [String] A RightScale API OAuth Refresh Token, which # will be exchanged for an access token # * email [String] A RightScale user email address # * password [String] A RightScale user password # * logger [Logger] A logger which will be used, mostly for debug purposes def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end # Accepts request parameters and returns a Rest Client Request which has # necessary authentication details appended. # # @param request_params [Hash] A hash of params to be passed to # RestClient::Request.new after it has had API authentication details # injected # # @return [RestClient::Request] A request which is ready to be executed # cause it's got necessary authentication details def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end # Returns a service of the specified (or newest) version # # @param name [String] The name of the desired service # # @return [RightScaleSelfService::Api::Service] # # @example Get latest version (1.0) of designer service # service = client.designer # service.version #=> "1.0" # @example Get specified version of designer service # service = client.designer("1.1") # service.version #=> "1.1" def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end # Converts the input param to a relative href. # I.E. /api/service/:account_id/resource # # @param url [String] The full url to get the relative href from # # @return [String] A relative href def get_relative_href(url) url.gsub!(@selfservice_url,"") end # Accepts a full URL with protocol and hostname, or a relative href and # returns the ID which is the last token in the path. # # I.E. https://hostname/api/foo/bar/baz/12345 == 12345 # and /api/foo/bar/baz/12345 == 12345 # # @param url_href_or_id [String] The full url with protocol and hostname, # a relative resource href, or the id. # # @return [String] ID of the resource referred to by the url or href, or # nil if the id can not be determined. def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end # Accepts various possible responses and formats it into useful error text # # @param [RestClient::ExceptionWithResponse] error The response or error # to format def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end end |
#api_url ⇒ String
Returns URL to use for Cloud Management API requests. Only used once to authenticate.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/rightscale_selfservice/api/client.rb', line 38 class Client # A list of tokens which might appear in hrefs which need to be replaced # with the RightScale account_id. This will likely change over time and # some of these will likely go away or change meaning # # @return [Array<String>] def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end attr_accessor :selfservice_url attr_accessor :api_url attr_accessor :logger attr_accessor :account_id attr_reader :interface # @param params [Hash] a hash of parameters where the possible values are # * account_id [String] (required) A RightScale account id # * selfservice_url [String] (required) URL to use for Self Service API # requests. I.E. https://selfservice-4.rightscale.com # * api_url [String] (required) URL to use for Cloud Management API # requests. Only used once to authenticate. # I.E. https://us-4.rightscale.com # * access_token [String] A RightScale API OAuth Access Token # * refresh_token [String] A RightScale API OAuth Refresh Token, which # will be exchanged for an access token # * email [String] A RightScale user email address # * password [String] A RightScale user password # * logger [Logger] A logger which will be used, mostly for debug purposes def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end # Accepts request parameters and returns a Rest Client Request which has # necessary authentication details appended. # # @param request_params [Hash] A hash of params to be passed to # RestClient::Request.new after it has had API authentication details # injected # # @return [RestClient::Request] A request which is ready to be executed # cause it's got necessary authentication details def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end # Returns a service of the specified (or newest) version # # @param name [String] The name of the desired service # # @return [RightScaleSelfService::Api::Service] # # @example Get latest version (1.0) of designer service # service = client.designer # service.version #=> "1.0" # @example Get specified version of designer service # service = client.designer("1.1") # service.version #=> "1.1" def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end # Converts the input param to a relative href. # I.E. /api/service/:account_id/resource # # @param url [String] The full url to get the relative href from # # @return [String] A relative href def get_relative_href(url) url.gsub!(@selfservice_url,"") end # Accepts a full URL with protocol and hostname, or a relative href and # returns the ID which is the last token in the path. # # I.E. https://hostname/api/foo/bar/baz/12345 == 12345 # and /api/foo/bar/baz/12345 == 12345 # # @param url_href_or_id [String] The full url with protocol and hostname, # a relative resource href, or the id. # # @return [String] ID of the resource referred to by the url or href, or # nil if the id can not be determined. def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end # Accepts various possible responses and formats it into useful error text # # @param [RestClient::ExceptionWithResponse] error The response or error # to format def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end end |
#interface ⇒ Hash (readonly)
Returns interface A hash containing details about the services, resources, and actions available in this client.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/rightscale_selfservice/api/client.rb', line 38 class Client # A list of tokens which might appear in hrefs which need to be replaced # with the RightScale account_id. This will likely change over time and # some of these will likely go away or change meaning # # @return [Array<String>] def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end attr_accessor :selfservice_url attr_accessor :api_url attr_accessor :logger attr_accessor :account_id attr_reader :interface # @param params [Hash] a hash of parameters where the possible values are # * account_id [String] (required) A RightScale account id # * selfservice_url [String] (required) URL to use for Self Service API # requests. I.E. https://selfservice-4.rightscale.com # * api_url [String] (required) URL to use for Cloud Management API # requests. Only used once to authenticate. # I.E. https://us-4.rightscale.com # * access_token [String] A RightScale API OAuth Access Token # * refresh_token [String] A RightScale API OAuth Refresh Token, which # will be exchanged for an access token # * email [String] A RightScale user email address # * password [String] A RightScale user password # * logger [Logger] A logger which will be used, mostly for debug purposes def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end # Accepts request parameters and returns a Rest Client Request which has # necessary authentication details appended. # # @param request_params [Hash] A hash of params to be passed to # RestClient::Request.new after it has had API authentication details # injected # # @return [RestClient::Request] A request which is ready to be executed # cause it's got necessary authentication details def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end # Returns a service of the specified (or newest) version # # @param name [String] The name of the desired service # # @return [RightScaleSelfService::Api::Service] # # @example Get latest version (1.0) of designer service # service = client.designer # service.version #=> "1.0" # @example Get specified version of designer service # service = client.designer("1.1") # service.version #=> "1.1" def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end # Converts the input param to a relative href. # I.E. /api/service/:account_id/resource # # @param url [String] The full url to get the relative href from # # @return [String] A relative href def get_relative_href(url) url.gsub!(@selfservice_url,"") end # Accepts a full URL with protocol and hostname, or a relative href and # returns the ID which is the last token in the path. # # I.E. https://hostname/api/foo/bar/baz/12345 == 12345 # and /api/foo/bar/baz/12345 == 12345 # # @param url_href_or_id [String] The full url with protocol and hostname, # a relative resource href, or the id. # # @return [String] ID of the resource referred to by the url or href, or # nil if the id can not be determined. def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end # Accepts various possible responses and formats it into useful error text # # @param [RestClient::ExceptionWithResponse] error The response or error # to format def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end end |
#logger ⇒ Logger
Returns A logger which will be used, mostly for debug purposes.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/rightscale_selfservice/api/client.rb', line 38 class Client # A list of tokens which might appear in hrefs which need to be replaced # with the RightScale account_id. This will likely change over time and # some of these will likely go away or change meaning # # @return [Array<String>] def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end attr_accessor :selfservice_url attr_accessor :api_url attr_accessor :logger attr_accessor :account_id attr_reader :interface # @param params [Hash] a hash of parameters where the possible values are # * account_id [String] (required) A RightScale account id # * selfservice_url [String] (required) URL to use for Self Service API # requests. I.E. https://selfservice-4.rightscale.com # * api_url [String] (required) URL to use for Cloud Management API # requests. Only used once to authenticate. # I.E. https://us-4.rightscale.com # * access_token [String] A RightScale API OAuth Access Token # * refresh_token [String] A RightScale API OAuth Refresh Token, which # will be exchanged for an access token # * email [String] A RightScale user email address # * password [String] A RightScale user password # * logger [Logger] A logger which will be used, mostly for debug purposes def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end # Accepts request parameters and returns a Rest Client Request which has # necessary authentication details appended. # # @param request_params [Hash] A hash of params to be passed to # RestClient::Request.new after it has had API authentication details # injected # # @return [RestClient::Request] A request which is ready to be executed # cause it's got necessary authentication details def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end # Returns a service of the specified (or newest) version # # @param name [String] The name of the desired service # # @return [RightScaleSelfService::Api::Service] # # @example Get latest version (1.0) of designer service # service = client.designer # service.version #=> "1.0" # @example Get specified version of designer service # service = client.designer("1.1") # service.version #=> "1.1" def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end # Converts the input param to a relative href. # I.E. /api/service/:account_id/resource # # @param url [String] The full url to get the relative href from # # @return [String] A relative href def get_relative_href(url) url.gsub!(@selfservice_url,"") end # Accepts a full URL with protocol and hostname, or a relative href and # returns the ID which is the last token in the path. # # I.E. https://hostname/api/foo/bar/baz/12345 == 12345 # and /api/foo/bar/baz/12345 == 12345 # # @param url_href_or_id [String] The full url with protocol and hostname, # a relative resource href, or the id. # # @return [String] ID of the resource referred to by the url or href, or # nil if the id can not be determined. def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end # Accepts various possible responses and formats it into useful error text # # @param [RestClient::ExceptionWithResponse] error The response or error # to format def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end end |
#selfservice_url ⇒ String
Returns URL to use for Self Service API requests. I.E. selfservice-4.rightscale.com.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/rightscale_selfservice/api/client.rb', line 38 class Client # A list of tokens which might appear in hrefs which need to be replaced # with the RightScale account_id. This will likely change over time and # some of these will likely go away or change meaning # # @return [Array<String>] def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end attr_accessor :selfservice_url attr_accessor :api_url attr_accessor :logger attr_accessor :account_id attr_reader :interface # @param params [Hash] a hash of parameters where the possible values are # * account_id [String] (required) A RightScale account id # * selfservice_url [String] (required) URL to use for Self Service API # requests. I.E. https://selfservice-4.rightscale.com # * api_url [String] (required) URL to use for Cloud Management API # requests. Only used once to authenticate. # I.E. https://us-4.rightscale.com # * access_token [String] A RightScale API OAuth Access Token # * refresh_token [String] A RightScale API OAuth Refresh Token, which # will be exchanged for an access token # * email [String] A RightScale user email address # * password [String] A RightScale user password # * logger [Logger] A logger which will be used, mostly for debug purposes def initialize(params) @services = {} @auth = {"cookie" => {}, "authorization" => {}} required_params = [:account_id,:selfservice_url,:api_url] # Use the defined logger, or log to a blackhole if params.include?(:logger) @logger = params[:logger] else @logger = NullLogger.new end # Validate required properties unless (required_params - params.keys()).length == 0 raise "RightScaleSelfService::Api requires the following parameters (#{required_params.join(',')}) but only these were supplied (#{params.keys().join(',')})" end @account_id = params[:account_id] @selfservice_url = params[:selfservice_url] @api_url = params[:api_url] if params.include?(:access_token) @logger.info("Using pre-authenticated access token") @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{params[:access_token]}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{params[:access_token]}"} end if params.include?(:refresh_token) # OAuth @logger.info("Logging into RightScale API 1.5 using OAuth @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :grant_type => "refresh_token", :refresh_token => params[:refresh_token] }), :url => "#{@api_url}/api/oauth2", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute oauth_token = JSON.parse(cm_login_resp.to_s)["access_token"] @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :headers => {"Authorization" => "Bearer #{oauth_token}"} ) ss_login_resp = ss_login_req.execute @auth["authorization"] = {"Authorization" => "Bearer #{oauth_token}"} end if params.include?(:email) && params.include?(:password) @logger.info("Logging into RightScale Cloud Management API 1.5 @ #{@api_url}") cm_login_req = RestClient::Request.new( :method => :post, :payload => URI.encode_www_form({ :email => params[:email], :password => params[:password], :account_href => "/api/accounts/#{@account_id}" }), :url => "#{@api_url}/api/session", :headers => {"X-API-VERSION" => "1.5"} ) cm_login_resp = cm_login_req.execute @logger.info("Logging into self service @ #{@selfservice_url}") ss_login_req = RestClient::Request.new( :method => :get, :url => "#{@selfservice_url}/api/catalog/new_session?account_id=#{@account_id}", :cookies => {"rs_gbl" => cm_login_resp.["rs_gbl"]} ) ss_login_resp = ss_login_req.execute @auth["cookie"] = cm_login_resp. end if @auth == {"cookie" => {}, "authorization" => {}} raise "RightScaleSelfService::Api did not authenticate with #{@selfservice_url}. Make sure you supplied valid login details" end interface_filepath = File.(File.join(File.dirname(__FILE__),"interface.json")) interface_file = File.open(interface_filepath, "rb") begin @interface = JSON.parse(interface_file.read) rescue Exception => e raise e ensure interface_file.close end end # Accepts request parameters and returns a Rest Client Request which has # necessary authentication details appended. # # @param request_params [Hash] A hash of params to be passed to # RestClient::Request.new after it has had API authentication details # injected # # @return [RestClient::Request] A request which is ready to be executed # cause it's got necessary authentication details def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end # Returns a service of the specified (or newest) version # # @param name [String] The name of the desired service # # @return [RightScaleSelfService::Api::Service] # # @example Get latest version (1.0) of designer service # service = client.designer # service.version #=> "1.0" # @example Get specified version of designer service # service = client.designer("1.1") # service.version #=> "1.1" def method_missing(name, *args) unless interface["services"].has_key?(name.to_s) raise "No service named \"#{name}\" can not be found. Available services are [#{interface["services"].keys.join(',')}]" end version = "" if args.length > 0 version = args.first unless interface["services"][name.to_s].has_key? version raise "Version #{version} of service \"#{name}\" can not be found. Available versions are [#{interface["services"][name.to_s].keys.join(',')}]" end else version = interface["services"][name.to_s].keys.sort.last end service_hash_key = "#{name}::#{version}" if @services.has_key?(service_hash_key) @services[service_hash_key] else base_url = selfservice_url.gsub(/\/*$/,"") base_url += "/api/#{name}" service = RightScaleSelfService::Api::Service.new(name.to_s,version,base_url,self) @services[service_hash_key] = service end end # Converts the input param to a relative href. # I.E. /api/service/:account_id/resource # # @param url [String] The full url to get the relative href from # # @return [String] A relative href def get_relative_href(url) url.gsub!(@selfservice_url,"") end # Accepts a full URL with protocol and hostname, or a relative href and # returns the ID which is the last token in the path. # # I.E. https://hostname/api/foo/bar/baz/12345 == 12345 # and /api/foo/bar/baz/12345 == 12345 # # @param url_href_or_id [String] The full url with protocol and hostname, # a relative resource href, or the id. # # @return [String] ID of the resource referred to by the url or href, or # nil if the id can not be determined. def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end # Accepts various possible responses and formats it into useful error text # # @param [RestClient::ExceptionWithResponse] error The response or error # to format def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end end |
Class Method Details
.format_error(error) ⇒ Object
Accepts various possible responses and formats it into useful error text
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/rightscale_selfservice/api/client.rb', line 262 def self.format_error(error) formatted_text = "" if error if error.is_a?(RestClient::ExceptionWithResponse) formatted_text = "HTTP Response Code: #{error.http_code}\nMessage:\n" if error.response.headers[:content_type] == "application/json" formatted_text += JSON.pretty_generate( JSON.parse(error.response.body) ).gsub('\n',"\n") else formatted_text += error.response.body end end else formatted_text = "Nothing supplied for formatting" end formatted_text end |
.get_known_account_id_tokens ⇒ Array<String>
A list of tokens which might appear in hrefs which need to be replaced with the RightScale account_id. This will likely change over time and some of these will likely go away or change meaning
45 46 47 |
# File 'lib/rightscale_selfservice/api/client.rb', line 45 def self.get_known_account_id_tokens [":account_id",":catalog_id",":collection_id",":project_id"] end |
.get_resource_id_from_href(url_href_or_id) ⇒ String
Accepts a full URL with protocol and hostname, or a relative href and returns the ID which is the last token in the path.
I.E. hostname/api/foo/bar/baz/12345 == 12345 and /api/foo/bar/baz/12345 == 12345
252 253 254 255 256 |
# File 'lib/rightscale_selfservice/api/client.rb', line 252 def self.get_resource_id_from_href(url_href_or_id) return url_href_or_id if url_href_or_id =~ /^[a-zA-Z0-9]*$/ matchdata = url_href_or_id.match(/[a-zA-Z0-9\/]*\/(?<id>[a-zA-Z0-9]*)$/) matchdata['id'] if matchdata end |
Instance Method Details
#get_authorized_rest_client_request(request_params) ⇒ RestClient::Request
Accepts request parameters and returns a Rest Client Request which has necessary authentication details appended.
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/rightscale_selfservice/api/client.rb', line 178 def (request_params) if @auth["cookie"].length > 0 request_params[:cookies] = @auth["cookie"] end if @auth["authorization"].length > 0 if request_params.has_key?(:headers) request_params[:headers].merge!(@auth["authorization"]) else request_params[:headers] = @auth["authorization"] end end RestClient::Request.new(request_params) end |
#get_relative_href(url) ⇒ String
Converts the input param to a relative href. I.E. /api/service/:account_id/resource
237 238 239 |
# File 'lib/rightscale_selfservice/api/client.rb', line 237 def get_relative_href(url) url.gsub!(@selfservice_url,"") end |