Class: HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/secured_cloud_api_client/http_client.rb

Overview

Class HttpClient performs HTTP requests to the Secured Cloud API Server. Authentication is handled via the supplied application key and shared secret.

This class expects the pem file “/cert/sc.pem” to be found in the working directory of the application using this library. This pem file is used for SSL validation.

@author

Alan Vella

Constant Summary collapse

APP_CONTENT_TYPE =
"application/vnd.securedcloud.v7.0+json"
AUTH_SCHEME =
"SC "
PEM_FILE_PATH =
Dir.pwd + "/cert/sc.pem"

Class Method Summary collapse

Class Method Details

.createAuthorization(method, url) ⇒ Object

Creates authorization header for a given method and URL.



282
283
284
285
286
287
288
289
# File 'lib/secured_cloud_api_client/http_client.rb', line 282

def self.createAuthorization(method, url)
  stringToSign = method + " " + removeServletName(url) + " " + @applicationKey
  hash = OpenSSL::HMAC.digest('sha256', @sharedSecret, stringToSign)
  requestSignature = Base64.encode64(hash).gsub(/\s+/, ' ').strip    
  credentials = @applicationKey + ":" + requestSignature;    
  encodedCredentials = Base64.encode64(credentials).gsub(/\s+/, ' ').strip
  return encodedCredentials
end

.handleResponseError(response) ⇒ Object

Raise error if response is not successful.



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
79
80
81
# File 'lib/secured_cloud_api_client/http_client.rb', line 35

def self.handleResponseError(response)
  
  if ((response.code != "202") && (response.code != "200")) then
    
    errorMsg = ""
    
    httpStatusDesc = ""
    
    #Add description of HTTP error code
    if (response.code == "400") then
      httpStatusDesc = "Bad Request"
      
    elsif (response.code == "403") then
      httpStatusDesc = "Forbidden"
      
    elsif (response.code == "404") then
      httpStatusDesc = "Resource Not Found"
      
    elsif (response.code == "405") then
      httpStatusDesc = "Method Not Allowed"
      
    elsif (response.code == "405") then
      httpStatusDesc = "Too Many Requests"
      
    elsif (response.code == "500") then
      httpStatusDesc = "Internal Error"
      
    end
    
    #Add error message from SecuredCloud API if there is any
    if ((response['X-Application-Error-Reference'] != nil) && (response['X-Application-Error-Reference'] != "")) then
      errorMsg = response['X-Application-Error-Reference']
    end
    if ((response['X-Application-Error-Description'] != nil) && (response['X-Application-Error-Description'] != "")) then
      errorMsg = response['X-Application-Error-Description']
    end
    
    #Build final error message to be sent to user.
    if (errorMsg == "") then
      errorMsg = "Error " + response.code.to_str() + " (" + httpStatusDesc + ") " + response.body()
    else
      errorMsg = "Error " + response.code.to_str() + " (" + httpStatusDesc + ") " + errorMsg  
    end
    
    raise errorMsg
  end
end

.removeServletName(url) ⇒ Object

Removes the servlet name from a given external API URL.



271
272
273
274
275
276
277
278
# File 'lib/secured_cloud_api_client/http_client.rb', line 271

def self.removeServletName(url)
  urlAsArray = url.split("/");
  newURL = ""
  for i in 4..(urlAsArray.size() - 1)
    newURL += "/" + urlAsArray[i]
  end
  return newURL
end

.runChecksObject

Run checks before issuing request.



26
27
28
29
30
# File 'lib/secured_cloud_api_client/http_client.rb', line 26

def self.runChecks
  if !(File.exists?(PEM_FILE_PATH)) then
    raise "A valid pem file named sc.pem is required for SSL validation. This file must be placed in the cert directory of your vagrant workspace."
  end
end

.sendDELETERequest(authInfo, url, params = nil) ⇒ Object

Sends an HTTP DELETE request and returns response.



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/secured_cloud_api_client/http_client.rb', line 167

