require 'erb' module OEHClient module Helper module Request ONE_PROTOCOL = "https://" THUNDERHEAD_DOMAIN = ".thunderhead.com" ONE_URI_PART = "/one/oauth1" API_URI_PART = "/rt/api" API_VERSION = "/2.0" POST_METHOD = "post" PUT_METHOD = "put" # request_url builds the target request URL with the passed parameters, URL encoding the parameters # as necessary to create a valid request def self.format_url(url, params) # for each of the parameters, build a single query parameter string parameter_part = "" params.each do |key, value| # if there is more than one argument, add the apppropriate separator (&) between # query parameters parameter_part << "&" if (parameter_part.length > 0) # URL Encode the value of the property parameter_part << "#{key.to_s}=#{ERB::Util.url_encode(value)}" end # return the fully-qualified URL with parameters (if passsed) (parameter_part.length > 0 ? "#{url}?#{parameter_part}" : "#{url}") end # default_JSON_header is the default header that is passed to any OEH Request if not provided explicitly by the # calling methods def self.default_JSON_header() {'Accept' => 'application/json' , 'Content-Type' =>'application/json', 'X-Requested-With' => 'XMLHttpRequest' } end end # module Request module Response # determine if the string that was passed is valid JSON syntax and can be parsed by the the # ActiveSupport::JSON.decode method def self.valid_json?(json) valid_indicator = true begin ActiveSupport::JSON.decode(json) rescue ActiveSupport::JSON.parse_error valid_indicator = false end end def self.handle(rest_response) valid_response_codes = [100, 200, 204, 302] # raise a generic HTTPRequestException if the the status code is not 100 (Continue) or 200 (OK) raise OEHClient::Exception::HTTPRequestException.new("HTTP Request Exception with code #{rest_response.code}", rest_response.code) unless (valid_response_codes.include?(rest_response.code)) api_response = Hash.new api_response[:body] = (rest_response.code == 204 ? {} : (OEHClient::Helper::Response.valid_json?(rest_response.body) ? ActiveSupport::JSON.decode(rest_response.body) : rest_response.body)) api_response[:cookies] = rest_response.cookies api_response end end # module Response module Timestamp # convert the time value from a Time, DateTime, String, or Integer to a proper ONE timestamp value # format (UTC Milliseconds) def self.to_one_timestamp(timevalue) one_timestamp = timevalue if (timevalue.is_a?(Integer)) one_timestamp = timevalue.utc.strftime("%s%L").to_i if (timevalue.is_a?(Time) || timevalue.is_a?(DateTime)) one_timestamp = Time.parse(timevalue).utc.strftime("%s%L").to_i if (timevalue.is_a?(String)) one_timestamp end end end end