Class: RForce::Binding

Inherits:
Object
  • Object
show all
Includes:
RForce
Defined in:
lib/rforce/binding.rb

Overview

Implements the connection to the Salesforce server.

Constant Summary collapse

DEFAULT_BATCH_SIZE =

Increase the maximum fetch size to 2000, as allowed by Salesforce Added by Raymond Gao

2000
Envelope =

Fill in the guts of this typical SOAP envelope with the session ID and the body of the SOAP request.

<<-HERE
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:partner="urn:partner.soap.sforce.com"
xmlns:spartner="urn:sobject.partner.soap.sforce.com">
  <soap:Header>
<partner:SessionHeader soap:mustUnderstand='1'>
  <partner:sessionId>%s</partner:sessionId>
</partner:SessionHeader>
%s
  </soap:Header>
  <soap:Body>
%s
  </soap:Body>
</soap:Envelope>
HERE
QueryOptions =
'<partner:QueryOptions soap:mustUnderstand=\'1\'><partner:batchSize>%d</partner:batchSize></partner:QueryOptions>'
AssignmentRuleHeaderUsingRuleId =
'<partner:AssignmentRuleHeader soap:mustUnderstand="1"><partner:assignmentRuleId>%s</partner:assignmentRuleId></partner:AssignmentRuleHeader>'
AssignmentRuleHeaderUsingDefaultRule =
'<partner:AssignmentRuleHeader soap:mustUnderstand="1"><partner:useDefaultRule>true</partner:useDefaultRule></partner:AssignmentRuleHeader>'
MruHeader =
'<partner:MruHeader soap:mustUnderstand="1"><partner:updateMru>true</partner:updateMru></partner:MruHeader>'
ClientIdHeader =
'<partner:CallOptions soap:mustUnderstand="1"><partner:client>%s</partner:client></partner:CallOptions>'

Constants included from RForce

SoapResponse, VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from RForce

#expand

Constructor Details

#initialize(url, sid = nil, oauth = nil, proxy = nil, logger = nil) ⇒ Binding

Create a binding to the server (after which you can call login or login_with_oauth to connect to it). If you pass an oauth hash, it must contain the keys :consumer_key, :consumer_secret, :access_token, :access_secret, and :login_url.

proxy may be a URL of the form user:[email protected]:port

if a logger is specified, it will be used for very verbose SOAP logging



56
57
58
59
60
61
62
63
# File 'lib/rforce/binding.rb', line 56

def initialize(url, sid = nil, oauth = nil, proxy = nil, logger = nil)
  @session_id = sid
  @oauth = oauth
  @proxy = proxy
  @batch_size = DEFAULT_BATCH_SIZE
  @logger = logger
  @url = URI.parse(url)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Turns method calls on this object into remote SOAP calls.



294
295
296
297
298
299
300
# File 'lib/rforce/binding.rb', line 294

def method_missing(method, *args)
  unless args.empty? || (args.size == 1 && [Hash, Array].include?(args[0].class))
    raise 'Expected at most 1 Hash or Array argument'
  end

  call_remote method, args[0] || []
end

Instance Attribute Details

#assignment_rule_idObject

Returns the value of attribute assignment_rule_id.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def assignment_rule_id
  @assignment_rule_id
end

#batch_sizeObject

Returns the value of attribute batch_size.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def batch_size
  @batch_size
end

#client_idObject

Returns the value of attribute client_id.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def client_id
  @client_id
end

#trigger_auto_response_emailObject

Returns the value of attribute trigger_auto_response_email.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def trigger_auto_response_email
  @trigger_auto_response_email
end

#trigger_other_emailObject

Returns the value of attribute trigger_other_email.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def trigger_other_email
  @trigger_other_email
end

#trigger_user_emailObject

Returns the value of attribute trigger_user_email.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def trigger_user_email
  @trigger_user_email
end

#update_mruObject

Returns the value of attribute update_mru.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def update_mru
  @update_mru
end

#urlObject

