cloudfiles 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ tmp/*
2
+ coverage/*
3
+ doc/*
4
+ pkg/*
5
+ *.gem
data/COPYING ADDED
@@ -0,0 +1,12 @@
1
+ Unless otherwise noted, all files are released under the MIT license, exceptions contain licensing information in them.
2
+
3
+ Copyright (C) 2008 Rackspace US, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
11
+ Except as contained in this notice, the name of Rackspace US, Inc. shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Rackspace US, Inc.
12
+
@@ -0,0 +1,16 @@
1
+ cloudfiles.gemspec
2
+ lib/cloudfiles/authentication.rb
3
+ lib/cloudfiles/connection.rb
4
+ lib/cloudfiles/container.rb
5
+ lib/cloudfiles/storage_object.rb
6
+ lib/cloudfiles.rb
7
+ Manifest
8
+ Rakefile
9
+ README.rdoc
10
+ test/cf-testunit.rb
11
+ test/cloudfiles_authentication_test.rb
12
+ test/cloudfiles_connection_test.rb
13
+ test/cloudfiles_container_test.rb
14
+ test/cloudfiles_storage_object_test.rb
15
+ test/test_helper.rb
16
+ TODO
@@ -0,0 +1,61 @@
1
+ = Rackspace Cloud Files
2
+
3
+ == Description
4
+
5
+ This is a Ruby interface into the Rackspace[http://rackspace.com/] {Cloud Files}[http://www.rackspacecloud.com/cloud_hosting_products/files] service. Cloud Files is reliable, scalable and affordable web-based storage hosting for backing up and archiving all your static content. Cloud Files is the first and only cloud service that leverages a tier one CDN provider to create such an easy and complete storage-to-delivery solution for media content.
6
+
7
+ == Installation
8
+
9
+ This source is available on Github[http://github.com/rackspace/ruby-cloudfiles/] and the gem is available on Gemcutter[http://gemcutter.org/]. To install it, do
10
+
11
+ gem sources -a http://gems.rubyforge.org/
12
+
13
+ sudo gem install cloudfiles
14
+
15
+ To use it in a Rails application, add the following information to your config/environment.rb
16
+
17
+ config.gem "cloudfiles"
18
+
19
+
20
+ == Examples
21
+
22
+ See the class definitions for documentation on specific methods and operations.
23
+
24
+ require 'rubygems'
25
+ require 'cloudfiles'
26
+
27
+ # Log into the Cloud Files system
28
+ cf = CloudFiles::Connection.new(USERNAME, API_KEY)
29
+
30
+ # Get a listing of all containers under this account
31
+ cf.containers
32
+ => ["backup", "Books", "cftest", "test", "video", "webpics"]
33
+
34
+ # Access a specific container
35
+ container = cf.container('test')
36
+
37
+ # See how many objects are under this container
38
+ container.count
39
+ => 3
40
+
41
+ # List the objects
42
+ container.objects
43
+ => ["bigfile.txt", "new.txt", "test.txt"]
44
+
45
+ # Select an object
46
+ object = container.object('test.txt')
47
+
48
+ # Get that object's data
49
+ object.data
50
+ => "This is test data"
51
+
52
+ == Authors
53
+
54
+ Initial work by Major Hayden <major.hayden@rackspace.com>
55
+
56
+ Subsequent work by H. Wade Minter <wade.minter@rackspace.com>
57
+
58
+ == License
59
+
60
+ See COPYING for license information.
61
+ Copyright (c) 2009, Rackspace US, Inc.
@@ -0,0 +1,33 @@
1
+ require './lib/cloudfiles.rb'
2
+
3
+ begin
4
+ require 'jeweler'
5
+ Jeweler::Tasks.new do |gemspec|
6
+ gemspec.name = "cloudfiles"
7
+ gemspec.summary = "A Ruby API into Rackspace Cloud Files"
8
+ gemspec.description = "A Ruby version of the Rackspace Cloud Files API."
9
+ gemspec.email = "wade.minter@rackspace.com"
10
+ gemspec.homepage = "http://www.rackspacecloud.com/cloud_hosting_products/files"
11
+ gemspec.authors = ["H. Wade Minter", "Rackspace Hosting"]
12
+ end
13
+ Jeweler::GemcutterTasks.new
14
+ rescue LoadError
15
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
16
+ end
17
+
18
+ namespace :test do
19
+ desc 'Check test coverage'
20
+ task :coverage do
21
+ rm_f "coverage"
22
+ system("rcov -x '/Library/Ruby/Gems/1.8/gems/' --sort coverage #{File.join(File.dirname(__FILE__), 'test/*_test.rb')}")
23
+ system("open #{File.join(File.dirname(__FILE__), 'coverage/index.html')}") if PLATFORM['darwin']
24
+ end
25
+
26
+ desc 'Remove coverage products'
27
+ task :clobber_coverage do
28
+ rm_r 'coverage' rescue nil
29
+ end
30
+
31
+ end
32
+
33
+
data/TODO ADDED
File without changes
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.4.0
@@ -0,0 +1,62 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec`
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{cloudfiles}
8
+ s.version = "1.4.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["H. Wade Minter", "Rackspace Hosting"]
12
+ s.date = %q{2009-10-08}
13
+ s.description = %q{A Ruby version of the Rackspace Cloud Files API.}
14
+ s.email = %q{wade.minter@rackspace.com}
15
+ s.extra_rdoc_files = [
16
+ "README.rdoc"
17
+ ]
18
+ s.files = [
19
+ ".gitignore",
20
+ "COPYING",
21
+ "Manifest",
22
+ "README.rdoc",
23
+ "Rakefile",
24
+ "TODO",
25
+ "VERSION",
26
+ "cloudfiles.gemspec",
27
+ "lib/cloudfiles.rb",
28
+ "lib/cloudfiles/authentication.rb",
29
+ "lib/cloudfiles/connection.rb",
30
+ "lib/cloudfiles/container.rb",
31
+ "lib/cloudfiles/storage_object.rb",
32
+ "test/cf-testunit.rb",
33
+ "test/cloudfiles_authentication_test.rb",
34
+ "test/cloudfiles_connection_test.rb",
35
+ "test/cloudfiles_container_test.rb",
36
+ "test/cloudfiles_storage_object_test.rb",
37
+ "test/test_helper.rb"
38
+ ]
39
+ s.homepage = %q{http://www.rackspacecloud.com/cloud_hosting_products/files}
40
+ s.rdoc_options = ["--charset=UTF-8"]
41
+ s.require_paths = ["lib"]
42
+ s.rubygems_version = %q{1.3.5}
43
+ s.summary = %q{A Ruby API into Rackspace Cloud Files}
44
+ s.test_files = [
45
+ "test/cf-testunit.rb",
46
+ "test/cloudfiles_authentication_test.rb",
47
+ "test/cloudfiles_connection_test.rb",
48
+ "test/cloudfiles_container_test.rb",
49
+ "test/cloudfiles_storage_object_test.rb",
50
+ "test/test_helper.rb"
51
+ ]
52
+
53
+ if s.respond_to? :specification_version then
54
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
55
+ s.specification_version = 3
56
+
57
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
58
+ else
59
+ end
60
+ else
61
+ end
62
+ end
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env ruby
2
+ #
3
+ # == Cloud Files API
4
+ # ==== Connects Ruby Applications to Rackspace's {Cloud Files service}[http://www.rackspacecloud.com/cloud_hosting_products/files]
5
+ # Initial work by Major Hayden <major.hayden@rackspace.com>
6
+ #
7
+ # Subsequent work by H. Wade Minter <wade.minter@rackspace.com>
8
+ #
9
+ # See COPYING for license information.
10
+ # Copyright (c) 2009, Rackspace US, Inc.
11
+ # ----
12
+ #
13
+ # === Documentation & Examples
14
+ # To begin reviewing the available methods and examples, peruse the README file, or begin by looking at documentation for the
15
+ # CloudFiles::Connection class.
16
+ #
17
+ # The CloudFiles class is the base class. Not much of note happens here.
18
+ # To create a new CloudFiles connection, use the CloudFiles::Connection.new('user_name', 'api_key') method.
19
+ module CloudFiles
20
+
21
+ VERSION = '1.4.0.0'
22
+ require 'net/http'
23
+ require 'net/https'
24
+ require 'rexml/document'
25
+ require 'uri'
26
+ require 'digest/md5'
27
+ require 'time'
28
+ require 'rubygems'
29
+ require 'mime/types'
30
+
31
+ unless "".respond_to? :each_char
32
+ require "jcode"
33
+ $KCODE = 'u'
34
+ end
35
+
36
+ $:.unshift(File.dirname(__FILE__))
37
+ require 'cloudfiles/authentication'
38
+ require 'cloudfiles/connection'
39
+ require 'cloudfiles/container'
40
+ require 'cloudfiles/storage_object'
41
+
42
+ def self.lines(str)
43
+ (str.respond_to?(:lines) ? str.lines : str).to_a.map { |x| x.chomp }
44
+ end
45
+ end
46
+
47
+
48
+
49
+ class SyntaxException < StandardError # :nodoc:
50
+ end
51
+ class ConnectionException < StandardError # :nodoc:
52
+ end
53
+ class AuthenticationException < StandardError # :nodoc:
54
+ end
55
+ class InvalidResponseException < StandardError # :nodoc:
56
+ end
57
+ class NonEmptyContainerException < StandardError # :nodoc:
58
+ end
59
+ class NoSuchObjectException < StandardError # :nodoc:
60
+ end
61
+ class NoSuchContainerException < StandardError # :nodoc:
62
+ end
63
+ class NoSuchAccountException < StandardError # :nodoc:
64
+ end
65
+ class MisMatchedChecksumException < StandardError # :nodoc:
66
+ end
67
+ class IOException < StandardError # :nodoc:
68
+ end
69
+ class CDNNotEnabledException < StandardError # :nodoc:
70
+ end
71
+ class ObjectExistsException < StandardError # :nodoc:
72
+ end
73
+ class ExpiredAuthTokenException < StandardError # :nodoc:
74
+ end
@@ -0,0 +1,42 @@
1
+ module CloudFiles
2
+ class Authentication
3
+ # See COPYING for license information.
4
+ # Copyright (c) 2009, Rackspace US, Inc.
5
+
6
+ # Performs an authentication to the Cloud Files servers. Opens a new HTTP connection to the API server,
7
+ # sends the credentials, and looks for a successful authentication. If it succeeds, it sets the cdmmgmthost,
8
+ # cdmmgmtpath, storagehost, storagepath, authtoken, and authok variables on the connection. If it fails, it raises
9
+ # an AuthenticationException.
10
+ #
11
+ # Should probably never be called directly.
12
+ def initialize(connection)
13
+ path = '/auth'
14
+ hdrhash = { "X-Auth-User" => connection.authuser, "X-Auth-Key" => connection.authkey }
15
+ begin
16
+ server = Net::HTTP.new('api.mosso.com',443)
17
+ server.use_ssl = true
18
+ server.verify_mode = OpenSSL::SSL::VERIFY_NONE
19
+ server.start
20
+ rescue
21
+ raise ConnectionException, "Unable to connect to #{server}"
22
+ end
23
+ response = server.get(path,hdrhash)
24
+ if (response.code == "204")
25
+ connection.cdnmgmthost = URI.parse(response["x-cdn-management-url"]).host
26
+ connection.cdnmgmtpath = URI.parse(response["x-cdn-management-url"]).path
27
+ connection.cdnmgmtport = URI.parse(response["x-cdn-management-url"]).port
28
+ connection.cdnmgmtscheme = URI.parse(response["x-cdn-management-url"]).scheme
29
+ connection.storagehost = URI.parse(response["x-storage-url"]).host
30
+ connection.storagepath = URI.parse(response["x-storage-url"]).path
31
+ connection.storageport = URI.parse(response["x-storage-url"]).port
32
+ connection.storagescheme = URI.parse(response["x-storage-url"]).scheme
33
+ connection.authtoken = response["x-auth-token"]
34
+ connection.authok = true
35
+ else
36
+ connection.authtoken = false
37
+ raise AuthenticationException, "Authentication failed"
38
+ end
39
+ server.finish
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,284 @@
1
+ module CloudFiles
2
+ class Connection
3
+ # See COPYING for license information.
4
+ # Copyright (c) 2009, Rackspace US, Inc.
5
+
6
+ # Authentication key provided when the CloudFiles class was instantiated
7
+ attr_reader :authkey
8
+
9
+ # Token returned after a successful authentication
10
+ attr_accessor :authtoken
11
+
12
+ # Authentication username provided when the CloudFiles class was instantiated
13
+ attr_reader :authuser
14
+
15
+ # Hostname of the CDN management server
16
+ attr_accessor :cdnmgmthost
17
+
18
+ # Path for managing containers on the CDN management server
19
+ attr_accessor :cdnmgmtpath
20
+
21
+ # Port number for the CDN server
22
+ attr_accessor :cdnmgmtport
23
+
24
+ # URI scheme for the CDN server
25
+ attr_accessor :cdnmgmtscheme
26
+
27
+ # Hostname of the storage server
28
+ attr_accessor :storagehost
29
+
30
+ # Path for managing containers/objects on the storage server
31
+ attr_accessor :storagepath
32
+
33
+ # Port for managing the storage server
34
+ attr_accessor :storageport
35
+
36
+ # URI scheme for the storage server
37
+ attr_accessor :storagescheme
38
+
39
+ # Instance variable that is set when authorization succeeds
40
+ attr_accessor :authok
41
+
42
+ # The total size in bytes under this connection
43
+ attr_reader :bytes
44
+
45
+ # The total number of containers under this connection
46
+ attr_reader :count
47
+
48
+ # Creates a new CloudFiles::Connection object. Uses CloudFiles::Authentication to perform the login for the connection.
49
+ # The authuser is the Rackspace Cloud username, the authkey is the Rackspace Cloud API key.
50
+ #
51
+ # Setting the optional retry_auth variable to false will cause an exception to be thrown if your authorization token expires.
52
+ # Otherwise, it will attempt to reauthenticate.
53
+ #
54
+ # This will likely be the base class for most operations.
55
+ #
56
+ # cf = CloudFiles::Connection.new(MY_USERNAME, MY_API_KEY)
57
+ def initialize(authuser,authkey,retry_auth = true)
58
+ @authuser = authuser
59
+ @authkey = authkey
60
+ @retry_auth = retry_auth
61
+ @authok = false
62
+ @http = {}
63
+ CloudFiles::Authentication.new(self)
64
+ end
65
+
66
+ # Returns true if the authentication was successful and returns false otherwise.
67
+ #
68
+ # cf.authok?
69
+ # => true
70
+ def authok?
71
+ @authok
72
+ end
73
+
74
+ # Returns an CloudFiles::Container object that can be manipulated easily. Throws a NoSuchContainerException if
75
+ # the container doesn't exist.
76
+ #
77
+ # container = cf.container('test')
78
+ # container.count
79
+ # => 2
80
+ def container(name)
81
+ CloudFiles::Container.new(self,name)
82
+ end
83
+ alias :get_container :container
84
+
85
+ # Sets instance variables for the bytes of storage used for this account/connection, as well as the number of containers
86
+ # stored under the account. Returns a hash with :bytes and :count keys, and also sets the instance variables.
87
+ #
88
+ # cf.get_info
89
+ # => {:count=>8, :bytes=>42438527}
90
+ # cf.bytes
91
+ # => 42438527
92
+ def get_info
93
+ response = cfreq("HEAD",@storagehost,@storagepath,@storageport,@storagescheme)
94
+ raise InvalidResponseException, "Unable to obtain account size" unless (response.code == "204")
95
+ @bytes = response["x-account-bytes-used"].to_i
96
+ @count = response["x-account-container-count"].to_i
97
+ {:bytes => @bytes, :count => @count}
98
+ end
99
+
100
+ # Gathers a list of the containers that exist for the account and returns the list of container names
101
+ # as an array. If no containers exist, an empty array is returned. Throws an InvalidResponseException
102
+ # if the request fails.
103
+ #
104
+ # If you supply the optional limit and marker parameters, the call will return the number of containers
105
+ # specified in limit, starting after the object named in marker.
106
+ #
107
+ # cf.containers
108
+ # => ["backup", "Books", "cftest", "test", "video", "webpics"]
109
+ #
110
+ # cf.containers(2,'cftest')
111
+ # => ["test", "video"]
112
+ def containers(limit=0,marker="")
113
+ paramarr = []
114
+ paramarr << ["limit=#{URI.encode(limit.to_s).gsub(/&/,'%26')}"] if limit.to_i > 0
115
+ paramarr << ["offset=#{URI.encode(marker.to_s).gsub(/&/,'%26')}"] unless marker.to_s.empty?
116
+ paramstr = (paramarr.size > 0)? paramarr.join("&") : "" ;
117
+ response = cfreq("GET",@storagehost,"#{@storagepath}?#{paramstr}",@storageport,@storagescheme)
118
+ return [] if (response.code == "204")
119
+ raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "200")
120
+ CloudFiles.lines(response.body)
121
+ end
122
+ alias :list_containers :containers
123
+
124
+ # Retrieves a list of containers on the account along with their sizes (in bytes) and counts of the objects
125
+ # held within them. If no containers exist, an empty hash is returned. Throws an InvalidResponseException
126
+ # if the request fails.
127
+ #
128
+ # If you supply the optional limit and marker parameters, the call will return the number of containers
129
+ # specified in limit, starting after the object named in marker.
130
+ #
131
+ # cf.containers_detail
132
+ # => { "container1" => { :bytes => "36543", :count => "146" },
133
+ # "container2" => { :bytes => "105943", :count => "25" } }
134
+ def containers_detail(limit=0,marker="")
135
+ paramarr = []
136
+ paramarr << ["limit=#{URI.encode(limit.to_s).gsub(/&/,'%26')}"] if limit.to_i > 0
137
+ paramarr << ["offset=#{URI.encode(marker.to_s).gsub(/&/,'%26')}"] unless marker.to_s.empty?
138
+ paramstr = (paramarr.size > 0)? paramarr.join("&") : "" ;
139
+ response = cfreq("GET",@storagehost,"#{@storagepath}?format=xml&#{paramstr}",@storageport,@storagescheme)
140
+ return {} if (response.code == "204")
141
+ raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "200")
142
+ doc = REXML::Document.new(response.body)
143
+ detailhash = {}
144
+ doc.elements.each("account/container/") { |c|
145
+ detailhash[c.elements["name"].text] = { :bytes => c.elements["bytes"].text, :count => c.elements["count"].text }
146
+ }
147
+ doc = nil
148
+ return detailhash
149
+ end
150
+ alias :list_containers_info :containers_detail
151
+
152
+ # Returns true if the requested container exists and returns false otherwise.
153
+ #
154
+ # cf.container_exists?('good_container')
155
+ # => true
156
+ #
157
+ # cf.container_exists?('bad_container')
158
+ # => false
159
+ def container_exists?(containername)
160
+ response = cfreq("HEAD",@storagehost,"#{@storagepath}/#{containername}",@storageport,@storagescheme)
161
+ return (response.code == "204")? true : false ;
162
+ end
163
+
164
+ # Creates a new container and returns the CloudFiles::Container object. Throws an InvalidResponseException if the
165
+ # request fails.
166
+ #
167
+ # Slash (/) and question mark (?) are invalid characters, and will be stripped out. The container name is limited to
168
+ # 256 characters or less.
169
+ #
170
+ # container = cf.create_container('new_container')
171
+ # container.name
172
+ # => "new_container"
173
+ #
174
+ # container = cf.create_container('bad/name')
175
+ # => SyntaxException: Container name cannot contain the characters '/' or '?'
176
+ def create_container(containername)
177
+ raise SyntaxException, "Container name cannot contain the characters '/' or '?'" if containername.match(/[\/\?]/)
178
+ raise SyntaxException, "Container name is limited to 256 characters" if containername.length > 256
179
+ response = cfreq("PUT",@storagehost,"#{@storagepath}/#{containername}",@storageport,@storagescheme)
180
+ raise InvalidResponseException, "Unable to create container #{containername}" unless (response.code == "201" || response.code == "202")
181
+ CloudFiles::Container.new(self,containername)
182
+ end
183
+
184
+ # Deletes a container from the account. Throws a NonEmptyContainerException if the container still contains
185
+ # objects. Throws a NoSuchContainerException if the container doesn't exist.
186
+ #
187
+ # cf.delete_container('new_container')
188
+ # => true
189
+ #
190
+ # cf.delete_container('video')
191
+ # => NonEmptyContainerException: Container video is not empty
192
+ #
193
+ # cf.delete_container('nonexistent')
194
+ # => NoSuchContainerException: Container nonexistent does not exist
195
+ def delete_container(containername)
196
+ response = cfreq("DELETE",@storagehost,"#{@storagepath}/#{containername}",@storageport,@storagescheme)
197
+ raise NonEmptyContainerException, "Container #{containername} is not empty" if (response.code == "409")
198
+ raise NoSuchContainerException, "Container #{containername} does not exist" unless (response.code == "204")
199
+ true
200
+ end
201
+
202
+ # Gathers a list of public (CDN-enabled) containers that exist for an account and returns the list of container names
203
+ # as an array. If no containers are public, an empty array is returned. Throws a InvalidResponseException if
204
+ # the request fails.
205
+ #
206
+ # If you pass the optional argument as true, it will only show containers that are CURRENTLY being shared on the CDN,
207
+ # as opposed to the default behavior which is to show all containers that have EVER been public.
208
+ #
209
+ # cf.public_containers
210
+ # => ["video", "webpics"]
211
+ def public_containers(enabled_only = false)
212
+ paramstr = enabled_only == true ? "enabled_only=true" : ""
213
+ response = cfreq("GET",@cdnmgmthost,"#{@cdnmgmtpath}?#{paramstr}",@cdnmgmtport,@cdnmgmtscheme)
214
+ return [] if (response.code == "204")
215
+ raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "200")
216
+ CloudFiles.lines(response.body)
217
+ end
218
+
219
+ # This method actually makes the HTTP calls out to the server
220
+ def cfreq(method,server,path,port,scheme,headers = {},data = nil,attempts = 0,&block) # :nodoc:
221
+ start = Time.now
222
+ headers['Transfer-Encoding'] = "chunked" if data.is_a?(IO)
223
+ hdrhash = headerprep(headers)
224
+ start_http(server,path,port,scheme,hdrhash)
225
+ request = Net::HTTP.const_get(method.to_s.capitalize).new(path,hdrhash)
226
+ if data
227
+ if data.respond_to?(:read)
228
+ request.body_stream = data
229
+ else
230
+ request.body = data
231
+ end
232
+ unless data.is_a?(IO)
233
+ request.content_length = data.respond_to?(:lstat) ? data.stat.size : data.size
234
+ end
235
+ else
236
+ request.content_length = 0
237
+ end
238
+ response = @http[server].request(request,&block)
239
+ raise ExpiredAuthTokenException if response.code == "401"
240
+ response
241
+ rescue Errno::EPIPE, Timeout::Error, Errno::EINVAL, EOFError
242
+ # Server closed the connection, retry
243
+ raise ConnectionException, "Unable to reconnect to #{server} after #{count} attempts" if attempts >= 5
244
+ attempts += 1
245
+ @http[server].finish
246
+ start_http(server,path,port,scheme,headers)
247
+ retry
248
+ rescue ExpiredAuthTokenException
249
+ raise ConnectionException, "Authentication token expired and you have requested not to retry" if @retry_auth == false
250
+ CloudFiles::Authentication.new(self)
251
+ retry
252
+ end
253
+
254
+ private
255
+
256
+ # Sets up standard HTTP headers
257
+ def headerprep(headers = {}) # :nodoc:
258
+ default_headers = {}
259
+ default_headers["X-Auth-Token"] = @authtoken if (authok? && @account.nil?)
260
+ default_headers["X-Storage-Token"] = @authtoken if (authok? && !@account.nil?)
261
+ default_headers["Connection"] = "Keep-Alive"
262
+ default_headers["User-Agent"] = "CloudFiles Ruby API #{VERSION}"
263
+ default_headers.merge(headers)
264
+ end
265
+
266
+ # Starts (or restarts) the HTTP connection
267
+ def start_http(server,path,port,scheme,headers) # :nodoc:
268
+ if (@http[server].nil?)
269
+ begin
270
+ @http[server] = Net::HTTP.new(server,port)
271
+ if scheme == "https"
272
+ @http[server].use_ssl = true
273
+ @http[server].verify_mode = OpenSSL::SSL::VERIFY_NONE
274
+ end
275
+ @http[server].start
276
+ rescue
277
+ raise ConnectionException, "Unable to connect to #{server}"
278
+ end
279
+ end
280
+ end
281
+
282
+ end
283
+
284
+ end