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 =
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>
<partner:QueryOptions soap:mustUnderstand='1'>
  <partner:batchSize>%d</partner:batchSize>
</partner:QueryOptions>
%s
  </soap:Header>
  <soap:Body>
%s
  </soap:Body>
</soap:Envelope>
HERE
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) ⇒ Binding

Connect to the server securely. If you pass an oauth hash, it must contain the keys :consumer_key, :consumer_secret, :access_token, :access_secret, and :login_url.



53
54
55
56
57
58
59
# File 'lib/rforce/binding.rb', line 53

def initialize(url, sid = nil, oauth = nil)
  @session_id = sid
  @oauth = oauth
  @batch_size = DEFAULT_BATCH_SIZE

  init_server(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.



253
254
255
256
257
258
259
# File 'lib/rforce/binding.rb', line 253

def method_missing(method, *args)
  unless args.size == 1 && [Hash, Array].include?(args[0].class)
    raise 'Expected 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.



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

def assignment_rule_id
  @assignment_rule_id
end

#batch_sizeObject

Returns the value of attribute batch_size.



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

def batch_size
  @batch_size
end

#client_idObject

Returns the value of attribute client_id.



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

def client_id
  @client_id
end

#trigger_auto_response_emailObject

Returns the value of attribute trigger_auto_response_email.



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

def trigger_auto_response_email
  @trigger_auto_response_email
end

#trigger_other_emailObject

Returns the value of attribute trigger_other_email.



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

def trigger_other_email
  @trigger_other_email
end

#trigger_user_emailObject

Returns the value of attribute trigger_user_email.



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

def trigger_user_email
  @trigger_user_email
end

#update_mruObject

Returns the value of attribute update_mru.



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

def update_mru
  @update_mru
end

#urlObject

Returns the value of attribute url.



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

def url
  @url
end

#use_default_ruleObject

Returns the value of attribute use_default_rule.



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

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.



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

def call_remote(method, args)

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

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

  extra_headers = ""
  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, @batch_size, extra_headers, expanded])

  # 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/0.4.1 LH'
  }

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

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

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

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

    # repackage and rencode request with the new session id
    request = (Envelope % [@session_id, @batch_size, 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)
  end

  SoapResponse.new(content).parse
end

#consumerObject



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rforce/binding.rb', line 78

def consumer
  OAuth::Consumer.new(@oauth[:consumer_key], 
                      @oauth[:consumer_secret], {
      :site               => "https://login.salesforce.com",
      :signature_method   => 'HMAC-SHA1', # this is default, but just for clarity
      :scheme             => :body,
      :request_token_path => "/_nc_external/system/security/oauth/RequestTokenHandler",
      :access_token_path  => "/_nc_external/system/security/oauth/AccessTokenHandler",
      :authorize_path     => '/setup/secur/RemoteAccessAuthorizationPage.apexp',
     })
end

#decode(response) ⇒ Object

decode gzip



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/rforce/binding.rb', line 216

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



239
240
241
242
243
244
245
246
247
248
249
# File 'lib/rforce/binding.rb', line 239

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

#init_server(url) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/rforce/binding.rb', line 67

def init_server(url)
  @url = URI.parse(url)
  @server = Net::HTTP.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
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.



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/rforce/binding.rb', line 119

def (user, password)
  @user = user
  @password = password

  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]

  init_server(result[:serverUrl])

  response
end

#login_with_oauthObject

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



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/rforce/binding.rb', line 94

def 
  # post is method of Oauth::AccessToken, @server is instance of it
  access_token  = OAuth::AccessToken.new consumer, @oauth[:access_token], @oauth[:access_secret]
  result = access_token.post @oauth[:login_url]
  
  case result
  when Net::HTTPSuccess
    doc = REXML::Document.new result.body
    @session_id = doc.elements['*/sessionId'].text
    server_url  = doc.elements['*/serverUrl'].text
    init_server(server_url)

    return {:sessionId => @session_id, :serverUrl => server_url}
  when Net::HTTPUnauthorized
    raise "Invalid OAuth tokens=#{@oauth.inspect}"
  else
    raise "Unexpected error: #{result.inspect}"
  end
end

#show_debugObject



62
63
64
# File 'lib/rforce/binding.rb', line 62

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