Class: CloudFiles::Container

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudfiles/container.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, name) ⇒ Container

Retrieves an existing CloudFiles::Container object tied to the current CloudFiles::Connection. If the requested container does not exist, it will raise a NoSuchContainerException.

Will likely not be called directly, instead use connection.container(‘container_name’) to retrieve the object.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cloudfiles/container.rb', line 31

def initialize(connection,name)
  @connection = connection
  @name = name
  @storagehost = self.connection.storagehost
  @storagepath = self.connection.storagepath + "/" + URI.encode(@name).gsub(/&/,'%26')
  @storageport = self.connection.storageport
  @storagescheme = self.connection.storagescheme
  @cdnmgmthost = self.connection.cdnmgmthost
  @cdnmgmtpath = self.connection.cdnmgmtpath + "/" + URI.encode(@name).gsub(/&/,'%26')
  @cdnmgmtport = self.connection.cdnmgmtport
  @cdnmgmtscheme = self.connection.cdnmgmtscheme
  populate
end

Instance Attribute Details

#bytesObject (readonly)

Size of the container (in bytes)



10
11
12
# File 'lib/cloudfiles/container.rb', line 10

def bytes
  @bytes
end

#cdn_enabledObject (readonly)

True if container is public, false if container is private



16
17
18
# File 'lib/cloudfiles/container.rb', line 16

def cdn_enabled
  @cdn_enabled
end

#cdn_ttlObject (readonly)

CDN container TTL (if container is public)



19
20
21
# File 'lib/cloudfiles/container.rb', line 19

def cdn_ttl
  @cdn_ttl
end

#cdn_urlObject (readonly)

CDN container URL (if container if public)



22
23
24
# File 'lib/cloudfiles/container.rb', line 22

def cdn_url
  @cdn_url
end

#connectionObject (readonly)

The parent CloudFiles::Connection object for this container



25
26
27
# File 'lib/cloudfiles/container.rb', line 25

def connection
  @connection
end

#countObject (readonly)

Number of objects in the container



13
14
15
# File 'lib/cloudfiles/container.rb', line 13

def count
  @count
end

#nameObject (readonly)

Name of the container which corresponds to the instantiated container class



7
8
9
# File 'lib/cloudfiles/container.rb', line 7

def name
  @name
end

Instance Method Details

#create_object(objectname, make_path = false) ⇒ Object

Creates a new CloudFiles::StorageObject in the current container.

If an object with the specified name exists in the current container, that object will be returned. Otherwise, an empty new object will be returned.

Passing in the optional make_path argument as true will create zero-byte objects to simulate a filesystem path to the object, if an objectname with path separators (“/path/to/myfile.mp3”) is supplied. These path objects can be used in the Container.objects method.



219
220
221
# File 'lib/cloudfiles/container.rb', line 219

def create_object(objectname,make_path = false)
  CloudFiles::StorageObject.new(self,objectname,false,make_path)
end

#delete_object(objectname) ⇒ Object

Removes an CloudFiles::StorageObject from a container. True is returned if the removal is successful. Throws NoSuchObjectException if the object doesn’t exist. Throws InvalidResponseException if the request fails.

container.delete_object('new.txt')
=> true

container.delete_object('nonexistent_file.txt')
=> NoSuchObjectException: Object nonexistent_file.txt does not exist


231
232
233
234
235
236
# File 'lib/cloudfiles/container.rb', line 231

def delete_object(objectname)
  response = self.connection.cfreq("DELETE",@storagehost,"#{@storagepath}/#{URI.encode(objectname).gsub(/&/,'%26')}",@storageport,@storagescheme)
  raise NoSuchObjectException, "Object #{objectname} does not exist" if (response.code == "404")
  raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "204")
  true
end

#empty?Boolean

Returns true if a container is empty and returns false otherwise.

new_container.empty?
=> true

full_container.empty?
=> false

Returns:

  • (Boolean)


195
196
197
# File 'lib/cloudfiles/container.rb', line 195

def empty?
  return (@count.to_i == 0)? true : false
end

#log_retention=(value) ⇒ Object

Change the log retention status for this container. Values are true or false.

These logs will be periodically (at unpredictable intervals) compressed and uploaded to a “.CDN_ACCESS_LOGS” container in the form of “container_name.YYYYMMDDHH-XXXX.gz”.



88
89
90
91
92
# File 'lib/cloudfiles/container.rb', line 88

def log_retention=(value)
  response = self.connection.cfreq("POST",@cdnmgmthost,@cdnmgmtpath,@cdnmgmtport,@cdnmgmtscheme,{"x-log-retention" => value.to_s.capitalize})
  raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "201" or response.code == "202")
  return true 
