Class: AMEE::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/amee/connection.rb,
lib/amee/v3/connection.rb

Constant Summary collapse

RootCA =
File.dirname(__FILE__) + '/../../cacert.pem'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server, username, password, options = {}) ⇒ Connection

Returns a new instance of Connection.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/amee/connection.rb', line 12

def initialize(server, username, password, options = {})
  unless options.is_a?(Hash)
    raise AMEE::ArgumentError.new("Fourth argument must be a hash of options!")
  end
  @server = server
  @username = username
  @password = password
  @ssl = (options[:ssl] == false) ? false : true
  @port = @ssl ? 443 : 80
  @auth_token = nil
  @format = options[:format] || (defined?(JSON) ? :json : :xml)
  @amee_source = options[:amee_source]
  @retries = options[:retries] || 0
  if !valid?
   raise "You must supply connection details - server, username and password are all required!"
  end
  # Handle old option
  if options[:enable_caching]
    Kernel.warn '[DEPRECATED] :enable_caching => true is deprecated. Use :cache => :memory_store instead'
    options[:cache] ||= :memory_store
  end
  # Create cache store
  if options[:cache] &&
    (options[:cache_store].is_a?(ActiveSupport::Cache::MemCacheStore) ||
     options[:cache].to_sym == :mem_cache_store)         
    raise 'ActiveSupport::Cache::MemCacheStore is not supported, as it doesn\'t allow regexp expiry'
  end
  if options[:cache_store].is_a?(ActiveSupport::Cache::Store)
    # Allows assignment of the entire cache store in Rails apps
    @cache = options[:cache_store]
  elsif options[:cache]
    if options[:cache_options]
      @cache = ActiveSupport::Cache.lookup_store(options[:cache].to_sym, options[:cache_options])
    else
      @cache = ActiveSupport::Cache.lookup_store(options[:cache].to_sym)
    end
  end
  # Make connection to server
  @http = Net::HTTP.new(@server, @port)
  if @ssl == true
    @http.use_ssl = true
    if File.exists? RootCA
      @http.ca_file = RootCA
      @http.verify_mode = OpenSSL::SSL::VERIFY_PEER
      @http.verify_depth = 5
    end
  end
  self.timeout = options[:timeout] || 60
  @http.set_debug_output($stdout) if options[:enable_debug]
  @debug = options[:enable_debug]
end

Instance Attribute Details

#formatObject (readonly)

Returns the value of attribute format.



64
65
66
# File 'lib/amee/connection.rb', line 64

def format
  @format
end

#passwordObject (readonly)

Returns the value of attribute password.



67
68
69
# File 'lib/amee/connection.rb', line 67

def password
  @password
end

#retriesObject (readonly)

Returns the value of attribute retries.



68
69
70
# File 'lib/amee/connection.rb', line 68

def retries
  @retries
end

#serverObject (readonly)

Returns the value of attribute server.



65
66
67
# File 'lib/amee/connection.rb', line 65

def server
  @server
end

#usernameObject (readonly)

Returns the value of attribute username.



66
67
68
# File 'lib/amee/connection.rb', line 66

def username
  @username
end

Class Method Details

.api_versionObject



7
8
9
# File 'lib/amee/v3/connection.rb', line 7

def self.api_version
  '3'
end

Instance Method Details

#authenticateObject



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/amee/connection.rb', line 172

def authenticate
  response = nil
  post = Net::HTTP::Post.new("/auth/signIn")
  post.body = "username=#{@username}&password=#{@password}"
  post['Accept'] = content_type(:xml)
  post['X-AMEE-Source'] = @amee_source if @amee_source
  response = @http.request(post)
  @auth_token = response['authToken']
  unless authenticated?
    raise AMEE::AuthFailed.new("Authentication failed. Please check your username and password. (tried #{@username},#{@password})")
  end
  # Detect API version
  if response.body.is_json?
    @version = JSON.parse(response.body)["user"]["apiVersion"].to_f
  elsif response.body.is_xml?
    @version = REXML::Document.new(response.body).elements['Resources'].elements['SignInResource'].elements['User'].elements['ApiVersion'].text.to_f
  else
    @version = 1.0
  end
end

#authenticated?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/amee/connection.rb', line 87

def authenticated?
  !@auth_token.nil?
end

#delete(path) ⇒ Object



164
165
166
167
168
169
170
# File 'lib/amee/connection.rb', line 164

def delete(path)
  expire_matching "#{parent_path(path)}.*"
  # Create DELETE request
  delete = Net::HTTP::Delete.new(path)
  # Send request
  do_request(delete)
end

#expire(path, options = nil) ⇒ Object



307
308
309
# File 'lib/amee/connection.rb', line 307

def expire(path, options = nil)
  @cache.delete(cache_key(path), options) if @cache
end

#expire_allObject



315
316
317
# File 'lib/amee/connection.rb', line 315

def expire_all
  @cache.clear if @cache
end

