Class: SalesforceBulkApi::Job

Inherits:
Object
  • Object
show all
Defined in:
lib/salesforce_bulk_api/job.rb

Defined Under Namespace

Classes: SalesforceException

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Job

Returns a new instance of Job.



8
9
10
11
12
13
14
15
16
17
# File 'lib/salesforce_bulk_api/job.rb', line 8

def initialize(args)
  @job_id         = args[:job_id]
  @operation      = args[:operation]
  @sobject        = args[:sobject]
  @external_field = args[:external_field]
  @records        = args[:records]
  @connection     = args[:connection]
  @batch_ids      = []
  @XML_HEADER     = '<?xml version="1.0" encoding="utf-8" ?>'
end

Instance Attribute Details

#job_idObject (readonly)

Returns the value of attribute job_id.



4
5
6
# File 'lib/salesforce_bulk_api/job.rb', line 4

def job_id
  @job_id
end

Instance Method Details

#add_batch(keys, batch) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/salesforce_bulk_api/job.rb', line 85

def add_batch(keys, batch)
  xml = "#{@XML_HEADER}<sObjects xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
  batch.each do |r|
    xml += create_sobject(keys, r)
  end
  xml += '</sObjects>'
  path = "job/#{@job_id}/batch/"
  headers = Hash["Content-Type" => "application/xml; charset=UTF-8"]
  response = @connection.post_xml(nil, path, xml, headers)
  response_parsed = XmlSimple.xml_in(response)
  response_parsed['id'][0] if response_parsed['id']
end

#add_batchesObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/salesforce_bulk_api/job.rb', line 68

def add_batches
  raise 'Records must be an array of hashes.' unless @records.is_a? Array
  keys = @records.reduce({}) {|h, pairs| pairs.each {|k, v| (h[k] ||= []) << v}; h}.keys

  @records_dup = @records.clone

  super_records = []
  (@records_dup.size / @batch_size).to_i.times do
    super_records << @records_dup.pop(@batch_size)
  end
  super_records << @records_dup unless @records_dup.empty?

  super_records.each do |batch|
    @batch_ids << add_batch(keys, batch)
  end
end

#add_queryObject



58
59
60
61
62
63
64
65
66
# File 'lib/salesforce_bulk_api/job.rb', line 58

def add_query
  path = "job/#{@job_id}/batch/"
  headers = Hash["Content-Type" => "application/xml; charset=UTF-8"]

  response = @connection.post_xml(nil, path, @records, headers)
  response_parsed = XmlSimple.xml_in(response)

  @batch_ids << response_parsed['id'][0]
end

#build_relationship_sobject(key, value) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/salesforce_bulk_api/job.rb', line 115

def build_relationship_sobject(key, value)
  if key.to_s.include? '.'
    relations = key.to_s.split('.')
    parent = relations[0]
    child = relations[1..-1].join('.')
    xml = "<#{parent}>"
    xml += "<sObject>"
    xml += build_relationship_sobject(child, value)
    xml += "</sObject>"
    xml += "</#{parent}>"
  else
    xml = "<#{key}>#{value}</#{key}>"
  end
end

#build_sobject(data) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/salesforce_bulk_api/job.rb', line 98

def build_sobject(data)
  xml = '<sObject>'
  data.keys.each do |k|
    if k.is_a?(Hash)
      xml += build_sobject(k)
    elsif k.to_s.include? '.'
      relations = k.to_s.split('.')
      parent = relations[0]
      child = relations[1..-1].join('.')
      xml += "<#{parent}>#{build_sobject({ child => data[k] })}</#{parent}>"
    elsif data[k] != :type
      xml += "<#{k}>#{data[k]}</#{k}>"
    end
  end
  xml += '</sObject>'
end

#check_batch_status(batch_id) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/salesforce_bulk_api/job.rb', line 172

def check_batch_status(batch_id)
  path = "job/#{@job_id}/batch/#{batch_id}"
  headers = Hash.new

  response = @connection.get_request(nil, path, headers)

  begin
    response_parsed = XmlSimple.xml_in(response) if response
    response_parsed
  rescue StandardError => e
    puts "Error parsing XML response for #{@job_id}, batch #{batch_id}"
    puts e
    puts e.backtrace
  end
end

#check_job_statusObject



157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/salesforce_bulk_api/job.rb', line 157

def check_job_status
  path = "job/#{@job_id}"
  headers = Hash.new
  response = @connection.get_request(nil, path, headers)

  begin
    response_parsed = XmlSimple.xml_in(response) if response
    response_parsed
  rescue StandardError => e
    puts "Error parsing XML response for #{@job_id}"
    puts e
    puts e.backtrace
  end
end

#close_jobObject



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/salesforce_bulk_api/job.rb', line 46

def close_job()
  xml = "#{@XML_HEADER}<jobInfo xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\">"
  xml += "<state>Closed</state>"
  xml += "</jobInfo>"

  path = "job/#{@job_id}"
  headers = Hash['Content-Type' => 'application/xml; charset=utf-8']

  response = @connection.post_xml(nil, path, xml, headers)
  XmlSimple.xml_in(response)
