zuora_api 1.4.12 → 1.5.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: ebc4bb86fbbf7590bc62e08d4f0a0159e9685d1c
4
- data.tar.gz: 10c3a81d25f0cfd3503a4ee1ae0661249ddf8b48
3
+ metadata.gz: 9b2a8ddb2245c12bb0d95d1d838a0d39190de064
4
+ data.tar.gz: d4ecd28e223f763e3e7113f720f3d7dc6779f5f3
5
5
  SHA512:
6
- metadata.gz: 21e52ba82573b4d98dd54417145b081488c3f8d7a3b0e4cb2fd0e92bbfd624652bbec24b165bb3281e52d505d9515ef24d89448d2a588aa41d0ea0005ccd54e5
7
- data.tar.gz: f1dd71d072f2dea943722cf9fbc6bad92a8f536a2a02a479a03a340fa8e9111eee5c5761cf99a54f085bd9b2d77f49571ac85762b180358eab9bdf9c5e1106eb
6
+ metadata.gz: 7200923efb484248935190b47b402ad2e987e0f92bd22a3c05576a9934ca635d7d0f9dd6b9ac2c45f9e3cb2035adafaaa5dac21ffcdbb9e1dd099cf2cc164e5f
7
+ data.tar.gz: 4da71d50b312948a08bfee906241a888b9417475fad8dd1d83852940bdb50194ec8142636069b930bd7a16cd3d243bccb81b77e4ebc113320828322b195a2a5a
data/.gitlab-ci.yml CHANGED
@@ -48,3 +48,16 @@ rubygems-deploy:
48
48
  - gem push $version
49
49
  only:
50
50
  - master
51
+
52
+ rubygems-deploy:
53
+ stage: deploy
54
+ allow_failure: false
55
+ when: manual
56
+ script:
57
+ - bundle install
58
+ - gem install rake
59
+ - version=$(rake install | grep -o 'pkg/zuora_api-.*gem')
60
+ - curl -u $USERNAME:$PASSWORD https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials; chmod 0600 ~/.gem/credentials
61
+ - gem push $version
62
+ only:
63
+ - staging
data/lib/zuora_api.rb CHANGED
@@ -2,6 +2,7 @@ require 'rails'
2
2
  require "zuora_api/login"
3
3
  require 'zuora_api/exceptions'
4
4
  require "insights_api/login"
5
+ require "zuora_api/metrics_helper"
5
6
  module ZuoraAPI
6
7
  # Your code goes here...
7
8
  end
@@ -1,10 +1,12 @@
1
1
  require "httparty"
2
2
  require "nokogiri"
3
+ require "uri"
4
+
3
5
  module ZuoraAPI
4
6
  class Login
5
7
  ENVIRONMENTS = [SANDBOX = 'Sandbox', PRODUCTION = 'Production', PREFORMANCE = 'Preformance', SERVICES = 'Services', UNKNOWN = 'Unknown' ]
6
8
  REGIONS = [EU = 'EU', US = 'US' ]
7
- XML_SAVE_OPTIONS = Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
9
+ XML_SAVE_OPTIONS = Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
8
10
  attr_accessor :username, :password, :region,:url, :wsdl_number, :current_session, :environment, :status, :errors, :current_error, :user_info, :tenant_id, :tenant_name, :entity_id, :timeout_sleep
9
11
 
10
12
  def initialize(username: nil, password: nil, status: nil, url: nil, entity_id: nil, session: nil, **keyword_args)
@@ -41,7 +43,6 @@ module ZuoraAPI
41
43
  }
42
44
  end
43
45
 
44
-
45
46
  def update_environment
46
47
  if !self.url.blank?
47
48
  env_path = self.url.split('https://').last.split('.zuora.com').first
@@ -114,12 +115,12 @@ module ZuoraAPI
114
115
  end
115
116
  end
116
117
  end
117
-
118
+
118
119
 
119
120
  input_xml = Nokogiri::XML(request.to_xml(:save_with => XML_SAVE_OPTIONS).strip)
120
121
  input_xml.xpath('//ns1:session', 'ns1' =>'http://api.zuora.com/').children.remove
121
122
  Rails.logger.debug('Connect') {"Request SOAP XML: #{input_xml.to_xml(:save_with => XML_SAVE_OPTIONS).strip}"} if debug
