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.



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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/amee/connection.rb', line 20

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

  # Working with caching

  # 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].class.name == "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

  # set up hash to pass to builder block
  @params = {
    :ssl => @ssl,
    :params => {},
    :headers => {}
  }

  if @ssl == true
    @params[:ssl] = true
    if File.exists? RootCA
      @params[:ca_file] = RootCA
    end
  end
  
  self.timeout = options[:timeout] || 60
  @debug = options[:enable_debug]
end

Instance Attribute Details

#auth_tokenObject

Only used in tests really



85
86
87
# File 'lib/amee/connection.rb', line 85

def auth_token
  @auth_token
end

#formatObject (readonly)

Returns the value of attribute format.



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

def format
  @format
end

#passwordObject (readonly)

Returns the value of attribute password.



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

def password
  @password
end

#retriesObject (readonly)

Returns the value of attribute retries.



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

def retries
  @retries
end

#serverObject (readonly)

Returns the value of attribute server.



81
82
83
# File 'lib/amee/connection.rb', line 81

def server
  @server
end

#usernameObject (readonly)

Returns the value of attribute username.



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

def username
  @username
end

Class Method Details

.api_versionObject

API version used in URLs



10
11
12
# File 'lib/amee/v3/connection.rb', line 10

def self.api_version
  '3'
end

Instance Method Details

#authenticateObject

Post to the sign in resource on the API, so that all future requests are signed



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/amee/connection.rb', line 218

def authenticate
  # :x_amee_source = "X-AMEE-Source".to_sym
  request = Typhoeus::Request.new("#{protocol}#{@server}/auth/signIn", 
    :method => "post",
    :verbose => DEBUG,
    :headers => {
      :Accept => content_type(:xml),
    },
    :body => form_encode(:username=>@username, :password=>@password)
  )

  hydra.queue(request)
  hydra.run
  response = request.response

  @auth_token = response.headers_hash['AuthToken']
  d {request.url}
  d {response.code}
  d {@auth_token}

  connection_failed if response.code == 0

  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

check if we have a valid authentication token

Returns:

  • (Boolean)


105
106
107
# File 'lib/amee/connection.rb', line 105

def authenticated?
  @auth_token =~ /^.*$/
end

#delete(path) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
# File 'lib/amee/connection.rb', line 204

def delete(path)
  # Clear cache
  expire_matching "#{parent_path(path)}.*"
  # Create DELETE request
  delete = Typhoeus::Request.new("#{protocol}#{@server}#{path}", 
    :verbose => DEBUG,
    :method => "delete"
  )
 # Send request
  do_request(delete)
end

#expire(path, options = nil) ⇒ Object



431
432
433
# File 'lib/amee/connection.rb', line 431

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

#expire_allObject



439
440
441
# File 'lib/amee/connection.rb', line 439

def expire_all
  @cache.clear if @cache
end

#expire_matching(matcher, options = nil) ⇒ Object



435
436
437
# File 'lib/amee/connection.rb', line 435

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

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

GET data from the API, passing in a hash of parameters



110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/amee/connection.rb', line 110

def get(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Add parameters to URL query string
  get_params = {
    :method => "get", 
    :verbose => DEBUG
  }
  get_params[:params] = data unless data.empty?
  # Create GET request
  get = Typhoeus::Request.new("#{protocol}#{@server}#{path}", get_params)
  # Send request
  do_request(get, format, :cache => true)
end

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

POST to the AMEE API, passing in a hash of values



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/amee/connection.rb', line 126

def post(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Clear cache
  expire_matching "#{raw_path(path)}.*"
  # Extract return unit params
  query_params = {}
  query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit]
  query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit]
  # Create POST request
  post_params = {
    :verbose => DEBUG,
    :method => "post",
    :body => form_encode(data)
  }
  post_params[:params] = query_params unless query_params.empty?
  post = Typhoeus::Request.new("#{protocol}#{@server}#{path}", post_params)
  # Send request
  do_request(post, format)      
