Class: KillBillClient::Model::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/killbill_client/models/resource.rb

Direct Known Subclasses

AccountAttributes, AccountEmailAttributes, AccountTimelineAttributes, AdminPaymentAttributes, AuditLogAttributes, BillingExceptionAttributes, BlockPriceAttributes, BlockingStateAttributes, BulkSubscriptionsBundleAttributes, BundleAttributes, BundleTimelineAttributes, CatalogAttributes, ComboHostedPaymentPageAttributes, ComboPaymentTransactionAttributes, CustomFieldAttributes, DurationAttributes, EventSubscriptionAttributes, Export, GatewayNotificationAttributes, HostedPaymentPageBillingAddressAttributes, HostedPaymentPageCustomerAttributes, HostedPaymentPageFieldsAttributes, HostedPaymentPageFormDescriptorAttributes, InvoiceAttributes, InvoiceDryRunAttributes, InvoiceItemAttributes, InvoicePaymentAttributes, InvoicePaymentTransactionAttributes, LimitAttributes, NodeCommandAttributes, NodeCommandPropertyAttributes, NodeInfoAttributes, NotificationAttributes, OverdueAttributes, OverdueConditionAttributes, OverdueStateAttributes, OverdueStateConfigAttributes, PaymentAttemptAttributes, PaymentAttributes, PaymentMethodAttributes, PaymentMethodPluginDetailAttributes, PaymentTransactionAttributes, PhaseAttributes, PhasePriceAttributes, PlanAttributes, PlanDetailAttributes, PluginInfoAttributes, PluginPropertyAttributes, PluginServiceInfoAttributes, PriceAttributes, PriceListAttributes, ProductAttributes, ProfilingDataAttributes, ProfilingDataAttributesItem, RoleDefinitionAttributes, RolledUpUnitAttributes, RolledUpUsageAttributes, Security, SessionAttributes, SimplePlanAttributes, StackTraceElementAttributes, SubjectAttributes, SubscriptionAttributes, SubscriptionUsageRecordAttributes, TagAttributes, TagDefinitionAttributes, TenantAttributes, TenantKeyValueAttributes, TierAttributes, TierPriceAttributes, TieredBlockAttributes, UnitAttributes, UnitUsageRecordAttributes, UsageAttributes, UsagePriceAttributes, UsageRecordAttributes, UserRolesAttributes

Constant Summary collapse

KILLBILL_API_PREFIX =
'/1.0/kb'
KILLBILL_API_PAGINATION_PREFIX =
'pagination'
@@attribute_names =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ Resource

Returns a new instance of Resource.



17
18
19
20
21
22
23
24
25
# File 'lib/killbill_client/models/resource.rb', line 17

def initialize(hash = nil)
	@uri = nil
  # Make sure we support ActiveSupport::HashWithIndifferentAccess for Kaui
  if hash.respond_to?(:each)
    hash.each do |key, value|
      send("#{Utils.underscore key.to_s}=", value)
    end
  end
end

Instance Attribute Details

#clazzObject (readonly)

Returns the value of attribute clazz.



7
8
9
# File 'lib/killbill_client/models/resource.rb', line 7

def clazz
  @clazz
end

#etagObject (readonly)

Returns the value of attribute etag.



7
8
9
# File 'lib/killbill_client/models/resource.rb', line 7

def etag
  @etag
end

#responseObject (readonly)

Returns the value of attribute response.



7
8
9
# File 'lib/killbill_client/models/resource.rb', line 7

def response
  @response
end

#session_idObject (readonly)

Returns the value of attribute session_id.



7
8
9
# File 'lib/killbill_client/models/resource.rb', line 7

def session_id
  @session_id
end

#uriObject

Set on create call



235
236
237
# File 'lib/killbill_client/models/resource.rb', line 235

def uri
  @uri
end

Class Method Details

.attribute(name) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/killbill_client/models/resource.rb', line 182

def attribute(name)
  send('attr_accessor', name.to_sym)
  attributes = @json_attributes ||= []

  if respond_to?(:json_attributes, true)
    json_attributes.push(name.to_s)
  else
    (class << self; self; end).
      send(:define_method, :json_attributes) { attributes }
    json_attributes.push(name.to_s)
  end
end

.create_alias(new_name, old_name) ⇒ Object

hack to cater the api return attributes and javax attributes without editing gen scripts call only after its declared as a instance_method using attr_accessor



213
214
215
216
# File 'lib/killbill_client/models/resource.rb', line 213