122
-
123
+
123
124
  @response_query = HTTParty.post(self.url,:body => request.to_xml(:save_with => XML_SAVE_OPTIONS).strip, :headers => {'Content-Type' => "text/xml; charset=utf-8"}, :timeout => 10)
124
125
  @output_xml = Nokogiri::XML(@response_query.body)
125
126
  Rails.logger.debug('Connect') {"Response SOAP XML: #{@output_xml.to_xml(:save_with => XML_SAVE_OPTIONS).strip}"} if debug
@@ -174,16 +175,16 @@ module ZuoraAPI
174
175
  else
175
176
  #If Session only is used for Gem TODO Depercate
176
177
  if (self.password.blank? && self.current_session.present?)
177
- self.current_session = self.current_session
178
+ self.current_session = self.current_session
178
179
  self.username = @output_xml.xpath('//ns1:Username', 'ns1' =>'http://api.zuora.com/').text if self.username.blank?
179
-
180
+
180
181
  #Username & password combo
181
182
  elsif (self.password.present? && self.username.present?)
182
183
  retrieved_session = @output_xml.xpath('//ns1:Session', 'ns1' =>'http://api.zuora.com/').text
183
184
  raise ZuoraAPI::Exceptions::ZuoraAPISessionError.new("No session found for api call.") if retrieved_session.blank?
184
185
  self.current_session = retrieved_session
185
186
  end
186
-
187
+
187
188
  self.current_error = nil
188
189
  self.status = 'Active'
189
190
  end
@@ -209,6 +210,9 @@ module ZuoraAPI
209
210
 
210
211
  def soap_call(ns1: 'ns1', ns2: 'ns2', batch_size: nil, single_transaction: false, debug: true, errors: [ZuoraAPI::Exceptions::ZuoraAPISessionError, ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition], z_session: true, timeout_retry: false, timeout: 120,**keyword_args)
211
212
  tries ||= 2
213
+ error_type = ""
214
+ start_time = Time.now
215
+
212
216
  xml = Nokogiri::XML::Builder.new do |xml|
213
217
  xml['SOAP-ENV'].Envelope('xmlns:SOAP-ENV' => "http://schemas.xmlsoap.org/soap/envelope/",
214
218
  "xmlns:#{ns2}" => "http://object.api.zuora.com/",
@@ -239,13 +243,15 @@ module ZuoraAPI
239
243
  input_xml = Nokogiri::XML(xml.to_xml(:save_with => XML_SAVE_OPTIONS).strip)
240
244
  input_xml.xpath('//ns1:session', 'ns1' =>'http://api.zuora.com/').children.remove
241
245
  Rails.logger.debug('Connect') {"Request SOAP XML: #{input_xml.to_xml(:save_with => XML_SAVE_OPTIONS).strip}"} if debug
246
+
242
247
  response = HTTParty.post(self.url,:body => xml.doc.to_xml(:save_with => XML_SAVE_OPTIONS).strip, :headers => {'Content-Type' => "text/xml; charset=utf-8"}, :timeout => timeout)
243
248
  output_xml = Nokogiri::XML(response.body)
244
249
  Rails.logger.debug('Connect') {"Response SOAP XML: #{output_xml.to_xml(:save_with => XML_SAVE_OPTIONS).strip}"} if debug
245
250
 
246
251
  raise_errors(type: :SOAP, body: output_xml, response: response)
247
-
252
+
248
253
  rescue ZuoraAPI::Exceptions::ZuoraAPISessionError => ex
254
+ error_type = "#{ex.class}"
249
255
  if !(tries -= 1).zero? && z_session
250
256
  Rails.logger.debug {"Session Invalid"}
251
257
  self.new_session
@@ -258,12 +264,14 @@ module ZuoraAPI
258
264
  end
259
265
  end
260
266
  rescue ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition => ex
267
+ error_type = "#{ex.class}"
261
268
  if errors.include?(ex.class)
262
269
  raise ex
263
270
  else
264
271
  return output_xml, input_xml, response
265
272
  end
266
273
  rescue Net::OpenTimeout, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex
274
+ error_type = "#{ex.class}"
267
275
  if !(tries -= 1).zero? && timeout_retry
268
276
  Rails.logger.info {"#{ex.class} Timed out will retry after 5 seconds"}
269
277
  sleep(self.timeout_sleep)
@@ -272,9 +280,21 @@ module ZuoraAPI
272
280
  raise ex
273
281
  end
274
282
  rescue => ex
283
+ error_type = "#{ex.class}"
275
284
  raise ex
276
285
  else
277
286
  return output_xml, input_xml, response
287
+ ensure
288
+ # Writing to telegraf
289
+ begin
290
+ end_time = Time.now
291
+ response_time = end_time - start_time
292
+ status_code = response.code if response
293
+ endpoint_name = url.present? ? URI(url).host : url
294
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "POST")
295
+ rescue
296
+ Rails.logger.info {"Failed to send metric"}
297
+ end
278
298
  end