end

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

PUT to the AMEE API, passing in a hash of data



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/amee/connection.rb', line 166

def put(path, data = {})
  # Allow format override
  format = data.delete(:format) || @format
  # Clear cache
  expire_matching "#{parent_path(path)}.*"
  # Extract return unit params
  query_params = {}
  query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit]
  query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit]
  # Create PUT request
  put_params = {
    :verbose => DEBUG,
    :method => "put",
    :body => form_encode(data)
  }
  put_params[:params] = query_params unless query_params.empty?
  put = Typhoeus::Request.new("#{protocol}#{@server}#{path}", put_params)
   # Send request
  do_request(put, format)
end

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

POST to the AMEE API, passing in a string of data



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

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 = Typhoeus::Request.new("#{protocol}#{@server}#{path}", 
    :verbose => DEBUG,
    :method => "post",
    :body => body,
    :headers => { :'Content-type' => options[:content_type] || content_type(format)  }
  )

  # Send request
  do_request(post, format)
end

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

PUT to the AMEE API, passing in a string of data



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/amee/connection.rb', line 188

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 = Typhoeus::Request.new("#{protocol}#{@server}#{path}", 
    :verbose => DEBUG,
    :method => "put",
    :body => body,
    :headers => { :'Content-type' => options[:content_type] || content_type(format)  }
  )
  # Send request
  do_request(put, format)
end

#timeoutObject



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

def timeout
  @params[:timeout]
end

#timeout=(t) ⇒ Object



91
92
93
# File 'lib/amee/connection.rb', line 91

def timeout=(t)
  @params[:open_timeout] = @params[:timeout] = t
end

#v3_delete(path) ⇒ Object

Perform a POST request



69
70
71
72
73
74
75
76
77
78
# File 'lib/amee/v3/connection.rb', line 69

def v3_delete(path)
  # Expire cached objects from here on down
  expire_matching "#{parent_path(path)}.*"
  # Create request parameters
  delete_params = { 
    :method => "delete" 
  }
  # Request
  v3_do_request(delete_params, path)
end

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

Perform a GET request options hash should contain query parameters



16
17
18
19
20
21
22
23
24
# File 'lib/amee/v3/connection.rb', line 16

def v3_get(path, options = {})
  # Create request parameters
  get_params = {
    :method => "get"
  }
  get_params[:params] = options unless options.empty?
  # Send request (with caching)
  v3_do_request(get_params, path, :cache => true)
end

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

Perform a POST request options hash should contain request body parameters It can also contain a :returnobj parameter which will cause a full reponse object to be returned instead of just the body



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/amee/v3/connection.rb', line 49

def v3_post(path, options = {})
  # Expire cached objects from here on down
  expire_matching "#{raw_path(path)}.*"
  # Get 'return full response object' flag
  return_obj = options.delete(:returnobj) || false
  # Create request parameters
  post_params = {
    :method => "post",
    :body => form_encode(options)
  }
  if options[:content_type]
    post_params[:headers] = {
      :'Content-Type' => content_type(options[:content_type])
    }
  end
  # Request
  v3_do_request(post_params, path, :return_obj => return_obj)
end

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

Perform a PUT request options hash should contain request body parameters



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/amee/v3/connection.rb', line 28

def v3_put(path, options = {})
  # Expire cached objects from parent on down
  expire_matching "#{parent_path(path)}.*"
  # Create request parameters
  put_params = { 
    :method => "put",
    :body => options[:body] ? options[:body] : form_encode(options)
  }
  if options[:content_type]
    put_params[:headers] = {
      :'Content-Type' => content_type(options[:content_type])
    }
  end
  # Request
  v3_do_request(put_params, path)
end

#valid?Boolean

Returns:

  • (Boolean)


100
101
102
# File 'lib/amee/connection.rb', line 100

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

#versionObject



95
96
97
98
# File 'lib/amee/connection.rb', line 95

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