def self.sendDELETERequest(authInfo, url, params = nil)
  
  self.runChecks
  
  begin
  
    @applicationKey = authInfo.getApplicationKey()
    @sharedSecret = authInfo.getSharedSecret()
  
    #Add parameters if present
    if (params != nil) then
      url += "?"
      params.each do |param|
        url += param[0] + "=" + param[1] + "&"
      end
    
      #Remove last ampersand
      url = url[0...-1]
    end
  
    @url = URI.parse(url)
      
    #Setup SSL validation.
    http = Net::HTTP.new(@url.host, @url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    http.cert_store = OpenSSL::X509::Store.new
    http.cert_store.set_default_paths
    http.cert_store.add_file(PEM_FILE_PATH)
     
    #Create and execute request
    request = Net::HTTP::Delete.new(@url.request_uri)
    request['Accept'] = APP_CONTENT_TYPE  
    request['Content-Type'] = APP_CONTENT_TYPE
    request['Authorization'] = AUTH_SCHEME + createAuthorization("DELETE", url)
    response = http.request(request)  
    
    rescue Exception => e  
      raise "Error creating API request: " + e.message
  
  end  
  
  #Raise error if response is not successful.
  self.handleResponseError(response)
  
  #Return response.
  return response
  
end

.sendGETRequest(authInfo, url) ⇒ Object

Sends an HTTP GET request and returns response.



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/secured_cloud_api_client/http_client.rb', line 85

def self.sendGETRequest(authInfo, url)

  self.runChecks

  begin
    
    @applicationKey = authInfo.getApplicationKey()
    @sharedSecret = authInfo.getSharedSecret()
  
    @url = URI.parse(url)
      
    #Setup SSL validation.
    http = Net::HTTP.new(@url.host, @url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    http.cert_store = OpenSSL::X509::Store.new
    http.cert_store.set_default_paths
    http.cert_store.add_file(PEM_FILE_PATH)
     
    #Create and execute request
    request = Net::HTTP::Get.new(@url.request_uri)
    request['Accept'] = APP_CONTENT_TYPE  
    request['Authorization'] = AUTH_SCHEME + createAuthorization("GET", url)
    response = http.request(request)
    
    rescue Exception => e  
      raise "Error creating API request: " + e.message
    
  end    
  
  #Raise error if response is not successful.
  self.handleResponseError(response)
  
  #Return response.
  return response
end

.sendPOSTRequest(authInfo, url, body) ⇒ Object

Sends an HTTP POST request and returns response.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/secured_cloud_api_client/http_client.rb', line 126

def self.sendPOSTRequest(authInfo, url, body)
  
  self.runChecks
  
  begin
  
    @applicationKey = authInfo.getApplicationKey()
    @sharedSecret = authInfo.getSharedSecret()
  
    @url = URI.parse(url)
      
    #Setup SSL validation.
    http = Net::HTTP.new(@url.host, @url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    http.cert_store = OpenSSL::X509::Store.new
    http.cert_store.set_default_paths
    http.cert_store.add_file(PEM_FILE_PATH)
     
    #Create and execute request
    request = Net::HTTP::Post.new(@url.request_uri)
    request['Accept'] = APP_CONTENT_TYPE  
    request['Content-Type'] = APP_CONTENT_TYPE
    request['Authorization'] = AUTH_SCHEME + createAuthorization("POST", url)
    request.body = body
    response = http.request(request)
    
    rescue Exception => e  
      raise "Error creating API request: " + e.message    
  
  end
  
  #Raise error if response is not successful.
  self.handleResponseError(response)
  
  #Return response.
  return response
end

.sendPUTRequest(authInfo, url, params = nil) ⇒ Object

Sends an HTTP PUT request and returns response.



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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/secured_cloud_api_client/http_client.rb', line 219

def self.sendPUTRequest(authInfo, url, params = nil)
  
  self.runChecks
  
  begin
  
    @applicationKey = authInfo.getApplicationKey()
    @sharedSecret = authInfo.getSharedSecret()
  
    #Add parameters if present
    if (params != nil) then
      url += "?"
      params.each do |param|
        url += param[0] + "=" + param[1] + "&"
      end
    
      #Remove last ampersand
      url = url[0...-1]
    end
  
    @url = URI.parse(url)
      
    #Setup SSL validation.
    http = Net::HTTP.new(@url.host, @url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    http.cert_store = OpenSSL::X509::Store.new
    http.cert_store.set_default_paths
    http.cert_store.add_file(PEM_FILE_PATH)
     
    #Create and execute request
    request = Net::HTTP::Put.new(@url.request_uri)
    request['Accept'] = APP_CONTENT_TYPE  
    request['Content-Type'] = APP_CONTENT_TYPE
    request['Authorization'] = AUTH_SCHEME + createAuthorization("PUT", url)
    response = http.request(request)
    
    rescue Exception => e  
      raise "Error creating API request: " + e.message
      
  end    
  
  #Raise error if response is not successful.
  self.handleResponseError(response)
  
  #Return response.
  return response
  
end