279
299
 
280
300
  def raise_errors(type: :SOAP, body: nil, response: nil)
@@ -287,7 +307,7 @@ module ZuoraAPI
287
307
  error = body.xpath('//faultcode').text
288
308
  message = body.xpath('//faultstring').text
289
309
  end
290
-
310
+
291
311
  if error.blank? || message.blank?
292
312
  error = body.xpath('//ns1:Code', 'ns1' =>'http://api.zuora.com/').text
293
313
  message = body.xpath('//ns1:Message', 'ns1' =>'http://api.zuora.com/').text
@@ -298,9 +318,9 @@ module ZuoraAPI
298
318
  error = []
299
319
  success = []
300
320
  body.xpath('//ns1:result', 'ns1' =>'http://api.zuora.com/').each_with_index do |call, object_index|
301
-
321
+
302
322
  if call.xpath('./ns1:Success', 'ns1' =>'http://api.zuora.com/').text == 'false'
303
- message = "#{call.xpath('./*/ns1:Code', 'ns1' =>'http://api.zuora.com/').text}::#{call.xpath('./*/ns1:Message', 'ns1' =>'http://api.zuora.com/').text}"
323
+ message = "#{call.xpath('./*/ns1:Code', 'ns1' =>'http://api.zuora.com/').text}::#{call.xpath('./*/ns1:Message', 'ns1' =>'http://api.zuora.com/').text}"
304
324
  error.push(message)
305
325
  else
306
326
  success.push(call.xpath('./ns1:Id', 'ns1' =>'http://api.zuora.com/').text)
@@ -332,7 +352,7 @@ module ZuoraAPI
332
352
  raise ZuoraAPI::Exceptions::ZuoraAPIRequestLimit.new("The total number of concurrent requests has exceeded the limit allowed by the system. Please resubmit your request later.", body, response.code)
333
353
  end
334
354
 
335
- when :JSON
355
+ when :JSON
336
356
  if body.class == Hash && (!body["success"] || !body["Success"] || response.code != 200)
337
357
  messages_array = (body["reasons"] || []).map {|error| error['message']}.compact
338
358
  codes_array = (body["reasons"] || []).map {|error| error['code']}.compact
@@ -358,7 +378,7 @@ module ZuoraAPI
358
378
  end
359
379
 
360
380
  #All Errors catch
361
- if codes_array.size > 0
381
+ if codes_array.size > 0
362
382
  raise ZuoraAPI::Exceptions::ZuoraAPIError.new("#{messages_array.join(', ')}", body, response.code)
363
383
  end
364
384
 
@@ -375,7 +395,7 @@ module ZuoraAPI
375
395
  raise ZuoraAPI::Exceptions::ZuoraAPISessionError.new("#{body["faultcode"]}::#{body["faultstring"]}", body, response.code)
376
396
  else
377
397
  raise ZuoraAPI::Exceptions::ZuoraAPIError.new("#{body["faultcode"]}::#{body["faultstring"]}", body, response.code)
378
- end
398
+ end
379
399
  end
380
400
 
381
401
  if body["Errors"].present? || body["errors"].present?
@@ -387,14 +407,14 @@ module ZuoraAPI
387
407
  end
388
408
  end
389
409
  end
390
-
410
+
391
411
  #Zuora REST Actions error (Create, Update, Delete)
392
412
  if body.class == Array
393
413
  all_errors = body.select {|obj| !obj['Success'] || !obj['success'] }.map {|obj| obj['Errors'] || obj['errors'] }.compact
394
414
  all_success = body.select {|obj| obj['Success'] || obj['success']}.compact