#expire_matching(matcher, options = nil) ⇒ Object



311
312
313
# File 'lib/amee/connection.rb', line 311

def expire_matching(matcher, options = nil)
  @cache.delete_matched(Regexp.new(cache_key(matcher)), options) if @cache
end

#get(path, data = {}) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/amee/connection.rb', line 91

def get(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Create URL parameters
  params = []
  data.each_pair do |key, value|
    params << "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}"
  end
  if params.size > 0
    path += "?#{params.join('&')}"
  end
  # Send request      
  cache(path) { do_request(Net::HTTP::Get.new(path), format) }
end

#post(path, data = {}) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/amee/connection.rb', line 106

def post(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Clear cache
  expire_matching "#{raw_path(path)}.*"
  # Create POST request
  post = Net::HTTP::Post.new(path)
  body = []
    data.each_pair do |key, value|
    body << "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}"
  end
  post.body = body.join '&'
  # Send request
  do_request(post, format)
end

#put(path, data = {}) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/amee/connection.rb', line 135

def put(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Clear cache
  expire_matching "#{parent_path(path)}.*"
  # Create PUT request
  put = Net::HTTP::Put.new(path)
  body = []
    data.each_pair do |key, value|
    body << "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}"
  end
  put.body = body.join '&'
  # Send request
  do_request(put, format)
end

#raw_post(path, body, options = {}) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/amee/connection.rb', line 122

def raw_post(path, body, options = {})
  # Allow format override
  format = options.delete(:format) || @format
  # Clear cache
  expire_matching "#{raw_path(path)}.*"
  # Create POST request
  post = Net::HTTP::Post.new(path)
  post['Content-type'] = options[:content_type] || content_type(format)
  post.body = body
  # Send request
  do_request(post, format)
end

#raw_put(path, body, options = {}) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/amee/connection.rb', line 151

def raw_put(path, body, options = {})
  # Allow format override
  format = options.delete(:format) || @format
  # Clear cache
  expire_matching "#{parent_path(path)}.*"
  # Create PUT request
  put = Net::HTTP::Put.new(path)
  put['Content-type'] = options[:content_type] || content_type(format)
  put.body = body
  # Send request
  do_request(put, format)
end

#timeoutObject



70
71
72
# File 'lib/amee/connection.rb', line 70

def timeout
  @http.read_timeout
end

#timeout=(t) ⇒ Object



74
75
76
# File 'lib/amee/connection.rb', line 74

def timeout=(t)
  @http.open_timeout = @http.read_timeout = t
end

#v3_authObject



57
58
59
60
# File 'lib/amee/v3/connection.rb', line 57

def v3_auth
  # now the same as v2, i.e.
  [@username,@password]
end

#v3_connectionObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/amee/v3/connection.rb', line 11

def v3_connection
  @v3_http ||= begin
    @v3_http = Net::HTTP.new(v3_hostname, @port)
    if @ssl == true
      @v3_http.use_ssl = true
      if File.exists? RootCA
        @v3_http.ca_file = RootCA
        @v3_http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        @v3_http.verify_depth = 5
      end
    end
    @v3_http.set_debug_output($stdout) if @debug
    @v3_http
  end
end

#v3_delete(path, options = {}) ⇒ Object



52
53
54
55
56
# File 'lib/amee/v3/connection.rb', line 52

def v3_delete(path, options = {})
  expire_matching "#{parent_path(path)}.*"
  delete = Net::HTTP::Delete.new(path)
  v3_request delete
end

#v3_get(path, options = {}) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/amee/v3/connection.rb', line 26

def v3_get(path, options = {})
  # Create URL parameters
  unless options.empty?
    path += "?" + options.map { |x| "#{CGI::escape(x[0].to_s)}=#{CGI::escape(x[1].to_s)}" }.join('&')
  end
  cache(path) { v3_request(Net::HTTP::Get.new(path)) }
end

#v3_post(path, options = {}) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/amee/v3/connection.rb', line 45

def v3_post(path, options = {})
  expire_matching "#{raw_path(path)}.*"
  post = Net::HTTP::Post.new(path)
  returnobj=options.delete(:returnobj) || false
  post.set_form_data(options)
  v3_request post,returnobj
end

#v3_put(path, options = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/amee/v3/connection.rb', line 33

def v3_put(path, options = {})
  expire_matching "#{parent_path(path)}.*"
  put = Net::HTTP::Put.new(path)
  if options[:body]
    put.body = options[:body]
    put['Content-Type'] = content_type :xml if options[:body].is_xml?
    put['Content-Type'] = content_type :json if options[:body].is_json?
  else
    put.set_form_data(options)
  end
  v3_request put
end

#valid?Boolean

Returns:

  • (Boolean)


83
84
85
# File 'lib/amee/connection.rb', line 83

def valid?
  @username && @password && @server
end

#versionObject



78
79
80
81
# File 'lib/amee/connection.rb', line 78

def version
  authenticate if @version.nil?
  @version
end