end

#log_retention?Boolean

Returns true if log retention is enabled on this container, false otherwise

Returns:

  • (Boolean)


80
81
82
# File 'lib/cloudfiles/container.rb', line 80

def log_retention?
  @cdn_log
end

#make_privateObject

Makes a container private and returns true upon success. Throws NoSuchContainerException if the container doesn’t exist or if the request fails.

Note that if the container was previously public, it will continue to exist out on the CDN until it expires.

container.make_private
=> true


262
263
264
265
266
267
# File 'lib/cloudfiles/container.rb', line 262

def make_private
  headers = { "X-CDN-Enabled" => "False" }
  response = self.connection.cfreq("POST",@cdnmgmthost,@cdnmgmtpath,@cdnmgmtport,@cdnmgmtscheme,headers)
  raise NoSuchContainerException, "Container #{@name} does not exist" unless (response.code == "201" || response.code == "202")
  true
end

#make_public(ttl = 86400) ⇒ Object

Makes a container publicly available via the Cloud Files CDN and returns true upon success. Throws NoSuchContainerException if the container doesn’t exist or if the request fails.

Takes an optional argument, which is the CDN cache TTL in seconds (default 86400 seconds or 1 day, maximum 259200 or 3 days)

container.make_public(432000)
=> true


245
246
247
248
249
250
251
252
253
# File 'lib/cloudfiles/container.rb', line 245

def make_public(ttl = 86400)
  response = self.connection.cfreq("PUT",@cdnmgmthost,@cdnmgmtpath,@cdnmgmtport,@cdnmgmtscheme)
  raise NoSuchContainerException, "Container #{@name} does not exist" unless (response.code == "201" || response.code == "202")

  headers = { "X-TTL" => ttl.to_s }
  response = self.connection.cfreq("POST",@cdnmgmthost,@cdnmgmtpath,@cdnmgmtport,@cdnmgmtscheme,headers)
  raise NoSuchContainerException, "Container #{@name} does not exist" unless (response.code == "201" || response.code == "202")
  true
end

#object(objectname) ⇒ Object Also known as: get_object

Returns the CloudFiles::StorageObject for the named object. Refer to the CloudFiles::StorageObject class for available methods. If the object exists, it will be returned. If the object does not exist, a NoSuchObjectException will be thrown.

object = container.object('test.txt')
object.data
=> "This is test data"

object = container.object('newfile.txt')
=> NoSuchObjectException: Object newfile.txt does not exist


104
105
106
107
# File 'lib/cloudfiles/container.rb', line 104

def object(objectname)
  o = CloudFiles::StorageObject.new(self,objectname,true)
  return o
end

#object_exists?(objectname) ⇒ Boolean

Returns true if object exists and returns false otherwise.

container.object_exists?('goodfile.txt')
=> true

container.object_exists?('badfile.txt')
=> false

Returns:

  • (Boolean)


206
207
208
209
# File 'lib/cloudfiles/container.rb', line 206

def object_exists?(objectname)
  response = self.connection.cfreq("HEAD",@storagehost,"#{@storagepath}/#{URI.encode(objectname).gsub(/&/,'%26')}",@storageport,@storagescheme)
  return (response.code == "204")? true : false
end

#objects(params = {}) ⇒ Object Also known as: list_objects

Gathers a list of all available objects in the current container and returns an array of object names.

container = cf.container("My Container")
container.objects                     #=> [ "dog", "cat", "donkey", "monkeydir/capuchin"]

Pass a limit argument to limit the list to a number of objects:

container.objects(:limit => 1)                  #=> [ "dog" ]

Pass an offset with or without a limit to start the list at a certain object:

container.objects(:limit => 1, :offset => 2)                #=> [ "donkey" ]

Pass a prefix to search for objects that start with a certain string:

container.objects(:prefix => "do")       #=> [ "dog", "donkey" ]

Only search within a certain pseudo-filesystem path:

container.objects(:path => 'monkeydir')     #=> ["monkeydir/capuchin"]

All arguments to this method are optional.

Returns an empty array if no object exist in the container. Throws an InvalidResponseException if the request fails.



126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/cloudfiles/container.rb', line 126