395
415
 
396
- if all_errors.size > 0
397
- raise ZuoraAPI::Exceptions::ZuoraAPIError.new("#{all_errors.flatten.group_by {|error| error['Message']}.keys.uniq.join(' ')}", body, response.code, all_errors, all_success )
416
+ if all_errors.size > 0
417
+ raise ZuoraAPI::Exceptions::ZuoraAPIError.new("#{all_errors.flatten.group_by {|error| error['Message']}.keys.uniq.join(' ')}", body, response.code, all_errors, all_success )
398
418
  end
399
419
  end
400
420
 
@@ -402,7 +422,7 @@ module ZuoraAPI
402
422
  if response.code != 200
403
423
  if response.code == 429
404
424
  raise ZuoraAPI::Exceptions::ZuoraAPIRequestLimit.new("The total number of concurrent requests has exceeded the limit allowed by the system. Please resubmit your request later.", body, response.code)
405
- else
425
+ else
406
426
  raise ZuoraAPI::Exceptions::ZuoraAPIError.new("#{response.message}", body, response.code)
407
427
  end
408
428
  end
@@ -449,11 +469,16 @@ module ZuoraAPI
449
469
 
450
470
  def describe_call(object = nil)
451
471
  tries ||= 2
472
+
473
+ error_type = ""
474
+ start_time = Time.now
475
+
452
476
  self.get_session
453
477
  base = self.url.include?(".com") ? self.url.split(".com")[0].concat(".com") : self.url.split(".eu")[0].concat(".eu")
454
478
  url = object ? "#{base}/apps/api/describe/#{object}" : "#{base}/apps/api/describe/"
455
479
  headers = !self.entity_id.blank? ? {"entityId" => self.entity_id, 'Content-Type' => "text/xml; charset=utf-8"} : {'Content-Type' => "text/xml; charset=utf-8"}
456
- response = HTTParty.get(url, :headers => headers , basic_auth: {:username => self.username, :password => self.password}, :timeout => 120)
480
+ response = HTTParty.get(url, :headers => headers , basic_auth: {:username => self.username, :password => self.password}, :timeout => 1)
481
+
457
482
  output_xml = Nokogiri::XML(response.body)
458
483
  des_hash = Hash.new
459
484
  if object == nil
@@ -484,6 +509,7 @@ module ZuoraAPI
484
509
  des_hash[:related_objects] = output_xml.xpath(".//related-objects").xpath(".//object").map{ |x| [x.xpath(".//name").text.to_sym, [ [:url, x.attributes["href"].value], [:label, x.xpath(".//name").text ] ].to_h] }.to_h
485
510
  end
486
511
  rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex
512
+ error_type = "#{ex.class}"
487
513
  if !(tries -= 1).zero?
488
514
  Rails.logger.info {"#{ex.class} Timed out will retry after 5 seconds"}
489
515
  sleep(self.timeout_sleep)
@@ -492,18 +518,32 @@ module ZuoraAPI
492
518
  raise ex
493
519
  end
494
520
  rescue => ex
521
+ error_type = "#{ex.class}"
495
522
  raise ex
496
523
  else
497
524
  return des_hash
525
+ ensure
526
+ # Writing to telegraf
527
+ begin
528
+ end_time = Time.now
529
+ response_time = end_time - start_time
530
+ status_code = response.code if response
531
+ endpoint_name = url.present? ? URI(url).host : url
532
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "GET")
533
+ rescue
534
+ Rails.logger.info {"Failed to send metric"}
535
+ end
498
536
  end
499
537
 
500
538
  def rest_call(method: :get, body: {},headers: {}, url: rest_endpoint("catalog/products?pageSize=4"), debug: true, errors: [ZuoraAPI::Exceptions::ZuoraAPISessionError, ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition], z_session: true, timeout_retry: false, timeout: 120, **keyword_args)
501
539
  tries ||= 2
502
540
  headers["entityId"] = self.entity_id if !self.entity_id.blank?
503
541
  raise "Method not supported, supported methods include: :get, :post, :put, :delete, :patch, :head, :options" if ![:get, :post, :put, :delete, :patch, :head, :options].include?(method)