def create_alias(new_name, old_name)
  alias_method new_name.to_sym, old_name.to_sym #getter
  alias_method "#{new_name}=".to_sym, "#{old_name}=".to_sym #setter
end

.delete(uri, body = nil, params = {}, options = {}, clazz = self) ⇒ Object



64
65
66
67
# File 'lib/killbill_client/models/resource.rb', line 64

def delete(uri, body = nil, params = {}, options = {}, clazz = self)
  response = KillBillClient::API.delete uri, body, params, options
  from_response clazz, response
end

.extract_session_id(response) ⇒ Object

Extract the session id from a response



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/killbill_client/models/resource.rb', line 219

def extract_session_id(response)
  # The Set-Cookie header looks like
  # "set-cookie"=>["JSESSIONID=16; Path=/; HttpOnly", "rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Sat, 17-Aug-2013 23:39:37 GMT"],
  session_cookie = response['set-cookie']
  unless session_cookie.nil?
    session_cookie.split(';').each do |chunk|
      chunk.strip!
      key, value = chunk.split('=')
      return value if key == 'JSESSIONID'
    end
  end
  nil
end

.from_json(resource_class, json) ⇒ Resource

Instantiates a record from a JSON blob.

Parameters:

  • resource_class (Resource)
  • json (String)

Returns:

See Also:



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/killbill_client/models/resource.rb', line 122

def from_json(resource_class, json)
  # e.g. DELETE
  return nil if json.nil? or json.size == 0
  data = JSON.parse json

  if data.is_a? Array
    records = Resources.new
    data.each do |data_element|
      if data_element.is_a? Enumerable
        records << instantiate_record_from_json(resource_class, data_element)
      else
        # Value (e.g. String)
        records << data_element
      end
    end
    records
  else
    instantiate_record_from_json(resource_class, data)
  end
end

.from_response(resource_class, response) ⇒ Resource

Instantiates a record from an HTTP response, setting the record’s response attribute in the process.

Parameters:

  • resource_class (Resource)
  • response (Net::HTTPResponse)

Returns:



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
# File 'lib/killbill_client/models/resource.rb', line 75

def from_response(resource_class, response)
  case response['Content-Type']
    when nil
      response.body
    when %r{application/pdf}
      response.body
    when %r{text/html}
      response.body
    when %r{text/plain}
      response.body
    when %r{application/octet-stream}
      response.body
    when %r{text/xml}
      if response['location']
        response['location']
      else
        response.body
      end
    when %r{application/json}
      record = from_json resource_class, response.body
      if record.nil?
        record = resource_class.new
        record.uri = response['location']
      end

      session_id = extract_session_id(response)
      record.instance_eval {
        @clazz = resource_class
        @etag = response['ETag']
        @session_id = session_id
        @pagination_max_nb_records = response['X-Killbill-Pagination-MaxNbRecords'].to_i unless response['X-Killbill-Pagination-MaxNbRecords'].nil?
        @pagination_total_nb_records = response['X-Killbill-Pagination-TotalNbRecords'].to_i unless response['X-Killbill-Pagination-TotalNbRecords'].nil?
        @pagination_next_page = response['X-Killbill-Pagination-NextPageUri']
        @response = response
      }
      record
    else
      raise ArgumentError, "#{response['Content-Type']} is not supported by the library"
  end
end

.get(uri, params = {}, options = {}, clazz = self) ⇒ Object



42
43
44
45
# File 'lib/killbill_client/models/resource.rb', line 42

def get(uri, params = {}, options = {}, clazz = self)
  response = KillBillClient::API.get uri, params, options
  from_response clazz, response
end

.has_many(attr_name, type = nil) ⇒ Object



195
196
197
198
199
200
201
# File 'lib/killbill_client/models/resource.rb', line 195

def has_many(attr_name, type = nil)
  send("attr_accessor", attr_name.to_sym)

  #add it to attribute_names
  @@attribute_names[self.name] ||= {}
  @@attribute_names[self.name][attr_name.to_sym] = {:type => type, :cardinality => :many}
end

.has_one(attr_name, type = nil) ⇒ Object



203
204
205
206
207
208
209
# File 'lib/killbill_client/models/resource.rb', line 203

def has_one(attr_name, type = nil)
  send("attr_accessor", attr_name.to_sym)

  #add it to attribute_names
  @@attribute_names[self.name] ||= {}
  @@attribute_names[self.name][attr_name.to_sym] = {:type => type, :cardinality => :one}
end

.head(uri, params = {}, options = {}, clazz = self) ⇒ Object



37
38
39
40
# File 'lib/killbill_client/models/resource.rb', line 37