Returns the value of attribute url.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def url
  @url
end

#use_default_ruleObject

Returns the value of attribute use_default_rule.



17
18
19
# File 'lib/rforce/binding.rb', line 17

def use_default_rule
  @use_default_rule
end

Instance Method Details

#call_remote(method, args) ⇒ Object

Call a method on the remote server. Arguments can be a hash or (if order is important) an array of alternating keys and values.



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
# File 'lib/rforce/binding.rb', line 138

def call_remote(method, args)
  @server ||= create_server(@url)

  # Different URI requirements for regular vs. OAuth.  This is
  # *screaming* for a refactor.
  fallback_soap_url = @oauth ? @url.to_s : @url.path

  urn, soap_url = block_given? ? yield : ["urn:partner.soap.sforce.com", fallback_soap_url]

  # Create XML text from the arguments.
  expanded = ''
  @builder = Builder::XmlMarkup.new(:target => expanded)
  expand(@builder, {method => args}, urn)

  extra_headers = ""

  # QueryOptions is not valid when making an Apex Webservice SOAP call
  if !block_given?
    extra_headers << (QueryOptions % @batch_size)
  end

  extra_headers << (AssignmentRuleHeaderUsingRuleId % assignment_rule_id) if assignment_rule_id
  extra_headers << AssignmentRuleHeaderUsingDefaultRule if use_default_rule
  extra_headers << MruHeader if update_mru
  extra_headers << (ClientIdHeader % client_id) if client_id

  if trigger_user_email or trigger_other_email or trigger_auto_response_email
    extra_headers << '<partner:EmailHeader soap:mustUnderstand="1">'

    extra_headers << '<partner:triggerUserEmail>true</partner:triggerUserEmail>' if trigger_user_email
    extra_headers << '<partner:triggerOtherEmail>true</partner:triggerOtherEmail>' if trigger_other_email
    extra_headers << '<partner:triggerAutoResponseEmail>true</partner:triggerAutoResponseEmail>' if trigger_auto_response_email

    extra_headers << '</partner:EmailHeader>'
  end

  # Fill in the blanks of the SOAP envelope with our
  # session ID and the expanded XML of our request.
  request = (Envelope % [@session_id, extra_headers, expanded])
  @logger && @logger.info("RForce request: #{request}")

  # reset the batch size for the next request
  @batch_size = DEFAULT_BATCH_SIZE

  # gzip request
  request = encode(request)

  headers = {
    'Connection' => 'Keep-Alive',
    'Content-Type' => 'text/xml',
    'SOAPAction' => '""',
    'User-Agent' => 'activesalesforce rforce/1.0'
  }

  unless show_debug
    headers['Accept-Encoding'] = 'gzip'
    headers['Content-Encoding'] = 'gzip'
  end

  # Send the request to the server and read the response.
  @logger && @logger.info("RForce request to host #{@server} url #{soap_url} headers: #{headers}")
  response = @server.post2(soap_url, request.lstrip, headers)

  # decode if we have encoding
  content = decode(response)

  # Fix charset encoding. Needed because the "content" variable may contain a UTF-8
  # or ISO-8859-1 string, but is carrying the US-ASCII encoding.
  content = fix_encoding(content)

  # Check to see if INVALID_SESSION_ID was raised and try to relogin in
  if method != :login and @session_id and content =~ /sf:INVALID_SESSION_ID/
    if @user
      (@user, @password)
    else
      raise "INVALID_SESSION_ID"
    end

    # repackage and rencode request with the new session id
    request = (Envelope % [@session_id, extra_headers, expanded])
    request = encode(request)

    # Send the request to the server and read the response.
    response = @server.post2(soap_url, request.lstrip, headers)

    content = decode(response)

    # Fix charset encoding. Needed because the "content" variable may contain a UTF-8
    # or ISO-8859-1 string, but is carrying the US-ASCII encoding.
    content = fix_encoding(content)
  end

  @logger && @logger.info("RForce response: #{content}")
  SoapResponse.new(content).parse