def objects(params = {})
  paramarr = []
  paramarr << ["limit=#{URI.encode(params[:limit].to_i).gsub(/&/,'%26')}"] if params[:limit]
  paramarr << ["offset=#{URI.encode(params[:offset].to_i).gsub(/&/,'%26')}"] if params[:offset]
  paramarr << ["prefix=#{URI.encode(params[:prefix]).gsub(/&/,'%26')}"] if params[:prefix]
  paramarr << ["path=#{URI.encode(params[:path]).gsub(/&/,'%26')}"] if params[:path]
  paramstr = (paramarr.size > 0)? paramarr.join("&") : "" ;
  response = self.connection.cfreq("GET",@storagehost,"#{@storagepath}?#{paramstr}",@storageport,@storagescheme)
  return [] if (response.code == "204")
  raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "200")
  return CloudFiles.lines(response.body)
end

#objects_detail(params = {}) ⇒ Object Also known as: list_objects_info

Retrieves a list of all objects in the current container along with their size in bytes, hash, and content_type. If no objects exist, an empty hash is returned. Throws an InvalidResponseException if the request fails. Takes a parameter hash as an argument, in the same form as the objects method.

Returns a hash in the same format as the containers_detail from the CloudFiles class.

container.objects_detail
=> {"test.txt"=>{:content_type=>"application/octet-stream", 
                 :hash=>"e2a6fcb4771aa3509f6b27b6a97da55b", 
                 :last_modified=>Mon Jan 19 10:43:36 -0600 2009, 
                 :bytes=>"16"}, 
    "new.txt"=>{:content_type=>"application/octet-stream", 
                :hash=>"0aa820d91aed05d2ef291d324e47bc96", 
                :last_modified=>Wed Jan 28 10:16:26 -0600 2009, 
                :bytes=>"22"}
   }


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/cloudfiles/container.rb', line 156

def objects_detail(params = {})
  paramarr = []
  paramarr << ["format=xml"]
  paramarr << ["limit=#{URI.encode(params[:limit].to_i).gsub(/&/,'%26')}"] if params[:limit]
  paramarr << ["offset=#{URI.encode(params[:offset].to_i).gsub(/&/,'%26')}"] if params[:offset]
  paramarr << ["prefix=#{URI.encode(params[:prefix]).gsub(/&/,'%26')}"] if params[:prefix]
  paramarr << ["path=#{URI.encode(params[:path]).gsub(/&/,'%26')}"] if params[:path]
  paramstr = (paramarr.size > 0)? paramarr.join("&") : "" ;
  response = self.connection.cfreq("GET",@storagehost,"#{@storagepath}?#{paramstr}",@storageport,@storagescheme)
  return {} if (response.code == "204")
  raise InvalidResponseException, "Invalid response code #{response.code}" unless (response.code == "200")
  doc = REXML::Document.new(response.body)
  detailhash = {}
  doc.elements.each("container/object") { |o|
    detailhash[o.elements["name"].text] = { :bytes => o.elements["bytes"].text, :hash => o.elements["hash"].text, :content_type => o.elements["content_type"].text, :last_modified => Time.parse(o.elements["last_modified"].text) }
  }
  doc = nil
  return detailhash
end

#populateObject Also known as: refresh

Retrieves data about the container and populates class variables. It is automatically called when the Container class is instantiated. If you need to refresh the variables, such as size, count, cdn_enabled, cdn_ttl, and cdn_url, this method can be called again.

container.count
=> 2
[Upload new file to the container]
container.count
=> 2
container.populate
container.count
=> 3


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/cloudfiles/container.rb', line 57

def populate
  # Get the size and object count
  response = self.connection.cfreq("HEAD",@storagehost,@storagepath+"/",@storageport,@storagescheme)
  raise NoSuchContainerException, "Container #{@name} does not exist" unless (response.code == "204")
  @bytes = response["x-container-bytes-used"].to_i
  @count = response["x-container-object-count"].to_i

  # Get the CDN-related details
  response = self.connection.cfreq("HEAD",@cdnmgmthost,@cdnmgmtpath,@cdnmgmtport,@cdnmgmtscheme)
  @cdn_enabled = ((response["x-cdn-enabled"] || "").downcase == "true") ? true : false
  @cdn_ttl = @cdn_enabled ? response["x-ttl"] : false
  @cdn_url = @cdn_enabled ? response["x-cdn-uri"] : false
  if @cdn_enabled
    @cdn_log = response["x-log-retention"] == "False" ? false : true
  else
    @cdn_log = false
  end

  true
end

#public?Boolean

Returns true if the container is public and CDN-enabled. Returns false otherwise.

public_container.public?
=> true

private_container.public?
=> false

Returns:

  • (Boolean)


184
185
186
# File 'lib/cloudfiles/container.rb', line 184

def public?
  return @cdn_enabled
end

#to_sObject

:nodoc:



269
270
271
# File 'lib/cloudfiles/container.rb', line 269

def to_s # :nodoc:
  @name
end