end

#create_job(batch_size, send_nulls, no_null_list) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/salesforce_bulk_api/job.rb', line 19

def create_job(batch_size, send_nulls, no_null_list)
  @batch_size = batch_size
  @send_nulls = send_nulls
  @no_null_list = no_null_list

  xml = "#{@XML_HEADER}<jobInfo xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\">"
  xml += "<operation>#{@operation}</operation>"
  xml += "<object>#{@sobject}</object>"
  # This only happens on upsert
  if !@external_field.nil?
    xml += "<externalIdFieldName>#{@external_field}</externalIdFieldName>"
  end
  xml += "<contentType>XML</contentType>"
  xml += "</jobInfo>"

  path = "job"
  headers = Hash['Content-Type' => 'application/xml; charset=utf-8']

  response = @connection.post_xml(nil, path, xml, headers)
  response_parsed = XmlSimple.xml_in(response)

  # response may contain an exception, so raise it
  raise SalesforceException.new("#{response_parsed['exceptionMessage'][0]} (#{response_parsed['exceptionCode'][0]})") if response_parsed['exceptionCode']

  @job_id = response_parsed['id'][0]
end

#create_sobject(keys, r) ⇒ Object



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
# File 'lib/salesforce_bulk_api/job.rb', line 130

def create_sobject(keys, r)
  sobject_xml = '<sObject>'
  keys.each do |k|
    if r[k].is_a?(Hash)
      sobject_xml += "<#{k}>"
      sobject_xml += build_sobject(r[k])
      sobject_xml += "</#{k}>"
    elsif k.to_s.include? '.'
      sobject_xml += build_relationship_sobject(k, r[k])
    elsif !r[k].to_s.empty?
      sobject_xml += "<#{k}>"
      if r[k].respond_to?(:encode)
        sobject_xml += r[k].encode(:xml => :text)
      elsif r[k].respond_to?(:iso8601) # timestamps
        sobject_xml += r[k].iso8601.to_s
      else
        sobject_xml += r[k].to_s
      end
      sobject_xml += "</#{k}>"
    elsif @send_nulls && !@no_null_list.include?(k) && r.key?(k)
      sobject_xml += "<#{k} xsi:nil=\"true\"/>"
    end
  end
  sobject_xml += '</sObject>'
  sobject_xml
end

#get_batch_records(batch_id) ⇒ Object



249
250
251
252
253
254
255
256
257
258
# File 'lib/salesforce_bulk_api/job.rb', line 249

def get_batch_records(batch_id)
  path = "job/#{@job_id}/batch/#{batch_id}/request"
  headers = Hash["Content-Type" => "application/xml; charset=UTF-8"]

  response = @connection.get_request(nil, path, headers)
  response_parsed = XmlSimple.xml_in(response)
  results = response_parsed['sObject']

  results
end

#get_batch_result(batch_id) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/salesforce_bulk_api/job.rb', line 229

def get_batch_result(batch_id)
  path = "job/#{@job_id}/batch/#{batch_id}/result"
  headers = Hash["Content-Type" => "application/xml; charset=UTF-8"]

  response = @connection.get_request(nil, path, headers)
  response_parsed = XmlSimple.xml_in(response)
  results = response_parsed['result'] unless @operation == 'query'

  if(@operation == 'query') # The query op requires us to do another request to get the results
    result_id = response_parsed["result"][0]
    path = "job/#{@job_id}/batch/#{batch_id}/result/#{result_id}"
    headers = Hash.new
    headers = Hash["Content-Type" => "application/xml; charset=UTF-8"]
    response = @connection.get_request(nil, path, headers)
    response_parsed = XmlSimple.xml_in(response)
    results = response_parsed['records']
  end
  results
end

#get_job_result(return_result, timeout) ⇒ Object



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
# File 'lib/salesforce_bulk_api/job.rb', line 188

def get_job_result(return_result, timeout)
  # timeout is in seconds
  begin
    state = []
    Timeout::timeout(timeout, SalesforceBulkApi::JobTimeout) do
      while true
        job_status = self.check_job_status
        if job_status && job_status['state'] && job_status['state'][0] == 'Closed'
          batch_statuses = {}

          batches_ready = @batch_ids.all? do |batch_id|
            batch_state = batch_statuses[batch_id] = self.check_batch_status(batch_id)
            batch_state && batch_state['state'] && batch_state['state'][0] && !['Queued', 'InProgress'].include?(batch_state['state'][0])
          end

          if batches_ready
            @batch_ids.each do |batch_id|
              state.insert(0, batch_statuses[batch_id])
              @batch_ids.delete(batch_id)
            end
          end
          break if @batch_ids.empty?
        else
          break
        end
      end
    end
  rescue SalesforceBulkApi::JobTimeout => e
    puts 'Timeout waiting for Salesforce to process job batches #{@batch_ids} of job #{@job_id}.'
    puts e
    raise
  end

  state.each_with_index do |batch_state, i|
    if batch_state['state'][0] == 'Completed' && return_result == true
      state[i].merge!({'response' => self.get_batch_result(batch_state['id'][0])})
    end
  end
  state
end