end

#create_server(url) ⇒ Object



69
70
71
72
73
74
75
76
77
78
# File 'lib/rforce/binding.rb', line 69

def create_server(url)
  server = Net::HTTP.Proxy(@proxy).new(url.host, url.port)
  server.use_ssl = (url.scheme == 'https')
  server.verify_mode = OpenSSL::SSL::VERIFY_NONE

  # run ruby with -d or env variable SHOWSOAP=true to see SOAP wiredumps.
  server.set_debug_output $stderr if show_debug

  return server
end

#decode(response) ⇒ Object

decode gzip



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/rforce/binding.rb', line 235

def decode(response)
  encoding = response['Content-Encoding']

  # return body if no encoding
  if !encoding then return response.body end

  # decode gzip
  case encoding.strip
  when 'gzip' then
    begin
      gzr = Zlib::GzipReader.new(StringIO.new(response.body))
      decoded = gzr.read
    ensure
      gzr.close
    end
    decoded
  else
    response.body
  end
end

#encode(request) ⇒ Object

encode gzip



257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/rforce/binding.rb', line 257

def encode(request)
  return request if show_debug

  begin
    ostream = StringIO.new
    gzw = Zlib::GzipWriter.new(ostream)
    gzw.write(request)
    ostream.string
  ensure
    gzw.close
  end
end

#fix_encoding(string) ⇒ Object

fix invalid US-ASCII strings by applying the correct encoding on ruby 1.9+



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/rforce/binding.rb', line 271

def fix_encoding(string)
  if [:valid_encoding?, :force_encoding].all? { |m| string.respond_to?(m) }
    if !string.valid_encoding?
      # The 2 possible encodings in responses are UTF-8 and ISO-8859-1
      # http://www.salesforce.com/us/developer/docs/api/Content/implementation_considerations.htm#topic-title_international
      #
      ["UTF-8", "ISO-8859-1"].each do |encoding_name|

        s = string.dup.force_encoding(encoding_name)

        if s.valid_encoding?
          return s
        end
      end

      raise "Invalid encoding in SOAP response: not in [US-ASCII, UTF-8, ISO-8859-1]"
    end
  end

  return string
end

#login(user, password) ⇒ Object

Log in to the server with a user name and password, remembering the session ID returned to us by Salesforce.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rforce/binding.rb', line 82

def (user, password)
  @user     = user
  @password = password
  @server   = create_server(@url)
  response  = call_remote(:login, [:username, user, :password, password])

  raise "Incorrect user name / password [#{response.Fault}]" unless response.loginResponse

  result      = response[:loginResponse][:result]
  @session_id = result[:sessionId]
  @url        = URI.parse(result[:serverUrl])
  @server     = create_server(@url)

  return response
end

#login_with_oauthObject

Log in to the server with OAuth, remembering the session ID returned to us by Salesforce.



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
# File 'lib/rforce/binding.rb', line 100

def 
  consumer = OAuth::Consumer.new \
    @oauth[:consumer_key],
    @oauth[:consumer_secret]

  access = OAuth::AccessToken.new \
    consumer, @oauth[:access_token],
    @oauth[:access_secret]

   = @oauth[:login_url]

  result = access.post \
    ,
    '',
    {'content-type' => 'application/x-www-form-urlencoded'}

  case result
  when Net::HTTPSuccess
    doc         = REXML::Document.new result.body
    @session_id = doc.elements['*/sessionId'].text
    @url        = URI.parse(doc.elements['*/serverUrl'].text)
    @server     = access

    class << @server
      alias_method :post2, :post
    end

    return {:sessionId => @session_id, :serverUrl => @url.to_s}
  when Net::HTTPUnauthorized
    raise 'Invalid OAuth tokens'
  else
    raise "Unexpected error: #{response.inspect}"
  end
end

#show_debugObject



65
66
67
# File 'lib/rforce/binding.rb', line 65

def show_debug
  ENV['SHOWSOAP'] == 'true'
end