def head(uri, params = {}, options = {}, clazz = self)
  response = KillBillClient::API.head uri, params, options
  from_response clazz, response
end

.instantiate_record_from_json(resource_class, data) ⇒ Object



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
# File 'lib/killbill_client/models/resource.rb', line 143

def instantiate_record_from_json(resource_class, data)
  record = resource_class.send :new

  kb_ancestors = resource_class.ancestors.select { |ancestor| !@@attribute_names[ancestor.name].nil? }
  data.each do |name, value|
    name = Utils.underscore name
    attr_desc = nil

    # Allow for inheritance
    kb_ancestors.each do |ancestor|
      attr_desc = @@attribute_names[ancestor.name][name.to_sym]
      break unless attr_desc.nil?
    end

    unless attr_desc.nil?
      type = attr_desc[:type]
      if attr_desc[:cardinality] == :many && !type.nil? && value.is_a?(Array)
        newValue = []
        value.each do |val|
          if val.is_a?(Hash)
            newValue << instantiate_record_from_json(type, val)
          else
            newValue << val
          end
        end
        value = newValue
      elsif attr_desc[:cardinality] == :one && !type.nil? && value.is_a?(Hash)
        value = instantiate_record_from_json(type, value)
      end
    end #end unless attr_desc.nil? or data_elem.blank?

    # TODO Be lenient for now to support different API formats
    record.send("#{Utils.underscore name}=", value) rescue nil

  end #end data.each

  record
end

.post(uri, body = nil, params = {}, options = {}, clazz = self) ⇒ Object



54
55
56
57
# File 'lib/killbill_client/models/resource.rb', line 54

def post(uri, body = nil, params = {}, options = {}, clazz = self)
  response = KillBillClient::API.post uri, body, params, options
  from_response clazz, response
end

.put(uri, body = nil, params = {}, options = {}, clazz = self) ⇒ Object



59
60
61
62
# File 'lib/killbill_client/models/resource.rb', line 59

def put(uri, body = nil, params = {}, options = {}, clazz = self)
  response = KillBillClient::API.put uri, body, params, options
  from_response clazz, response
end

.raw_get(uri, params = {}, options = {}) ⇒ Object

Performs a GET request and returns the raw response body as received from Kill Bill, without any model parsing or re-serialization.



49
50
51
52
# File 'lib/killbill_client/models/resource.rb', line 49

def raw_get(uri, params = {}, options = {})
  response = KillBillClient::API.get uri, params, options
  response.body
end

.require_multi_tenant_options!(options, msg) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/killbill_client/models/resource.rb', line 29

def require_multi_tenant_options!(options, msg)
  api_key = options[:api_key] || KillBillClient.api_key
  api_secret = options[:api_secret] || KillBillClient.api_secret
  if api_key.nil? || api_secret.nil?
    raise ArgumentError, msg
  end
end

Instance Method Details

#==(o) ⇒ Object Also known as: eql?



275
276
277
# File 'lib/killbill_client/models/resource.rb', line 275

def ==(o)
  o.class == self.class && o.hash == hash
end

#_to_hash(value) ⇒ Object



248
249
250
251
252
253
254
255
256
# File 'lib/killbill_client/models/resource.rb', line 248

def _to_hash(value)
  if value.is_a?(Resource)
    value.to_hash
  elsif value.is_a?(Array)
    value.map { |v| _to_hash(v) }
  else
    value
  end
end

#hashObject



281
282
283
# File 'lib/killbill_client/models/resource.rb', line 281

def hash
  to_hash.hash
end

#refresh(options = {}, clazz = self.class) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
# File 'lib/killbill_client/models/resource.rb', line 262

def refresh(options = {}, clazz=self.class)
  if @uri
    # Need to decode in case an encoding is in place (e.g. /1.0/kb/security/users/Mad%20Max/roles) , since later on
    # it will be encoded and can cause an undesired result on the call.
    unecoded_uri = URI::DEFAULT_PARSER.unescape(@uri)

    self.class.get unecoded_uri, {}, options, clazz
  else
    self
  end
end

#to_hashObject



237
238
239
240
241
242
243
244
245
246
# File 'lib/killbill_client/models/resource.rb', line 237

def to_hash
  json_hash = {}
  self.class.json_attributes.each do |name|
    value = self.send(name)
    unless value.nil?
      json_hash[Utils.camelize name, :lower] = _to_hash(value)
    end
  end
  json_hash
end

#to_json(*args) ⇒ Object



258
259
260
# File 'lib/killbill_client/models/resource.rb', line 258

def to_json(*args)
  to_hash.to_json(*args)
end