542
+
543
+ error_type = ""
544
+ start_time = Time.now
504
545
  response = HTTParty::Request.new("Net::HTTP::#{method.to_s.capitalize}".constantize, url, body: body, headers: {'Content-Type' => "application/json; charset=utf-8"}.merge(z_session ? {"Authorization" => "ZSession #{self.get_session}"} : {}).merge(headers), timeout: timeout).perform
505
546
 
506
- Rails.logger.debug('Connect') {"Response Code: #{response.code}" } if debug
507
547
  begin
508
548
  output_json = JSON.parse(response.body)
509
549
  rescue JSON::ParserError => ex
@@ -514,6 +554,7 @@ module ZuoraAPI
514
554
  raise_errors(type: :JSON, body: output_json, response: response)
515
555
 
516
556
  rescue ZuoraAPI::Exceptions::ZuoraAPISessionError => ex
557
+ error_type = "#{ex.class}"
517
558
  if !(tries -= 1).zero? && z_session
518
559
  Rails.logger.debug {"Session Invalid"}
519
560
  self.new_session
@@ -526,12 +567,14 @@ module ZuoraAPI
526
567
  end
527
568
  end
528
569
  rescue ZuoraAPI::Exceptions::ZuoraAPIError, ZuoraAPI::Exceptions::ZuoraAPIRequestLimit, ZuoraAPI::Exceptions::ZuoraAPILockCompetition => ex
570
+ error_type = "#{ex.class}"
529
571
  if errors.include?(ex.class)
530
572
  raise ex
531
573
  else
532
574
  return [output_json, response]
533
575
  end
534
576
  rescue Net::OpenTimeout, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex
577
+ error_type = "#{ex.class}"
535
578
  if !(tries -= 1).zero? && timeout_retry
536
579
  Rails.logger.info {"#{ex.class} Timed out will retry after 5 seconds"}
537
580
  sleep(self.timeout_sleep)
@@ -540,9 +583,21 @@ module ZuoraAPI
540
583
  raise ex
541
584
  end
542
585
  rescue => ex
586
+ error_type = "#{ex.class}"
543
587
  raise ex
544
588
  else
545
589
  return [output_json, response]
590
+ ensure
591
+ # Writing to telegraf
592
+ begin
593
+ end_time = Time.now
594
+ response_time = end_time - start_time
595
+ status_code = response.code if response
596
+ endpoint_name = url.present? ? URI(url).host : url
597
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "#{method.upcase}")
598
+ rescue
599
+ Rails.logger.info {"Failed to send metric"}
600
+ end
546
601
  end
547
602
 
548
603
  def update_create_tenant
@@ -598,9 +653,12 @@ module ZuoraAPI
598
653
  require 'fileutils'
599
654
  FileUtils.mkdir_p(file_path) unless File.exists?(file_path)
600
655
 
656
+ error_type = ""
657
+ start_time = Time.now
658
+
601
659
  begin
660
+ status_code = nil
602
661
  uri = URI.parse(url)
603
-
604
662
  http = Net::HTTP.new(uri.host, uri.port)
605
663
  http.read_timeout = timeout #Seconds
606
664
  http.use_ssl = true if uri.scheme.downcase == 'https'
@@ -609,6 +667,8 @@ module ZuoraAPI
609
667
  response_save = nil
610
668
  http.request_get(uri.path, headers) do |response|
611
669
  response_save = response
670
+ status_code = response.code if response
671
+
612
672
  case response
613
673
  when Net::HTTPNotFound
614
674
  Rails.logger.fatal("404 - Not Found")
@@ -694,18 +754,32 @@ module ZuoraAPI
694
754
 
695
755
  file_handle.close
696
756
  Rails.logger.info("Filepath: #{file_handle.path} Size: #{File.size(file_handle.path).to_f/1000000} mb")
697
-
757
+
698
758
  return file_handle
699
759
  end
700
760
  end
701
761
  rescue Exception => e
762
+ error_type = "#{e.class}"
702
763
  Rails.logger.fatal('GetFile') {"Download Failed: #{response_save} - #{e.class} : #{e.message}"}
703
764
  Rails.logger.fatal('GetFile') {"Download Failed: #{e.backtrace.join("\n")}"}
704
765
  raise
