rforce 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,9 @@
1
+ == 0.1.0 2005-09-02
2
+
3
+ * 1 major enhancement:
4
+ * Initial release
5
+
6
+ == 0.2.0 2008-07-03
7
+
8
+ * 1 major enhancement:
9
+ * Incorporated fixes from ActiveSalesforce project
data/Manifest.txt ADDED
@@ -0,0 +1,9 @@
1
+ History.txt
2
+ Manifest.txt
3
+ README.txt
4
+ Rakefile
5
+ lib/rforce.rb
6
+ spec/rforce_spec.rb
7
+ spec/spec.opts
8
+ spec/spec_helper.rb
9
+ tasks/rspec.rake
data/README.txt ADDED
@@ -0,0 +1,61 @@
1
+ = rforce
2
+
3
+ * http://rforce.rubyforge.org
4
+
5
+ == DESCRIPTION:
6
+
7
+ RForce is a simple, usable binding to the SalesForce API.
8
+
9
+ == FEATURES/PROBLEMS:
10
+
11
+ Rather than enforcing adherence to the sforce.com schema, RForce assumes you are familiar with the API. Ruby method names become SOAP method names. Nested Ruby hashes become nested XML elements.
12
+
13
+ == SYNOPSIS:
14
+
15
+ binding = RForce::Binding.new 'na1-api.salesforce.com'
16
+ binding.login 'username', 'password'
17
+ answer = binding.search(
18
+ :searchString =>
19
+ 'find {Some Account Name} in name fields returning account(id)')
20
+ account_id = answer.searchResponse.result.searchRecords.record.Id
21
+
22
+ opportunity = {
23
+ :accountId => account_id,
24
+ :amount => "10.00",
25
+ :name => "New sale",
26
+ :closeDate => "2005-09-01",
27
+ :stageName => "Closed Won"
28
+ }
29
+
30
+ binding.create 'sObject {"xsi:type" => "Opportunity"}' => opportunity
31
+
32
+ == REQUIREMENTS:
33
+
34
+ * A SalesForce Enterprise or Developer account
35
+
36
+ == INSTALL:
37
+
38
+ * sudo gem install rforce
39
+
40
+ == LICENSE:
41
+
42
+ Copyright (c) 2005-2008 Ian Dees
43
+
44
+ Permission is hereby granted, free of charge, to any person obtaining
45
+ a copy of this software and associated documentation files (the
46
+ 'Software'), to deal in the Software without restriction, including
47
+ without limitation the rights to use, copy, modify, merge, publish,
48
+ distribute, sublicense, and/or sell copies of the Software, and to
49
+ permit persons to whom the Software is furnished to do so, subject to
50
+ the following conditions:
51
+
52
+ The above copyright notice and this permission notice shall be
53
+ included in all copies or substantial portions of the Software.
54
+
55
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
56
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
58
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
59
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
60
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
61
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ # -*- ruby -*-
2
+
3
+ require 'rubygems'
4
+ require 'hoe'
5
+ require './lib/rforce.rb'
6
+
7
+ Hoe.new('rforce', RForce::VERSION) do |p|
8
+ # p.rubyforge_name = 'rforcex' # if different than lowercase project name
9
+ p.developer('Ian Dees', 'undees@gmail.com')
10
+ p.remote_rdoc_dir = ''
11
+ end
12
+
13
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
14
+
15
+ # vim: syntax=Ruby
data/lib/rforce.rb ADDED
@@ -0,0 +1,362 @@
1
+ =begin
2
+ RForce v0.2
3
+ Copyright (c) 2005-2008 Ian Dees
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+ =end
23
+
24
+ # RForce is a simple Ruby binding to the SalesForce CRM system.
25
+ # Rather than enforcing adherence to the sforce.com schema,
26
+ # RForce assumes you are familiar with the API. Ruby method names
27
+ # become SOAP method names. Nested Ruby hashes become nested
28
+ # XML elements.
29
+ #
30
+ # Example:
31
+ #
32
+ # binding = RForce::Binding.new 'na1-api.salesforce.com'
33
+ # binding.login 'username', 'password'
34
+ # answer = binding.search(
35
+ # :searchString =>
36
+ # 'find {Some Account Name} in name fields returning account(id)')
37
+ # account_id = answer.searchResponse.result.searchRecords.record.Id
38
+ #
39
+ # opportunity = {
40
+ # :accountId => account_id,
41
+ # :amount => "10.00",
42
+ # :name => "New sale",
43
+ # :closeDate => "2005-09-01",
44
+ # :stageName => "Closed Won"
45
+ # }
46
+ #
47
+ # binding.create 'sObject {"xsi:type" => "Opportunity"}' => opportunity
48
+ #
49
+
50
+
51
+ require 'net/https'
52
+ require 'uri'
53
+ require 'zlib'
54
+ require 'stringio'
55
+ require 'rexml/document'
56
+ require 'rexml/xpath'
57
+ require 'rubygems'
58
+ gem 'builder', ">= 2.0.0"
59
+
60
+
61
+ module RForce
62
+ VERSION = '0.2.0'
63
+
64
+ #Allows indexing hashes like method calls: hash.key
65
+ #to supplement the traditional way of indexing: hash[key]
66
+ module FlashHash
67
+ def method_missing(method, *args)
68
+ self[method]
69
+ end
70
+ end
71
+
72
+ #Turns an XML response from the server into a Ruby
73
+ #object whose methods correspond to nested XML elements.
74
+ class SoapResponse
75
+ include FlashHash
76
+
77
+ #Parses an XML string into structured data.
78
+ def initialize(content)
79
+ document = REXML::Document.new content
80
+ node = REXML::XPath.first document, '//soapenv:Body'
81
+ @parsed = SoapResponse.parse node
82
+ end
83
+
84
+ #Allows this object to act like a hash (and therefore
85
+ #as a FlashHash via the include above).
86
+ def [](symbol)
87
+ @parsed[symbol]
88
+ end
89
+
90
+ #Digests an XML DOM node into nested Ruby types.
91
+ def SoapResponse.parse(node)
92
+ #Convert text nodes into simple strings.
93
+ return node.text unless node.has_elements?
94
+
95
+ #Convert nodes with children into FlashHashes.
96
+ elements = {}
97
+ class << elements
98
+ include FlashHash
99
+ end
100
+
101
+ #Add all the element's children to the hash.
102
+ node.each_element do |e|
103
+ name = e.name.to_sym
104
+
105
+ case elements[name]
106
+ #The most common case: unique child element tags.
107
+ when NilClass: elements[name] = parse(e)
108
+
109
+ #Non-unique child elements become arrays:
110
+
111
+ #We've already created the array: just
112
+ #add the element.
113
+ when Array: elements[name] << parse(e)
114
+
115
+ #We haven't created the array yet: do so,
116
+ #then put the existing element in, followed
117
+ #by the new one.
118
+ else
119
+ elements[name] = [elements[name]]
120
+ elements[name] << parse(e)
121
+ end
122
+ end
123
+
124
+ return elements
125
+ end
126
+ end
127
+
128
+
129
+ #Implements the connection to the SalesForce server.
130
+ class Binding
131
+ DEFAULT_BATCH_SIZE = 10
132
+ attr_accessor :batch_size, :url, :assignment_rule_id, :use_default_rule, :update_mru, :client_id, :trigger_user_email,
133
+ :trigger_other_email, :trigger_auto_response_email
134
+
135
+ #Fill in the guts of this typical SOAP envelope
136
+ #with the session ID and the body of the SOAP request.
137
+ Envelope = <<-HERE
138
+ <?xml version="1.0" encoding="utf-8" ?>
139
+ <soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
140
+ xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
141
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
142
+ xmlns:partner="urn:partner.soap.sforce.com">
143
+ xmlns:spartner="urn:sobject.partner.soap.sforce.com">
144
+ <soap:Header>
145
+ <partner:SessionHeader soap:mustUnderstand='1'>
146
+ <partner:sessionId>%s</partner:sessionId>
147
+ </partner:SessionHeader>
148
+ <partner:QueryOptions soap:mustUnderstand='1'>
149
+ <partner:batchSize>%d</partner:batchSize>
150
+ </partner:QueryOptions>
151
+ %s
152
+ </soap:Header>
153
+ <soap:Body>
154
+ %s
155
+ </soap:Body>
156
+ </soap:Envelope>
157
+ HERE
158
+
159
+ AssignmentRuleHeaderUsingRuleId = '<partner:AssignmentRuleHeader soap:mustUnderstand="1"><partner:assignmentRuleId>%s</partner:assignmentRuleId></partner:AssignmentRuleHeader>'
160
+ AssignmentRuleHeaderUsingDefaultRule = '<partner:AssignmentRuleHeader soap:mustUnderstand="1"><partner:useDefaultRule>true</partner:useDefaultRule></partner:AssignmentRuleHeader>'
161
+ MruHeader = '<partner:MruHeader soap:mustUnderstand="1"><partner:updateMru>true</partner:updateMru></partner:MruHeader>'
162
+ ClientIdHeader = '<partner:CallOptions soap:mustUnderstand="1"><partner:client>%s</partner:client></partner:CallOptions>'
163
+
164
+ #Connect to the server securely.
165
+ def initialize(url, sid)
166
+ init_server(url)
167
+
168
+ @session_id = sid
169
+ @batch_size = DEFAULT_BATCH_SIZE
170
+ end
171
+
172
+
173
+ def show_debug
174
+ ENV['SHOWSOAP'] == 'true'
175
+ end
176
+
177
+
178
+ def init_server(url)
179
+ @url = URI.parse(url)
180
+ @server = Net::HTTP.new(@url.host, @url.port)
181
+ @server.use_ssl = @url.scheme == 'https'
182
+ @server.verify_mode = OpenSSL::SSL::VERIFY_NONE
183
+
184
+ # run ruby with -d or env variable SHOWSOAP=true to see SOAP wiredumps.
185
+ @server.set_debug_output $stderr if show_debug
186
+ end
187
+
188
+
189
+ #Log in to the server and remember the session ID
190
+ #returned to us by SalesForce.
191
+ def login(user, password)
192
+ @user = user
193
+ @password = password
194
+
195
+ response = call_remote(:login, [:username, user, :password, password])
196
+
197
+ raise "Incorrect user name / password [#{response.fault}]" unless response.loginResponse
198
+
199
+ result = response[:loginResponse][:result]
200
+ @session_id = result[:sessionId]
201
+
202
+ init_server(result[:serverUrl])
203
+
204
+ response
205
+ end
206
+
207
+
208
+ #Call a method on the remote server. Arguments can be
209
+ #a hash or (if order is important) an array of alternating
210
+ #keys and values.
211
+ def call_remote(method, args)
212
+ #Create XML text from the arguments.
213
+ expanded = ''
214
+ @builder = Builder::XmlMarkup.new(:target => expanded)
215
+ expand({method => args}, 'urn:partner.soap.sforce.com')
216
+
217
+ extra_headers = ""
218
+ extra_headers << (AssignmentRuleHeaderUsingRuleId % assignment_rule_id) if assignment_rule_id
219
+ extra_headers << AssignmentRuleHeaderUsingDefaultRule if use_default_rule
220
+ extra_headers << MruHeader if update_mru
221
+ extra_headers << (ClientIdHeader % client_id) if client_id
222
+
223
+ if trigger_user_email or trigger_other_email or trigger_auto_response_email
224
+ extra_headers << '<partner:EmailHeader soap:mustUnderstand="1">'
225
+
226
+ extra_headers << '<partner:triggerUserEmail>true</partner:triggerUserEmail>' if trigger_user_email
227
+ extra_headers << '<partner:triggerOtherEmail>true</partner:triggerOtherEmail>' if trigger_other_email
228
+ extra_headers << '<partner:triggerAutoResponseEmail>true</partner:triggerAutoResponseEmail>' if trigger_auto_response_email
229
+
230
+ extra_headers << '</partner:EmailHeader>'
231
+ end
232
+
233
+ #Fill in the blanks of the SOAP envelope with our
234
+ #session ID and the expanded XML of our request.
235
+ request = (Envelope % [@session_id, @batch_size, extra_headers, expanded])
236
+
237
+ # reset the batch size for the next request
238
+ @batch_size = DEFAULT_BATCH_SIZE
239
+
240
+ # gzip request
241
+ request = encode(request)
242
+
243
+ headers = {
244
+ 'Connection' => 'Keep-Alive',
245
+ 'Content-Type' => 'text/xml',
246
+ 'SOAPAction' => '""',
247
+ 'User-Agent' => 'activesalesforce rforce/1.0'
248
+ }
249
+
250
+ unless show_debug
251
+ headers['Accept-Encoding'] = 'gzip'
252
+ headers['Content-Encoding'] = 'gzip'
253
+ end
254
+
255
+ #Send the request to the server and read the response.
256
+ response = @server.post2(@url.path, request.lstrip, headers)
257
+
258
+ # decode if we have encoding
259
+ content = decode(response)
260
+
261
+ # Check to see if INVALID_SESSION_ID was raised and try to relogin in
262
+ if method != :login and @session_id and content =~ /sf:INVALID_SESSION_ID/
263
+ login(@user, @password)
264
+
265
+ # repackage and rencode request with the new session id
266
+ request = (Envelope % [@session_id, @batch_size, extra_headers, expanded])
267
+ request = encode(request)
268
+
269
+ #Send the request to the server and read the response.
270
+ response = @server.post2(@url.path, request.lstrip, headers)
271
+
272
+ content = decode(response)
273
+ end
274
+
275
+ SoapResponse.new(content)
276
+ end
277
+
278
+
279
+ # decode gzip
280
+ def decode(response)
281
+ encoding = response['Content-Encoding']
282
+
283
+ # return body if no encoding
284
+ if !encoding then return response.body end
285
+
286
+ # decode gzip
287
+ case encoding.strip
288
+ when 'gzip':
289
+ begin
290
+ gzr = Zlib::GzipReader.new(StringIO.new(response.body))
291
+ decoded = gzr.read
292
+ ensure
293
+ gzr.close
294
+ end
295
+ decoded
296
+ else
297
+ response.body
298
+ end
299
+ end
300
+
301
+
302
+ # encode gzip
303
+ def encode(request)
304
+ return request if show_debug
305
+
306
+ begin
307
+ ostream = StringIO.new
308
+ gzw = Zlib::GzipWriter.new(ostream)
309
+ gzw.write(request)
310
+ ostream.string
311
+ ensure
312
+ gzw.close
313
+ end
314
+ end
315
+
316
+
317
+ #Turns method calls on this object into remote SOAP calls.
318
+ def method_missing(method, *args)
319
+ unless args.size == 1 && [Hash, Array].include?(args[0].class)
320
+ raise 'Expected 1 Hash or Array argument'
321
+ end
322
+
323
+ call_remote method, args[0]
324
+ end
325
+
326
+
327
+ #Expand Ruby data structures into XML.
328
+ def expand(args, xmlns = nil)
329
+ #Nest arrays: [:a, 1, :b, 2] => [[:a, 1], [:b, 2]]
330
+ if (args.class == Array)
331
+ args.each_index{|i| args[i, 2] = [args[i, 2]]}
332
+ end
333
+
334
+ args.each do |key, value|
335
+ attributes = xmlns ? {:xmlns => xmlns} : {}
336
+
337
+ #If the XML tag requires attributes,
338
+ #the tag name will contain a space
339
+ #followed by a string representation
340
+ #of a hash of attributes.
341
+ #
342
+ #e.g. 'sObject {"xsi:type" => "Opportunity"}'
343
+ #becomes <sObject xsi:type="Opportunity>...</sObject>
344
+ if key.is_a? String
345
+ key, modifier = key.split(' ', 2)
346
+
347
+ attributes.merge!(eval(modifier)) if modifier
348
+ end
349
+
350
+ #Create an XML element and fill it with this
351
+ #value's sub-items.
352
+ case value
353
+ when Hash, Array
354
+ @builder.tag!(key, attributes) do expand value; end
355
+
356
+ when String
357
+ @builder.tag!(key, attributes) { @builder.text! value }
358
+ end
359
+ end
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,11 @@
1
+ require File.dirname(__FILE__) + '/spec_helper.rb'
2
+
3
+ describe FlashHash do
4
+ it 'lets you access hash keys with methods' do
5
+ h = {:foo => :bar}
6
+ class << h; include FlashHash; end
7
+
8
+ h.foo.should == :bar
9
+ h.nonexistent.should be_nil
10
+ end
11
+ end
data/spec/spec.opts ADDED
@@ -0,0 +1 @@
1
+ --colour
@@ -0,0 +1,12 @@
1
+ begin
2
+ require 'spec'
3
+ rescue LoadError
4
+ require 'rubygems'
5
+ gem 'rspec'
6
+ require 'spec'
7
+ end
8
+
9
+ $:.unshift(File.dirname(__FILE__) + '/../lib')
10
+ require 'rforce'
11
+
12
+ include RForce
data/tasks/rspec.rake ADDED
@@ -0,0 +1,21 @@
1
+ begin
2
+ require 'spec'
3
+ rescue LoadError
4
+ require 'rubygems'
5
+ require 'spec'
6
+ end
7
+ begin
8
+ require 'spec/rake/spectask'
9
+ rescue LoadError
10
+ puts <<-EOS
11
+ To use rspec for testing you must install rspec gem:
12
+ gem install rspec
13
+ EOS
14
+ exit(0)
15
+ end
16
+
17
+ desc "Run the specs under spec/models"
18
+ Spec::Rake::SpecTask.new do |t|
19
+ t.spec_opts = ['--options', "spec/spec.opts"]
20
+ t.spec_files = FileList['spec/**/*_spec.rb']
21
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rforce
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Ian Dees
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2008-07-03 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: hoe
17
+ type: :development
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: 1.7.0
24
+ version:
25
+ description: RForce is a simple, usable binding to the SalesForce API.
26
+ email:
27
+ - undees@gmail.com
28
+ executables: []
29
+
30
+ extensions: []
31
+
32
+ extra_rdoc_files:
33
+ - History.txt
34
+ - Manifest.txt
35
+ - README.txt
36
+ files:
37
+ - History.txt
38
+ - Manifest.txt
39
+ - README.txt
40
+ - Rakefile
41
+ - lib/rforce.rb
42
+ - spec/rforce_spec.rb
43
+ - spec/spec.opts
44
+ - spec/spec_helper.rb
45
+ - tasks/rspec.rake
46
+ has_rdoc: true
47
+ homepage: http://rforce.rubyforge.org
48
+ post_install_message:
49
+ rdoc_options:
50
+ - --main
51
+ - README.txt
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: "0"
59
+ version:
60
+ required_rubygems_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: "0"
65
+ version:
66
+ requirements: []
67
+
68
+ rubyforge_project: rforce
69
+ rubygems_version: 1.2.0
70
+ signing_key:
71
+ specification_version: 2
72
+ summary: RForce is a simple, usable binding to the SalesForce API.
73
+ test_files: []
74
+