ibm_sbdtc_rest 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ require File.join(File.dirname(__FILE__), 'support', 'class')
2
+ require File.join(File.dirname(__FILE__), 'support', 'blank')
3
+ require 'timeout'
4
+
5
+ # This file must be loaded after the JSON gem and any other library that beats up the Time class.
6
+ class Time
7
+ # This date format sorts lexicographically
8
+ # and is compatible with Javascript's <tt>new Date(time_string)</tt> constructor.
9
+ # Note this this format stores all dates in UTC so that collation
10
+ # order is preserved. (There's no longer a need to set <tt>ENV['TZ'] = 'UTC'</tt>
11
+ # in your application.)
12
+
13
+ def to_json(options = nil)
14
+ u = self.getutc
15
+ %("#{u.strftime("%Y/%m/%d %H:%M:%S +0000")}")
16
+ end
17
+
18
+ # Decodes the JSON time format to a UTC time.
19
+ # Based on Time.parse from ActiveSupport. ActiveSupport's version
20
+ # is more complete, returning a time in your current timezone,
21
+ # rather than keeping the time in UTC. YMMV.
22
+ # def self.parse string, fallback=nil
23
+ # d = DateTime.parse(string).new_offset
24
+ # self.utc(d.year, d.month, d.day, d.hour, d.min, d.sec)
25
+ # rescue
26
+ # fallback
27
+ # end
28
+ end
29
+
30
+ # Monkey patch for faster net/http io
31
+ if RUBY_VERSION.to_f < 1.9
32
+ class Net::BufferedIO #:nodoc:
33
+ alias :old_rbuf_fill :rbuf_fill
34
+ def rbuf_fill
35
+ if @io.respond_to?(:read_nonblock)
36
+ begin
37
+ @rbuf << @io.read_nonblock(65536)
38
+ rescue Errno::EWOULDBLOCK
39
+ if IO.select([@io], nil, nil, @read_timeout)
40
+ retry
41
+ else
42
+ raise Timeout::Error
43
+ end
44
+ end
45
+ else
46
+ timeout(@read_timeout) do
47
+ @rbuf << @io.sysread(65536)
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
53
+
54
+ # module RestClient
55
+ # # def self.copy(url, headers={})
56
+ # # Request.execute(:method => :copy,
57
+ # # :url => url,
58
+ # # :headers => headers)
59
+ # # end
60
+ #
61
+ # # class Request
62
+ # #
63
+ # # def establish_connection(uri)
64
+ # # Thread.current[:connection].finish if (Thread.current[:connection] && Thread.current[:connection].started?)
65
+ # # p net_http_class
66
+ # # net = net_http_class.new(uri.host, uri.port)
67
+ # # net.use_ssl = uri.is_a?(URI::HTTPS)
68
+ # # net.verify_mode = OpenSSL::SSL::VERIFY_NONE
69
+ # # Thread.current[:connection] = net
70
+ # # Thread.current[:connection].start
71
+ # # Thread.current[:connection]
72
+ # # end
73
+ # #
74
+ # # def transmit(uri, req, payload)
75
+ # # setup_credentials(req)
76
+ # #
77
+ # # Thread.current[:host] ||= uri.host
78
+ # # Thread.current[:port] ||= uri.port
79
+ # #
80
+ # # if (Thread.current[:connection].nil? || (Thread.current[:host] != uri.host))
81
+ # # p "establishing a connection"
82
+ # # establish_connection(uri)
83
+ # # end
84
+ # #
85
+ # # display_log request_log
86
+ # # http = Thread.current[:connection]
87
+ # # http.read_timeout = @timeout if @timeout
88
+ # #
89
+ # # begin
90
+ # # res = http.request(req, payload)
91
+ # # rescue
92
+ # # p "Net::HTTP connection failed, reconnecting"
93
+ # # establish_connection(uri)
94
+ # # http = Thread.current[:connection]
95
+ # # require 'ruby-debug'
96
+ # # req.body_stream = nil
97
+ # #
98
+ # # res = http.request(req, payload)
99
+ # # display_log response_log(res)
100
+ # # result res
101
+ # # else
102
+ # # display_log response_log(res)
103
+ # # process_result res
104
+ # # end
105
+ # #
106
+ # # rescue EOFError
107
+ # # raise RestClient::ServerBrokeConnection
108
+ # # rescue Timeout::Error
109
+ # # raise RestClient::RequestTimeout
110
+ # # end
111
+ # # end
112
+ #
113
+ # end
@@ -0,0 +1,42 @@
1
+ # blank? methods for several different class types
2
+ class Object
3
+ # Returns true if the object is nil or empty (if applicable)
4
+ def blank?
5
+ nil? || (respond_to?(:empty?) && empty?)
6
+ end
7
+ end # class Object
8
+
9
+ class Numeric
10
+ # Numerics can't be blank
11
+ def blank?
12
+ false
13
+ end
14
+ end # class Numeric
15
+
16
+ class NilClass
17
+ # Nils are always blank
18
+ def blank?
19
+ true
20
+ end
21
+ end # class NilClass
22
+
23
+ class TrueClass
24
+ # True is not blank.
25
+ def blank?
26
+ false
27
+ end
28
+ end # class TrueClass
29
+
30
+ class FalseClass
31
+ # False is always blank.
32
+ def blank?
33
+ true
34
+ end
35
+ end # class FalseClass
36
+
37
+ class String
38
+ # Strips out whitespace then tests if the string is empty.
39
+ def blank?
40
+ strip.empty?
41
+ end
42
+ end # class String
@@ -0,0 +1,176 @@
1
+ # Copyright (c) 2004-2008 David Heinemeier Hansson
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # Allows attributes to be shared within an inheritance hierarchy, but where
23
+ # each descendant gets a copy of their parents' attributes, instead of just a
24
+ # pointer to the same. This means that the child can add elements to, for
25
+ # example, an array without those additions being shared with either their
26
+ # parent, siblings, or children, which is unlike the regular class-level
27
+ # attributes that are shared across the entire hierarchy.
28
+ class Class
29
+ # Defines class-level and instance-level attribute reader.
30
+ #
31
+ # @param *syms<Array> Array of attributes to define reader for.
32
+ # @return <Array[#to_s]> List of attributes that were made into cattr_readers
33
+ #
34
+ # @api public
35
+ #
36
+ # @todo Is this inconsistent in that it does not allow you to prevent
37
+ # an instance_reader via :instance_reader => false
38
+ def cattr_reader(*syms)
39
+ syms.flatten.each do |sym|
40
+ next if sym.is_a?(Hash)
41
+ class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
42
+ unless defined? @@#{sym}
43
+ @@#{sym} = nil
44
+ end
45
+
46
+ def self.#{sym}
47
+ @@#{sym}
48
+ end
49
+
50
+ def #{sym}
51
+ @@#{sym}
52
+ end
53
+ RUBY
54
+ end
55
+ end unless Class.respond_to?(:cattr_reader)
56
+
57
+ # Defines class-level (and optionally instance-level) attribute writer.
58
+ #
59
+ # @param <Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to define writer for.
60
+ # @option syms :instance_writer<Boolean> if true, instance-level attribute writer is defined.
61
+ # @return <Array[#to_s]> List of attributes that were made into cattr_writers
62
+ #
63
+ # @api public
64
+ def cattr_writer(*syms)
65
+ options = syms.last.is_a?(Hash) ? syms.pop : {}
66
+ syms.flatten.each do |sym|
67
+ class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
68
+ unless defined? @@#{sym}
69
+ @@#{sym} = nil
70
+ end
71
+
72
+ def self.#{sym}=(obj)
73
+ @@#{sym} = obj
74
+ end
75
+ RUBY
76
+
77
+ unless options[:instance_writer] == false
78
+ class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
79
+ def #{sym}=(obj)
80
+ @@#{sym} = obj
81
+ end
82
+ RUBY
83
+ end
84
+ end
85
+ end unless Class.respond_to?(:cattr_writer)
86
+
87
+ # Defines class-level (and optionally instance-level) attribute accessor.
88
+ #
89
+ # @param *syms<Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to define accessor for.
90
+ # @option syms :instance_writer<Boolean> if true, instance-level attribute writer is defined.
91
+ # @return <Array[#to_s]> List of attributes that were made into accessors
92
+ #
93
+ # @api public
94
+ def cattr_accessor(*syms)
95
+ cattr_reader(*syms)
96
+ cattr_writer(*syms)
97
+ end unless Class.respond_to?(:cattr_accessor)
98
+
99
+ # Defines class-level inheritable attribute reader. Attributes are available to subclasses,
100
+ # each subclass has a copy of parent's attribute.
101
+ #
102
+ # @param *syms<Array[#to_s]> Array of attributes to define inheritable reader for.
103
+ # @return <Array[#to_s]> Array of attributes converted into inheritable_readers.
104
+ #
105
+ # @api public
106
+ #
107
+ # @todo Do we want to block instance_reader via :instance_reader => false
108
+ # @todo It would be preferable that we do something with a Hash passed in
109
+ # (error out or do the same as other methods above) instead of silently
110
+ # moving on). In particular, this makes the return value of this function
111
+ # less useful.
112
+ def extlib_inheritable_reader(*ivars)
113
+ instance_reader = ivars.pop[:reader] if ivars.last.is_a?(Hash)
114
+
115
+ ivars.each do |ivar|
116
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
117
+ def self.#{ivar}
118
+ return @#{ivar} if self.object_id == #{self.object_id} || defined?(@#{ivar})
119
+ ivar = superclass.#{ivar}
120
+ return nil if ivar.nil? && !#{self}.instance_variable_defined?("@#{ivar}")
121
+ @#{ivar} = ivar && !ivar.is_a?(Module) && !ivar.is_a?(Numeric) && !ivar.is_a?(TrueClass) && !ivar.is_a?(FalseClass) ? ivar.dup : ivar
122
+ end
123
+ RUBY
124
+ unless instance_reader == false
125
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
126
+ def #{ivar}
127
+ self.class.#{ivar}
128
+ end
129
+ RUBY
130
+ end
131
+ end
132
+ end unless Class.respond_to?(:extlib_inheritable_reader)
133
+
134
+ # Defines class-level inheritable attribute writer. Attributes are available to subclasses,
135
+ # each subclass has a copy of parent's attribute.
136
+ #
137
+ # @param *syms<Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to
138
+ # define inheritable writer for.
139
+ # @option syms :instance_writer<Boolean> if true, instance-level inheritable attribute writer is defined.
140
+ # @return <Array[#to_s]> An Array of the attributes that were made into inheritable writers.
141
+ #
142
+ # @api public
143
+ #
144
+ # @todo We need a style for class_eval <<-HEREDOC. I'd like to make it
145
+ # class_eval(<<-RUBY, __FILE__, __LINE__), but we should codify it somewhere.
146
+ def extlib_inheritable_writer(*ivars)
147
+ instance_writer = ivars.pop[:writer] if ivars.last.is_a?(Hash)
148
+ ivars.each do |ivar|
149
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
150
+ def self.#{ivar}=(obj)
151
+ @#{ivar} = obj
152
+ end
153
+ RUBY
154
+ unless instance_writer == false
155
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
156
+ def #{ivar}=(obj) self.class.#{ivar} = obj end
157
+ RUBY
158
+ end
159
+ end
160
+ end unless Class.respond_to?(:extlib_inheritable_writer)
161
+
162
+ # Defines class-level inheritable attribute accessor. Attributes are available to subclasses,
163
+ # each subclass has a copy of parent's attribute.
164
+ #
165
+ # @param *syms<Array[*#to_s, Hash{:instance_writer => Boolean}]> Array of attributes to
166
+ # define inheritable accessor for.
167
+ # @option syms :instance_writer<Boolean> if true, instance-level inheritable attribute writer is defined.
168
+ # @return <Array[#to_s]> An Array of attributes turned into inheritable accessors.
169
+ #
170
+ # @api public
171
+ def extlib_inheritable_accessor(*syms)
172
+ extlib_inheritable_reader(*syms)
173
+ extlib_inheritable_writer(*syms)
174
+ end unless Class.respond_to?(:extlib_inheritable_accessor)
175
+ end
176
+
@@ -0,0 +1,35 @@
1
+ # This file contains various hacks for Rails compatibility.
2
+ # To use, just require in environment.rb, like so:
3
+ #
4
+ # require 'couchrest/support/rails'
5
+
6
+ class Hash
7
+ # Hack so that CouchRest::Document, which descends from Hash,
8
+ # doesn't appear to Rails routing as a Hash of options
9
+ def self.===(other)
10
+ return false if self == Hash && other.is_a?(CouchRest::Document)
11
+ super
12
+ end
13
+ end
14
+
15
+
16
+ CouchRest::Document.class_eval do
17
+ # Hack so that CouchRest::Document, which descends from Hash,
18
+ # doesn't appear to Rails routing as a Hash of options
19
+ def is_a?(o)
20
+ return false if o == Hash
21
+ super
22
+ end
23
+ alias_method :kind_of?, :is_a?
24
+ end
25
+
26
+
27
+ require Pathname.new(File.dirname(__FILE__)).join('..', 'validation', 'validation_errors')
28
+
29
+ CouchRest::Validation::ValidationErrors.class_eval do
30
+ # Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
31
+ # This method is called by error_messages_for
32
+ def count
33
+ errors.values.inject(0) { |error_count, errors_for_attribute| error_count + errors_for_attribute.size }
34
+ end
35
+ end
@@ -0,0 +1,163 @@
1
+ # Copyright 2010 David Ruan
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ require 'rubygems'
16
+ begin
17
+ require 'json'
18
+ rescue LoadError
19
+ raise "You need install and require your own json compatible library since IbmCloudRest rest couldn't load the json/json_pure gem" unless Kernel.const_defined?("JSON")
20
+ end
21
+ require 'rest_client'
22
+
23
+ $:.unshift File.dirname(__FILE__) unless
24
+ $:.include?(File.dirname(__FILE__)) ||
25
+ $:.include?(File.expand_path(File.dirname(__FILE__)))
26
+
27
+ require 'ibm_cloud_rest/monkeypatches'
28
+
29
+ module IbmCloudRest
30
+ VERSION = '0.0.0' unless self.const_defined?("VERSION")
31
+
32
+ autoload :Server, 'ibm_cloud_rest/core/server'
33
+ autoload :Image, 'ibm_cloud_rest/core/image'
34
+ autoload :Instance, 'ibm_cloud_rest/core/instance'
35
+ autoload :Storage, 'ibm_cloud_rest/core/storage'
36
+ autoload :Address, 'ibm_cloud_rest/core/address'
37
+ autoload :Key, 'ibm_cloud_rest/core/key'
38
+ autoload :Request, 'ibm_cloud_rest/core/request'
39
+
40
+
41
+ require File.join(File.dirname(__FILE__), 'ibm_cloud_rest', 'core', 'rest_api')
42
+ require File.join(File.dirname(__FILE__), 'ibm_cloud_rest', 'core', 'http_abstraction')
43
+ require File.join(File.dirname(__FILE__), 'ibm_cloud_rest', 'mixins')
44
+
45
+ # we extend IbmCloudRest with the RestAPI module which gives us acess to
46
+ # the get, post, put, delete and copy
47
+ IbmCloudRest.extend(::RestAPI)
48
+
49
+ # The IbmCloudRest module methods handle the basic JSON serialization
50
+ # and deserialization, as well as query parameters. The module also includes
51
+ # some helpers for tasks like instantiating a new Database or Server instance.
52
+ class << self
53
+
54
+ # extracted from Extlib
55
+ #
56
+ # Constantize tries to find a declared constant with the name specified
57
+ # in the string. It raises a NameError when the name is not in CamelCase
58
+ # or is not initialized.
59
+ #
60
+ # @example
61
+ # "Module".constantize #=> Module
62
+ # "Class".constantize #=> Class
63
+ def constantize(camel_cased_word)
64
+ unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
65
+ raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
66
+ end
67
+
68
+ Object.module_eval("::#{$1}", __FILE__, __LINE__)
69
+ end
70
+
71
+ # extracted from Extlib
72
+ #
73
+ # Capitalizes the first word and turns underscores into spaces and strips _id.
74
+ # Like titleize, this is meant for creating pretty output.
75
+ #
76
+ # @example
77
+ # "employee_salary" #=> "Employee salary"
78
+ # "author_id" #=> "Author"
79
+ def humanize(lower_case_and_underscored_word)
80
+ lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
81
+ end
82
+
83
+ # todo, make this parse the url and instantiate a Server or Database instance
84
+ # depending on the specificity.
85
+ def new(*opts)
86
+ Server.new(*opts)
87
+ end
88
+
89
+ def parse url
90
+ base_path_pattern=/\/cloud\/developer\/api\/rest\/\d+/
91
+ case url
92
+ when /(^https:\/\/.*)(#{base_path_pattern})\/(.*)\/(.*)/
93
+ host = $1
94
+ bash_path = $2
95
+ object = $3
96
+ docid = $4
97
+ when /(^https:\/\/.*)(#{base_path_pattern})\/(.*)/
98
+ host = $1
99
+ bash_path = $2
100
+ object = $3
101
+ when /(^https:\/\/.*)/
102
+ host = $1
103
+ when /(.*)(#{base_path_pattern})\/(.*)\/(.*)/
104
+ host = $1
105
+ bash_path = $2
106
+ object = $3
107
+ docid = $4
108
+ when /(.*)(#{base_path_pattern})\/(.*)/
109
+ host = $1
110
+ bash_path = $2
111
+ object = $3
112
+ else
113
+ object = url
114
+ end
115
+
116
+ object = nil if object && object.empty?
117
+ # https://www.ibm.com/cloud/developer/api/rest/20090403/
118
+ {
119
+ :host => host || "https://www.ibm.com",
120
+ :base_path=> base_path || "/cloud/developer/api/rest/20090403",
121
+ :object => object,
122
+ :doc => docid
123
+ }
124
+ end
125
+
126
+ # set proxy to use
127
+ def proxy url
128
+ HttpAbstraction.proxy = url
129
+ end
130
+
131
+ def instances url
132
+ parsed = parse url
133
+ cr = IbmCloudRest.new(parsed[:host],parsed[:base_path])
134
+ cr.instances
135
+ end
136
+
137
+ # ensure that a database exists
138
+ # creates it if it isn't already there
139
+ # returns it after it's been created
140
+ def database! url
141
+ parsed = parse url
142
+ cr = IbmCloudRest.new(parsed[:host],parsed[:base_path])
143
+ cr.database!(parsed[:database])
144
+ end
145
+
146
+ def database url
147
+ parsed = parse url
148
+ cr = IbmCloudRest.new(parsed[:host],parsed[:base_path])
149
+ cr.database(parsed[:database])
150
+ end
151
+
152
+ def paramify_url url, params = {}
153
+ if params && !params.empty?
154
+ query = params.collect do |k,v|
155
+ v = v.to_json if %w{key startkey endkey}.include?(k.to_s)
156
+ "#{k}=#{CGI.escape(v.to_s)}"
157
+ end.join("&")
158
+ url = "#{url}?#{query}"
159
+ end
160
+ url
161
+ end
162
+ end # class << self
163
+ end