766
+ ensure
767
+ # Writing to telegraf
768
+ begin
769
+ end_time = Time.now
770
+ response_time = end_time - start_time
771
+ status_code = response.code if response
772
+ endpoint_name = url.present? ? URI(url).host : url
773
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "GET")
774
+ rescue
775
+ Rails.logger.info {"Failed to send metric"}
776
+ end
705
777
  end
706
778
  end
707
779
 
708
780
  def getDataSourceExport(query, extract: true, encrypted: false, zip: true)
781
+ error_type = ""
782
+ start_time = Time.now
709
783
  Rails.logger.info('Export') {"Build export"}
710
784
  Rails.logger.debug('Export query') {"#{query}"}
711
785
  request = Nokogiri::XML::Builder.new do |xml|
@@ -728,7 +802,23 @@ module ZuoraAPI
728
802
  end
729
803
  end
730
804
  end
731
- response_query = HTTParty.post(self.url, body: request.to_xml(:save_with => XML_SAVE_OPTIONS).strip, headers: {'Content-Type' => "application/json; charset=utf-8"}, :timeout => 120)
805
+
806
+ begin
807
+ response_query = HTTParty.post(self.url, body: request.to_xml(:save_with => XML_SAVE_OPTIONS).strip, headers: {'Content-Type' => "application/json; charset=utf-8"}, :timeout => 120)
808
+ rescue => e
809
+ error_type = "#{e.class}"
810
+ ensure
811
+ begin
812
+ end_time = Time.now
813
+ response_time = end_time - start_time
814
+ status_code = response.code if response
815
+ endpoint_name = url.present? ? URI(url).host : url
816
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "POST")
817
+ rescue
818
+ Rails.logger.info {"Failed to send metric"}
819
+ end
820
+ end
821
+
732
822
  output_xml = Nokogiri::XML(response_query.body)
733
823
 
734
824
  raise 'Export Creation Unsuccessful : ' + output_xml.xpath('//ns1:Message', 'ns1' =>'http://api.zuora.com/').text if output_xml.xpath('//ns1:Success', 'ns1' =>'http://api.zuora.com/').text != "true"
@@ -749,15 +839,35 @@ module ZuoraAPI
749
839
  end
750
840
  end
751
841
  result = 'Waiting'
842
+
843
+ start_time = Time.now
844
+ error_type = ""
845
+
752
846
  while result != "Completed"
753
847
  sleep 3
754
- response_query = HTTParty.post(self.url, body: confirmRequest.to_xml(:save_with => XML_SAVE_OPTIONS).strip, headers: {'Content-Type' => "application/json; charset=utf-8"}, :timeout => 120)
848
+ begin
849
+ response_query = HTTParty.post(self.url, body: confirmRequest.to_xml(:save_with => XML_SAVE_OPTIONS).strip, headers: {'Content-Type' => "application/json; charset=utf-8"}, :timeout => 120)
850
+ rescue => e
851
+ error_type = "#{e.class}"
852
+ end
755
853
  output_xml = Nokogiri::XML(response_query.body)
756
-
757
854
  result = output_xml.xpath('//ns2:Status', 'ns2' =>'http://object.api.zuora.com/').text
855
+ status_code = response_query.code if response_query
758
856
  raise "Export Creation Unsuccessful : #{output_xml.xpath('//ns1:Message', 'ns1' =>'http://api.zuora.com/').text}" if result.blank? || result == "Failed"
759
857
  end
760
858
 
859
+ begin
860
+ end_time = Time.now
861
+ response_time = end_time - start_time
862
+ status_code = response.code if response
863
+ endpoint_name = url.present? ? URI(url).host : url
864
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "POST")
865
+ rescue
866
+ Rails.logger.info {"Failed to send metric"}
867
+ end
868
+
869
+
870
+
761
871
  file_id = output_xml.xpath('//ns2:FileId', 'ns2' =>'http://object.api.zuora.com/').text
762
872
  Rails.logger.info('Export') {'=====> Export finished'}
763
873
  export_file = get_file(:url => self.fileURL(file_id))
@@ -785,7 +895,7 @@ module ZuoraAPI
785
895
  end
786
896
  end
787
897
  if parse
788
- return [] if output_xml.xpath('//ns1:size', 'ns1' =>'http://api.zuora.com/').text == '0'
898
+ return [] if output_xml.xpath('//ns1:size', 'ns1' =>'http://api.zuora.com/').text == '0'
789
899
  data = output_xml.xpath('//ns1:records', 'ns1' =>'http://api.zuora.com/').map {|record| record.children.map {|element| [element.name, element.text]}.to_h}
