alancse-aws-s3 0.4.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,58 @@
1
+ module AWS
2
+ module S3
3
+ # Objects on S3 can be distributed via the BitTorrent file sharing protocol.
4
+ #
5
+ # You can get a torrent file for an object by calling <tt>torrent_for</tt>:
6
+ #
7
+ # S3Object.torrent_for 'kiss.jpg', 'marcel'
8
+ #
9
+ # Or just call the <tt>torrent</tt> method if you already have the object:
10
+ #
11
+ # song = S3Object.find 'kiss.jpg', 'marcel'
12
+ # song.torrent
13
+ #
14
+ # Calling <tt>grant_torrent_access_to</tt> on a object will allow anyone to anonymously
15
+ # fetch the torrent file for that object:
16
+ #
17
+ # S3Object.grant_torrent_access_to 'kiss.jpg', 'marcel'
18
+ #
19
+ # Anonymous requests to
20
+ #
21
+ # http://s3.amazonaws.com/marcel/kiss.jpg?torrent
22
+ #
23
+ # will serve up the torrent file for that object.
24
+ module BitTorrent
25
+ def self.included(klass) #:nodoc:
26
+ klass.extend ClassMethods
27
+ end
28
+
29
+ # Adds methods to S3Object for accessing the torrent of a given object.
30
+ module ClassMethods
31
+ # Returns the torrent file for the object with the given <tt>key</tt>.
32
+ def torrent_for(key, bucket = nil)
33
+ get(path!(bucket, key) << '?torrent').body
34
+ end
35
+ alias_method :torrent, :torrent_for
36
+
37
+ # Grants access to the object with the given <tt>key</tt> to be accessible as a torrent.
38
+ def grant_torrent_access_to(key, bucket = nil)
39
+ policy = acl(key, bucket)
40
+ return true if policy.grants.include?(:public_read)
41
+ policy.grants << ACL::Grant.grant(:public_read)
42
+ acl(key, bucket, policy)
43
+ end
44
+ alias_method :grant_torrent_access, :grant_torrent_access_to
45
+ end
46
+
47
+ # Returns the torrent file for the object.
48
+ def torrent
49
+ self.class.torrent_for(key, bucket.name)
50
+ end
51
+
52
+ # Grants torrent access publicly to anyone who requests it on this object.
53
+ def grant_torrent_access
54
+ self.class.grant_torrent_access_to(key, bucket.name)
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,347 @@
1
+ module AWS
2
+ module S3
3
+ # Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.
4
+ #
5
+ # # Pick a unique name, or else you'll get an error
6
+ # # if the name is already taken.
7
+ # Bucket.create('jukebox')
8
+ #
9
+ # Bucket names must be unique across the entire S3 system, sort of like domain names across the internet. If you try
10
+ # to create a bucket with a name that is already taken, you will get an error.
11
+ #
12
+ # Assuming the name you chose isn't already taken, your new bucket will now appear in the bucket list:
13
+ #
14
+ # Service.buckets
15
+ # # => [#<AWS::S3::Bucket @attributes={"name"=>"jukebox"}>]
16
+ #
17
+ # Once you have succesfully created a bucket you can you can fetch it by name using Bucket.find.
18
+ #
19
+ # music_bucket = Bucket.find('jukebox')
20
+ #
21
+ # The bucket that is returned will contain a listing of all the objects in the bucket.
22
+ #
23
+ # music_bucket.objects.size
24
+ # # => 0
25
+ #
26
+ # If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.
27
+ #
28
+ # Bucket.objects('jukebox').size
29
+ # # => 0
30
+ #
31
+ # By default all objects will be returned, though there are several options you can use to limit what is returned, such as
32
+ # specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can
33
+ # be found in the documentation for Bucket.find.
34
+ #
35
+ # To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.
36
+ #
37
+ # file = 'black-flowers.mp3'
38
+ # S3Object.store(file, open(file), 'jukebox')
39
+ #
40
+ # You'll see your file has been added to it:
41
+ #
42
+ # music_bucket.objects
43
+ # # => [#<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>]
44
+ #
45
+ # You can treat your bucket like a hash and access objects by name:
46
+ #
47
+ # jukebox['black-flowers.mp3']
48
+ # # => #<AWS::S3::S3Object '/jukebox/black-flowers.mp3'>
49
+ #
50
+ # In the event that you want to delete a bucket, you can use Bucket.delete.
51
+ #
52
+ # Bucket.delete('jukebox')
53
+ #
54
+ # Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket
55
+ # that contains objects will raise a BucketNotEmpty exception.
56
+ #
57
+ # Passing the :force => true option to delete will take care of deleting all the bucket's objects for you.
58
+ #
59
+ # Bucket.delete('photos', :force => true)
60
+ # # => true
61
+ class Bucket < Base
62
+ class << self
63
+ # Creates a bucket named <tt>name</tt>.
64
+ #
65
+ # Bucket.create('jukebox')
66
+ #
67
+ # Your bucket name must be unique across all of S3. If the name
68
+ # you request has already been taken, you will get a 409 Conflict response, and a BucketAlreadyExists exception
69
+ # will be raised.
70
+ #
71
+ # By default new buckets have their access level set to private. You can override this using the <tt>:access</tt> option.
72
+ #
73
+ # Bucket.create('internet_drop_box', :access => :public_read_write)
74
+ #
75
+ # By default new buckets will be created in US. You can override this using the <tt>:location</tt> option.
76
+ #
77
+ # Bucket.create('internet_drop_box', :location => :eu)
78
+ #
79
+ # The full list of access levels that you can set on Bucket and S3Object creation are listed in the README[link:files/README.html]
80
+ # in the section called 'Setting access levels'.
81
+ def create(name, options = {})
82
+ validate_name!(name)
83
+ self.current_host = name
84
+
85
+ put("/", options, BucketConfiguration.new(options[:location]).to_s).success?
86
+ end
87
+
88
+ class BucketConfiguration < XmlGenerator
89
+ attr_reader :location
90
+
91
+ def initialize(location)
92
+ @location = location
93
+ super()
94
+ end
95
+
96
+ def build
97
+ return nil unless location == :eu
98
+
99
+ xml.tag!('CreateBucketConfiguration') do
100
+ xml.LocationConstraint 'EU'
101
+ end
102
+ end
103
+
104
+ end
105
+
106
+
107
+ # Fetches the bucket named <tt>name</tt>.
108
+ #
109
+ # Bucket.find('jukebox')
110
+ #
111
+ # If a default bucket is inferable from the current connection's subdomain, or if set explicitly with Base.set_current_bucket,
112
+ # it will be used if no bucket is specified.
113
+ #
114
+ # MusicBucket.current_bucket
115
+ # => 'jukebox'
116
+ # MusicBucket.find.name
117
+ # => 'jukebox'
118
+ #
119
+ # By default all objects contained in the bucket will be returned (sans their data) along with the bucket.
120
+ # You can access your objects using the Bucket#objects method.
121
+ #
122
+ # Bucket.find('jukebox').objects
123
+ #
124
+ # There are several options which allow you to limit which objects are retrieved. The list of object filtering options
125
+ # are listed in the documentation for Bucket.objects.
126
+ def find(name = nil, options = {})
127
+ new(get(path(name, options)).bucket)
128
+ end
129
+
130
+ # Return just the objects in the bucket named <tt>name</tt>.
131
+ #
132
+ # By default all objects of the named bucket will be returned. There are options, though, for filtering
133
+ # which objects are returned.
134
+ #
135
+ # === Object filtering options
136
+ #
137
+ # * <tt>:max_keys</tt> - The maximum number of keys you'd like to see in the response body.
138
+ # The server may return fewer than this many keys, but will not return more.
139
+ #
140
+ # Bucket.objects('jukebox').size
141
+ # # => 3
142
+ # Bucket.objects('jukebox', :max_keys => 1).size
143
+ # # => 1
144
+ #
145
+ # * <tt>:prefix</tt> - Restricts the response to only contain results that begin with the specified prefix.
146
+ #
147
+ # Bucket.objects('jukebox')
148
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/jazz/dolphy.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]
149
+ # Bucket.objects('jukebox', :prefix => 'classical')
150
+ # # => [<AWS::S3::S3Object '/classical/malher.mp3'>]
151
+ #
152
+ # * <tt>:marker</tt> - Marker specifies where in the result set to resume listing. It restricts the response
153
+ # to only contain results that occur alphabetically _after_ the value of marker. To retrieve the next set of results,
154
+ # use the last key from the current page of results as the marker in your next request.
155
+ #
156
+ # # Skip 'mahler'
157
+ # Bucket.objects('jukebox', :marker => 'mb')
158
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
159
+ #
160
+ # === Examples
161
+ #
162
+ # # Return no more than 2 objects whose key's are listed alphabetically after the letter 'm'.
163
+ # Bucket.objects('jukebox', :marker => 'm', :max_keys => 2)
164
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>, <AWS::S3::S3Object '/classical/malher.mp3'>]
165
+ #
166
+ # # Return no more than 2 objects whose key's are listed alphabetically after the letter 'm' and have the 'jazz' prefix.
167
+ # Bucket.objects('jukebox', :marker => 'm', :max_keys => 2, :prefix => 'jazz')
168
+ # # => [<AWS::S3::S3Object '/jazz/miles.mp3'>]
169
+ def objects(name = nil, options = {})
170
+ find(name, options).object_cache
171
+ end
172
+
173
+ # Deletes the bucket named <tt>name</tt>.
174
+ #
175
+ # All objects in the bucket must be deleted before the bucket can be deleted. If the bucket is not empty,
176
+ # BucketNotEmpty will be raised.
177
+ #
178
+ # You can side step this issue by passing the :force => true option to delete which will take care of
179
+ # emptying the bucket before deleting it.
180
+ #
181
+ # Bucket.delete('photos', :force => true)
182
+ #
183
+ # Only the owner of a bucket can delete a bucket, regardless of the bucket's access control policy.
184
+ def delete(name = nil, options = {})
185
+ name = path(name)
186
+ find(name).delete_all if options[:force]
187
+ # A bit confusing. Calling super actually makes makes an HTTP DELETE request. The delete method is
188
+ # defined in the Base class. It happens to have the same name.
189
+ super(name).success?
190
+ end
191
+
192
+ # List all your buckets. This is a convenient wrapper around AWS::S3::Service.buckets.
193
+ def list(reload = false)
194
+ self.current_host = nil
195
+ Service.buckets(reload)
196
+ end
197
+
198
+ private
199
+ def validate_name!(name)
200
+ raise InvalidBucketName.new(name) unless name =~ /^[-\w.]{3,255}$/
201
+ end
202
+
203
+ def path(name, options = {})
204
+ if name.is_a?(Hash)
205
+ options = name
206
+ name = nil
207
+ end
208
+ self.current_host = bucket_name(name)
209
+ "/#{RequestOptions.process(options).to_query_string}"
210
+ end
211
+ end
212
+
213
+ attr_reader :object_cache #:nodoc:
214
+
215
+ include Enumerable
216
+
217
+ def initialize(attributes = {}) #:nodoc:
218
+ super
219
+ @object_cache = []
220
+ build_contents!
221
+ end
222
+
223
+ # Fetches the object named <tt>object_key</tt>, or nil if the bucket does not contain an object with the
224
+ # specified key.
225
+ #
226
+ # bucket.objects
227
+ # => [#<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>,
228
+ # #<AWS::S3::S3Object '/marcel_molina/tongue_overload.jpg'>]
229
+ # bucket['beluga_baby.jpg']
230
+ # => #<AWS::S3::S3Object '/marcel_molina/beluga_baby.jpg'>
231
+ def [](object_key)
232
+ detect {|file| file.key == object_key.to_s}
233
+ end
234
+
235
+ # Initializes a new S3Object belonging to the current bucket.
236
+ #
237
+ # object = bucket.new_object
238
+ # object.value = data
239
+ # object.key = 'classical/mahler.mp3'
240
+ # object.store
241
+ # bucket.objects.include?(object)
242
+ # => true
243
+ def new_object(attributes = {})
244
+ object = S3Object.new(attributes)
245
+ register(object)
246
+ object
247
+ end
248
+
249
+ # List S3Object's of the bucket.
250
+ #
251
+ # Once fetched the objects will be cached. You can reload the objects by passing <tt>:reload</tt>.
252
+ #
253
+ # bucket.objects(:reload)
254
+ #
255
+ # You can also filter the objects using the same options listed in Bucket.objects.
256
+ #
257
+ # bucket.objects(:prefix => 'jazz')
258
+ #
259
+ # Using these filtering options will implictly reload the objects.
260
+ #
261
+ # To reclaim all the objects for the bucket you can pass in :reload again.
262
+ def objects(options = {})
263
+ if options.is_a?(Hash)
264
+ reload = !options.empty?
265
+ else
266
+ reload = options
267
+ options = {}
268
+ end
269
+
270
+ reload!(options) if reload || object_cache.empty?
271
+ object_cache
272
+ end
273
+
274
+ # Iterates over the objects in the bucket.
275
+ #
276
+ # bucket.each do |object|
277
+ # # Do something with the object ...
278
+ # end
279
+ def each(&block)
280
+ # Dup the collection since we might be destructively modifying the object_cache during the iteration.
281
+ objects.dup.each(&block)
282
+ end
283
+
284
+ # Returns true if there are no objects in the bucket.
285
+ def empty?
286
+ objects.empty?
287
+ end
288
+
289
+ # Returns the number of objects in the bucket.
290
+ def size
291
+ objects.size
292
+ end
293
+
294
+ # Deletes the bucket. See its class method counter part Bucket.delete for caveats about bucket deletion and how to ensure
295
+ # a bucket is deleted no matter what.
296
+ def delete(options = {})
297
+ self.class.delete(name, options)
298
+ end
299
+
300
+ # Delete all files in the bucket. Use with caution. Can not be undone.
301
+ def delete_all
302
+ each do |object|
303
+ object.delete
304
+ end
305
+ self
306
+ end
307
+ alias_method :clear, :delete_all
308
+
309
+ # Buckets observe their objects and have this method called when one of their objects
310
+ # is either stored or deleted.
311
+ def update(action, object) #:nodoc:
312
+ case action
313
+ when :stored then add object unless objects.include?(object)
314
+ when :deleted then object_cache.delete(object)
315
+ end
316
+ end
317
+
318
+ private
319
+ def build_contents!
320
+ return unless has_contents?
321
+ attributes.delete('contents').each do |content|
322
+ add new_object(content)
323
+ end
324
+ end
325
+
326
+ def has_contents?
327
+ attributes.has_key?('contents')
328
+ end
329
+
330
+ def add(object)
331
+ register(object)
332
+ object_cache << object
333
+ end
334
+
335
+ def register(object)
336
+ object.bucket = self
337
+ end
338
+
339
+ def reload!(options = {})
340
+ object_cache.clear
341
+ self.class.objects(name, options).each do |object|
342
+ add object
343
+ end
344
+ end
345
+ end
346
+ end
347
+ end
@@ -0,0 +1,325 @@
1
+ module AWS
2
+ module S3
3
+ class Connection #:nodoc:
4
+ class << self
5
+ def connect(options = {})
6
+ new(options)
7
+ end
8
+
9
+ def prepare_path(path)
10
+ path = path.remove_extended unless path.utf8?
11
+ URI.escape(path)
12
+ end
13
+ end
14
+
15
+ attr_reader :access_key_id, :secret_access_key, :http, :options
16
+
17
+ # Creates a new connection. Connections make the actual requests to S3, though these requests are usually
18
+ # called from subclasses of Base.
19
+ #
20
+ # For details on establishing connections, check the Connection::Management::ClassMethods.
21
+ def initialize(options = {})
22
+ @options = Options.new(options)
23
+ connect
24
+ end
25
+
26
+ def request(verb, path, headers = {}, body = nil, attempts = 0, current_host = nil, &block)
27
+ body.rewind if body.respond_to?(:rewind) unless attempts.zero?
28
+
29
+ requester = Proc.new do
30
+ path = self.class.prepare_path(path)
31
+ request = request_method(verb).new(path, headers)
32
+ ensure_content_type!(request)
33
+ add_user_agent!(request)
34
+ set_host!(request, current_host)
35
+ authenticate!(request, current_host)
36
+ if body
37
+ if body.respond_to?(:read)
38
+ request.body_stream = body
39
+ request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size
40
+ else
41
+ request.body = body
42
+ end
43
+ end
44
+
45
+ http.request(request, &block)
46
+ end
47
+
48
+ if persistent?
49
+ http.start unless http.started?
50
+ requester.call
51
+ else
52
+ http.start(&requester)
53
+ end
54
+ rescue Errno::EPIPE, Timeout::Error, Errno::EPIPE, Errno::EINVAL
55
+ @http = create_connection
56
+ attempts == 3 ? raise : (attempts += 1; retry)
57
+ end
58
+
59
+ def url_for(path, current_host, options = {})
60
+ authenticate = options.delete(:authenticated)
61
+ # Default to true unless explicitly false
62
+ authenticate = true if authenticate.nil?
63
+ path = self.class.prepare_path(path)
64
+ request = request_method(:get).new(path, {})
65
+ query_string = query_string_authentication(request, current_host, options)
66
+ returning "#{protocol(options)}#{get_host(current_host)}#{port_string}#{path}" do |url|
67
+ url << "?#{query_string}" if authenticate
68
+ end
69
+ end
70
+
71
+ def subdomain
72
+ subdomain = http.address.gsub("#{DEFAULT_HOST}", "").gsub(/.$/,'')
73
+ subdomain.empty? ? nil : subdomain
74
+ end
75
+
76
+ def persistent?
77
+ options[:persistent]
78
+ end
79
+
80
+ def protocol(options = {})
81
+ (options[:use_ssl] || http.use_ssl?) ? 'https://' : 'http://'
82
+ end
83
+
84
+ private
85
+ def extract_keys!
86
+ missing_keys = []
87
+ extract_key = Proc.new {|key| options[key] || (missing_keys.push(key); nil)}
88
+ @access_key_id = extract_key[:access_key_id]
89
+ @secret_access_key = extract_key[:secret_access_key]
90
+ raise MissingAccessKey.new(missing_keys) unless missing_keys.empty?
91
+ end
92
+
93
+ def create_connection
94
+ http = http_class.new(options[:server], options[:port])
95
+ http.use_ssl = !options[:use_ssl].nil? || options[:port] == 443
96
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
97
+ http
98
+ end
99
+
100
+ def http_class
101
+ if options.connecting_through_proxy?
102
+ Net::HTTP::Proxy(*options.proxy_settings)
103
+ else
104
+ Net::HTTP
105
+ end
106
+ end
107
+
108
+ def connect
109
+ extract_keys!
110
+ @http = create_connection
111
+ end
112
+
113
+ def port_string
114
+ default_port = options[:use_ssl] ? 443 : 80
115
+ http.port == default_port ? '' : ":#{http.port}"
116
+ end
117
+
118
+ def ensure_content_type!(request)
119
+ request['Content-Type'] ||= 'binary/octet-stream'
120
+ end
121
+
122
+ # Just do Header authentication for now
123
+ def authenticate!(request, current_host)
124
+ request['Authorization'] = Authentication::Header.new(request, access_key_id, secret_access_key, current_host)
125
+ end
126
+
127
+ def add_user_agent!(request)
128
+ request['User-Agent'] ||= "AWS::S3/#{Version}"
129
+ end
130
+
131
+ def set_host!(request, host)
132
+ request['Host'] = get_host(host)
133
+ end
134
+
135
+ def get_host(host)
136
+ (host && http.address.match(host)) ? http.address : host.nil? ? http.address : host.match(/amazonaws.com/) ? host : "#{host}.#{http.address}"
137
+ end
138
+
139
+ def query_string_authentication(request, current_host, options = {})
140
+ Authentication::QueryString.new(request, access_key_id, secret_access_key, current_host, options)
141
+ end
142
+
143
+ def request_method(verb)
144
+ Net::HTTP.const_get(verb.to_s.capitalize)
145
+ end
146
+
147
+ def method_missing(method, *args, &block)
148
+ options[method] || super
149
+ end
150
+
151
+ module Management #:nodoc:
152
+ def self.included(base)
153
+ base.cattr_accessor :connections
154
+ base.connections = {}
155
+ base.extend ClassMethods
156
+ end
157
+
158
+ # Manage the creation and destruction of connections for AWS::S3::Base and its subclasses. Connections are
159
+ # created with establish_connection!.
160
+ module ClassMethods
161
+ # Creates a new connection with which to make requests to the S3 servers for the calling class.
162
+ #
163
+ # AWS::S3::Base.establish_connection!(:access_key_id => '...', :secret_access_key => '...')
164
+ #
165
+ # You can set connections for every subclass of AWS::S3::Base. Once the initial connection is made on
166
+ # Base, all subsequent connections will inherit whatever values you don't specify explictly. This allows you to
167
+ # customize details of the connection, such as what server the requests are made to, by just specifying one
168
+ # option.
169
+ #
170
+ # AWS::S3::Bucket.established_connection!(:use_ssl => true)
171
+ #
172
+ # The Bucket connection would inherit the <tt>:access_key_id</tt> and the <tt>:secret_access_key</tt> from
173
+ # Base's connection. Unlike the Base connection, all Bucket requests would be made over SSL.
174
+ #
175
+ # == Required arguments
176
+ #
177
+ # * <tt>:access_key_id</tt> - The access key id for your S3 account. Provided by Amazon.
178
+ # * <tt>:secret_access_key</tt> - The secret access key for your S3 account. Provided by Amazon.
179
+ #
180
+ # If any of these required arguments is missing, a MissingAccessKey exception will be raised.
181
+ #
182
+ # == Optional arguments
183
+ #
184
+ # * <tt>:server</tt> - The server to make requests to. You can use this to specify your bucket in the subdomain,
185
+ # or your own domain's cname if you are using virtual hosted buckets. Defaults to <tt>s3.amazonaws.com</tt>.
186
+ # * <tt>:port</tt> - The port to the requests should be made on. Defaults to 80 or 443 if the <tt>:use_ssl</tt>
187
+ # argument is set.
188
+ # * <tt>:use_ssl</tt> - Whether requests should be made over SSL. If set to true, the <tt>:port</tt> argument
189
+ # will be implicitly set to 443, unless specified otherwise. Defaults to false.
190
+ # * <tt>:persistent</tt> - Whether to use a persistent connection to the server. Having this on provides around a two fold
191
+ # performance increase but for long running processes some firewalls may find the long lived connection suspicious and close the connection.
192
+ # If you run into connection errors, try setting <tt>:persistent</tt> to false. Defaults to true.
193
+ # * <tt>:proxy</tt> - If you need to connect through a proxy, you can specify your proxy settings by specifying a <tt>:host</tt>, <tt>:port</tt>, <tt>:user</tt>, and <tt>:password</tt>
194
+ # with the <tt>:proxy</tt> option.
195
+ # The <tt>:host</tt> setting is required if specifying a <tt>:proxy</tt>.
196
+ #
197
+ # AWS::S3::Bucket.established_connection!(:proxy => {
198
+ # :host => '...', :port => 8080, :user => 'marcel', :password => 'secret'
199
+ # })
200
+ def establish_connection!(options = {})
201
+ # After you've already established the default connection, just specify
202
+ # the difference for subsequent connections
203
+ options = default_connection.options.merge(options) if connected?
204
+ connections[connection_name] = Connection.connect(options)
205
+ end
206
+
207
+ # Returns the connection for the current class, or Base's default connection if the current class does not
208
+ # have its own connection.
209
+ #
210
+ # If not connection has been established yet, NoConnectionEstablished will be raised.
211
+ def connection
212
+ if connected?
213
+ connections[connection_name] || default_connection
214
+ else
215
+ raise NoConnectionEstablished
216
+ end
217
+ end
218
+
219
+ # Returns true if a connection has been made yet.
220
+ def connected?
221
+ !connections.empty?
222
+ end
223
+
224
+ # Removes the connection for the current class. If there is no connection for the current class, the default
225
+ # connection will be removed.
226
+ def disconnect(name = connection_name)
227
+ name = default_connection unless connections.has_key?(name)
228
+ connection = connections[name]
229
+ connection.http.finish if connection.persistent?
230
+ connections.delete(name)
231
+ end
232
+
233
+ # Clears *all* connections, from all classes, with prejudice.
234
+ def disconnect!
235
+ connections.each_key {|connection| disconnect(connection)}
236
+ end
237
+
238
+ private
239
+ def connection_name
240
+ name
241
+ end
242
+
243
+ def default_connection_name
244
+ 'AWS::S3::Base'
245
+ end
246
+
247
+ def default_connection
248
+ connections[default_connection_name]
249
+ end
250
+ end
251
+ end
252
+
253
+ class Options < Hash #:nodoc:
254
+ class << self
255
+ def valid_options
256
+ [:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy]
257
+ end
258
+ end
259
+
260
+ attr_reader :options
261
+ def initialize(options = {})
262
+ super()
263
+ @options = options
264
+ validate!
265
+ extract_proxy_settings!
266
+ extract_persistent!
267
+ extract_server!
268
+ extract_port!
269
+ extract_remainder!
270
+ end
271
+
272
+ def connecting_through_proxy?
273
+ !self[:proxy].nil?
274
+ end
275
+
276
+ def proxy_settings
277
+ proxy_setting_keys.map do |proxy_key|
278
+ self[:proxy][proxy_key]
279
+ end
280
+ end
281
+
282
+ private
283
+ def proxy_setting_keys
284
+ [:host, :port, :user, :password]
285
+ end
286
+
287
+ def missing_proxy_settings?
288
+ !self[:proxy].keys.include?(:host)
289
+ end
290
+
291
+ def extract_persistent!
292
+ self[:persistent] = options.has_key?(:persitent) ? options[:persitent] : true
293
+ end
294
+
295
+ def extract_proxy_settings!
296
+ self[:proxy] = options.delete(:proxy) if options.include?(:proxy)
297
+ validate_proxy_settings!
298
+ end
299
+
300
+ def extract_server!
301
+ self[:server] = options.delete(:server) || DEFAULT_HOST
302
+ end
303
+
304
+ def extract_port!
305
+ self[:port] = options.delete(:port) || (options[:use_ssl] ? 443 : 80)
306
+ end
307
+
308
+ def extract_remainder!
309
+ update(options)
310
+ end
311
+
312
+ def validate!
313
+ invalid_options = options.keys.select {|key| !self.class.valid_options.include?(key)}
314
+ raise InvalidConnectionOption.new(invalid_options) unless invalid_options.empty?
315
+ end
316
+
317
+ def validate_proxy_settings!
318
+ if connecting_through_proxy? && missing_proxy_settings?
319
+ raise ArgumentError, "Missing proxy settings. Must specify at least :host."
320
+ end
321
+ end
322
+ end
323
+ end
324
+ end
325
+ end