790
900
  return data
791
901
  else
@@ -794,14 +904,33 @@ module ZuoraAPI
794
904
  end
795
905
 
796
906
  def createJournalRun(call)
907
+ error_type = ""
908
+ start_time = Time.now
909
+
797
910
  url = rest_endpoint("/journal-runs")
798
911
  uri = URI(url)
799
912
  req = Net::HTTP::Post.new(uri,initheader = {'Content-Type' =>'application/json'})
800
913
  req.basic_auth self.username, self.password
801
914
  req.body = call
802
- response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
803
- http.request req
915
+
916
+ begin
917
+ response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
918
+ http.request req
919
+ end
920
+ rescue => e
921
+ error_type = "#{e.class}"
922
+ ensure
923
+ begin
924
+ end_time = Time.now
925
+ response_time = end_time - start_time
926
+ status_code = response.code if response
927
+ endpoint_name = url.present? ? URI(url).host : url
928
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "POST")
929
+ rescue
930
+ Rails.logger.info {"Failed to send metric"}
931
+ end
804
932
  end
933
+
805
934
  Rails.logger.debug('Journal Run') {"Response #{response.code} #{response.message}:
806
935
  #{response.body}"}
807
936
 
@@ -814,17 +943,39 @@ module ZuoraAPI
814
943
  Rails.logger.debug('Journal Run') {"Journal Run failed with message #{message}"}
815
944
  return result
816
945
  end
946
+
817
947
  end
818
948
 
819
949
  def checkJRStatus(jrNumber)
950
+ error_type = ""
951
+
820
952
  Rails.logger.info('Journal Run') {"Check for completion"}
953
+
954
+ start_time = Time.now
955
+
821
956
  url = rest_endpoint("/journal-runs/#{jrNumber}")
822
957
  uri = URI(url)
823
958
  req = Net::HTTP::Get.new(uri,initheader = {'Content-Type' =>'application/json'})
824
959
  req.basic_auth self.username, self.password
825
- response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
826
- http.request req
960
+
961
+ begin
962
+ response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
963
+ http.request req
964
+ end
965
+ rescue => e
966
+ error_type = "#{e.class}"
967
+ ensure
968
+ begin
969
+ end_time = Time.now
970
+ response_time = end_time - start_time
971
+ status_code = response.code if response
972
+ endpoint_name = url.present? ? URI(url).host : url
973
+ ::MetricsHelpers::MetricsHelpers.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "GET")
974
+ rescue
975
+ Rails.logger.info {"Failed to send metric"}
976
+ end
827
977
  end
978
+
828
979
  result = JSON.parse(response.body)
829
980
 
830
981
  if result["success"]
@@ -0,0 +1,12 @@
1
+ module MetricsHelpers
2
+
3
+ class MetricsHelpers
4
+ def self.write_to_telegraf(response_time: nil, status_code: nil, endpoint_name: nil, direction: nil, error_type: nil, function_name: nil, method_name: nil)
5
+ if Gem.loaded_specs.has_key?('zuora_connect') && defined?(::ZuoraConnect::AppInstance.write_to_telegraf)
6
+ Thread.current[:appinstance].present? ? app_instance = Thread.current[:appinstance].id : app_instance = 0
7
+ ZuoraConnect::AppInstanceBase.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "app_instance": app_instance, "function_name": function_name, "method_name": method_name)
8
+ end
9
+ end
10
+ end
11
+
12
+ end
@@ -1,3 +1,3 @@
1
1
  module ZuoraAPI
2
- VERSION = "1.4.12"
2
+ VERSION = "1.5.0"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: zuora_api
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.12
4
+ version: 1.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Zuora Strategic Solutions Group
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2018-05-19 00:00:00.000000000 Z
11
+ date: 2018-08-14 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -163,6 +163,7 @@ files:
163
163
  - lib/zuora_api.rb
164
164
  - lib/zuora_api/exceptions.rb
165
165
  - lib/zuora_api/login.rb
166
+ - lib/zuora_api/metrics_helper.rb
166
167
  - lib/zuora_api/version.rb
167
168
  - zuora_api.gemspec
168
169
  homepage: https://connect.zuora.com