Class: SlingInterface::Sling

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server = "http://localhost:8080/", trustedauth = false) ⇒ Sling

Returns a new instance of Sling.



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/nakamura.rb', line 89

def initialize(server="http://localhost:8080/", trustedauth=false)
  @server = server
  if not @server.end_with? '/'
    @server += '/'
  end
  @serveruri = URI.parse(server)
  @user = SlingUsers::User.admin_user()
  @trustedauth = trustedauth
  @cookies = Hash.new()
  @loggedin = false
  @log = Logger.new(STDOUT)
  @log.level = Logger::WARN
end

Instance Attribute Details

#logObject

Returns the value of attribute log.



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

def log
  @log
end

#loggedinObject

Returns the value of attribute loggedin.



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

def loggedin
  @loggedin
end

#trustedauthObject

Returns the value of attribute trustedauth.



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

def trustedauth
  @trustedauth
end

Instance Method Details

#clear_acl(path) ⇒ Object



402
403
404
405
# File 'lib/nakamura.rb', line 402

def clear_acl(path)
  acl = JSON.parse(get_node_acl_json(path))
  acl.keys.each { |p| delete_node_acl_entries(path, p) }
end

#create_file_node(path, fieldname, filename, data, content_type = "text/plain") ⇒ Object



329
330
331
# File 'lib/nakamura.rb', line 329

def create_file_node(path, fieldname, filename, data, content_type="text/plain")
  result = execute_file_post(url_for(path), fieldname, filename, data, content_type)
end

#create_node(path, params) ⇒ Object



333
334
335
# File 'lib/nakamura.rb', line 333

def create_node(path, params)
  result = execute_post(url_for(path), params)
end

#createHttp(uri) ⇒ Object



157
158
159
160
161
162
163
164
# File 'lib/nakamura.rb', line 157

def createHttp(uri)
  http = Net::HTTP.new(uri.host, uri.port)
  if (uri.scheme == 'https')
     http.use_ssl = true
     http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  return http
end

#delete_file(path, query_params = nil) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/nakamura.rb', line 186

def delete_file(path, query_params=nil)
  if (query_params != nil)
    param_string = query_params.collect { |k,v|
      val = case v
              when String then
                v
              when Numeric then
                v.to_s
              else
                v.to_json
            end
      CGI.escape(k) + "=" + CGI.escape(val)
    }.join("&")
    path = "#{path}?#{param_string}"
  end
  uri = URI.parse(path)
  path = uri.path
  path = path + "?" + uri.query if uri.query
  @log.debug("DELETE: #{path} (as '#{@user.name}')")
  req = Net::HTTP::Delete.new(path)
  res = sendRequest(uri, req)
  dump_response(res)
  return res
end

#delete_node(path) ⇒ Object



325
326
327
# File 'lib/nakamura.rb', line 325

def delete_node(path)
  result = execute_post(url_for(path), ":operation" => "delete")
end

#delete_node_acl_entries(path, principal) ⇒ Object



396
397
398
399
400
# File 'lib/nakamura.rb', line 396

def delete_node_acl_entries(path, principal)
  res = execute_post(url_for("#{path}.deleteAce.html"), {
        ":applyTo" => principal
  })
end

#do_loginObject



299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/nakamura.rb', line 299

def () 
  path = url_for("/system/sling/formlogin")
  uri = URI.parse(path)
  req = Net::HTTP::Post.new(uri.path)
  req.set_form_data({ "sakaiauth:un" => @user.name, "sakaiauth:pw" => @user.password, "sakaiauth:login" => 1 })
  res = createHttp(uri).start{ |http| http.request(req) }
  if ( res.code == "200" ) 
    save_cookies(res)
    @log.info("Login Ok, cookie was  {#@cookies}")
    @loggedin = true
  else
    @log.info("Failed to perform login, got "+res.code+" response code")
  end
end

#dump_response(response) ⇒ Object



103
104
105
106
# File 'lib/nakamura.rb', line 103

def dump_response(response)
  @log.info "Response: #{response.code} #{response.message}"
  @log.debug "#{response.body}"
end

#execute_file_post(path, fieldname, filename, data, content_type) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/nakamura.rb', line 141

def execute_file_post(path, fieldname, filename, data, content_type)
  uri = URI.parse(path)
  fileTypeHint = "Content-Disposition: form-data; name=\"*@TypeHint\"\r\n\r\n" +
                 "nt:file\r\n"

  params = [fileTypeHint,file_to_multipart(fieldname, filename, content_type, data)]
  boundary = '349832898984244898448024464570528145'
  post_body = params.collect {|p| '--' + boundary + "\r\n" + p}.join('') + "--" + boundary + "--\r\n"
  req = Net::HTTP::Post.new(uri.path)
  req.set_content_type("multipart/form-data", {"boundary" => boundary})
  req.body = post_body
  res = sendRequest(uri, req)
  dump_response(res)
  return res
end

#execute_get(path, query_params = nil) ⇒ Object



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
# File 'lib/nakamura.rb', line 236

def execute_get(path, query_params=nil)
  if (query_params != nil)
    param_string = query_params.collect { |k,v|
      val = case v
        when String then
        v
        when Numeric then
        v.to_s
      else
        v.to_json
      end
      CGI.escape(k) + "=" + CGI.escape(val)
    }.join("&")
    path = "#{path}?#{param_string}" 
  end
  @log.debug "URL: #{path}"
  uri = URI.parse(path)
  path = uri.path
  path = path + "?" + uri.query if uri.query
  @log.debug("GET: #{path} (as '#{@user.name}')")
  req = Net::HTTP::Get.new(path)
  res = sendRequest(uri, req)
  res = followRedirects(res)
  dump_response(res)
  return res
end

#execute_post(path, post_params = {}) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/nakamura.rb', line 222

def execute_post(path, post_params={})
  # We always post with utf-8
  if ( post_params["_charset_"] == nil)
    post_params["_charset_"] = "utf-8"
  end
  @log.debug("POST: #{path} (as '#{@user.name}')\n\tparams: #{post_params.dump}")
  uri = URI.parse(path)
  req = Net::HTTP::Post.new(uri.path)
  req.set_form_data(post_params)
  res = sendRequest(uri, req)
  dump_response(res)
  return res
end

#execute_put_file(path, data) ⇒ Object



211
212
213
214
215
216
217
218
219
220
# File 'lib/nakamura.rb', line 211

def execute_put_file(path, data)
  @log.debug "URL: #{path}"
  @log.debug("PUTFILE: #{path} (as '#{@user.name}')")
  uri = URI.parse(path)
  req = Net::HTTP::Put.new(uri.path)
  req.body = data
  res = sendRequest(uri, req)
  dump_response(res)
  return res
end

#file_to_multipart(key, filename, mime_type, content) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/nakamura.rb', line 124

def file_to_multipart(key,filename,mime_type,content)
  if ( filename != nil ) 
    return "Content-Disposition: form-data; name=\"*\"; filename=\"#{filename}\"\r\n" +
         "Content-Transfer-Encoding: binary\r\n" +
         "Content-Type: #{mime_type}\r\n" + 
         "\r\n" + 
         "#{content}\r\n"
  else 
    return "Content-Disposition: form-data; name=\"jcr:content\"\r\n" +
         "Content-Transfer-Encoding: binary\r\n" +
         "Content-Type: #{mime_type}\r\n" + 
         "\r\n" + 
         "#{content}\r\n"
  end

end

#followRedirects(res) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
# File 'lib/nakamura.rb', line 263

def followRedirects(res)
    lastlocation = ''
    while (res.header['location'] && res.header['location'] != lastlocation)
        lastlocation = res.header['location']
        uri = URI.parse(res.header['location'])
        @log.info("Redirecting to #{uri}")
        req = Net::HTTP::Get.new(uri.request_uri())
        res = sendRequest(uri, req)
    end
    return res
end

#get_node_acl(path) ⇒ Object



367
368
369
# File 'lib/nakamura.rb', line 367

def get_node_acl(path)
  return JSON.parse(get_node_acl_json(path))
end

#get_node_acl_json(path) ⇒ Object



359
360
361
# File 'lib/nakamura.rb', line 359

def get_node_acl_json(path)
  return execute_get(url_for("#{path}.acl.json")).body
end

#get_node_props(path) ⇒ Object



351
352
353
# File 'lib/nakamura.rb', line 351

def get_node_props(path)
  return JSON.parse(get_node_props_json(path))
end

#get_node_props_json(path) ⇒ Object



341
342
343
344
345
346
347
348
349
# File 'lib/nakamura.rb', line 341

def get_node_props_json(path)
  @log.debug "Getting props for path: #{path}"
  result = execute_get(url_for("#{path}.json"))
  if ( result.code == "200" ) 
    return result.body
  end 
  @log.info("Failed to get properties for "+path+" cause "+result.code+"\n"+result.body)
  return "{}"
end

#get_node_ruleacl(path) ⇒ Object



371
372
373
# File 'lib/nakamura.rb', line 371

def get_node_ruleacl(path)
  return JSON.parse(get_node_ruleacl_json(path))
end

#get_node_ruleacl_json(path) ⇒ Object



363
364
365
# File 'lib/nakamura.rb', line 363

def get_node_ruleacl_json(path)
  return execute_get(url_for("#{path}.ruleacl.json")).body
end

#get_userObject



337
338
339
# File 'lib/nakamura.rb', line 337

def get_user()
  return @user
end

#save_cookies(res) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/nakamura.rb', line 280

def save_cookies(res)
  if ( res["Set-Cookie"] ) 
    setcookie = res.get_fields('Set-Cookie')
    @log.debug("Set-Cookie header #{setcookie} ")
    setcookie.each do |cookieitem|
      cookie = cookieitem.split(/;/)[0]
      cookiename = cookie.split(/\=/)[0]
      value = cookie.split(/\=/)[1]
      cookievalue = "#{cookiename}=#{value}"
      if ( @cookies[cookiename] != cookievalue ) 
         @cookies[cookiename] = cookievalue
         @log.info("New Cookie Value #{@cookies.values * "' "} ")
      else 
        @log.debug("No Change to Cookie #{@cookies}")
      end
    end
  end
end

#save_node(path) ⇒ Object



407
408
409
410
411
412
413
# File 'lib/nakamura.rb', line 407

def save_node(path)
  res = execute_post(url_for("#{path}.save.json"), {})
  if (res.code == "200")
    return JSON.parse(res.body)["versionName"]
  end
  return nil
end

#sendRequest(uri, req) ⇒ Object



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

def sendRequest(uri, req)
  # Not all browsers take port number into account when setting cookies.
  isSlingReq = uri.host && (uri.host == @serveruri.host)
  if (isSlingReq)
    if ( @trustedauth )
      if ( ! @loggedin )
          ()
      end
    else
      @user.do_request_auth(req)
    end
    set_cookies(req)
  else
    @log.info("#{uri.host} does not match expected #{@serveruri.host}. Not sending state.")
  end
  res = createHttp(uri).start { |http| http.request(req ) }
  save_cookies(res) if (isSlingReq)
  return res
end

#set_cookies(req) ⇒ Object



275
276
277
278
# File 'lib/nakamura.rb', line 275

def set_cookies(req)
   req["Cookie"] = @cookies.values * ", "
   @log.debug("Cookie is #{req["Cookie"]}")
end

#set_node_acl_entries(path, principal, privs) ⇒ Object



375
376
377
378
379
380
381
382
383
# File 'lib/nakamura.rb', line 375

def set_node_acl_entries(path, principal, privs)
@log.info "Setting node acl for: #{principal} to #{privs.dump}"
res = execute_post(url_for("#{path}.modifyAce.html"), 
{ "principalId" => principal.name }.update(
                                           privs.keys.inject(Hash.new) do |n,k| 
  n.update("privilege@#{k}" => privs[k])
  end))
  return res
end

#set_node_acl_rule_entries(path, principal, privs, props) ⇒ Object



385
386
387
388
389
390
391
392
393
394
# File 'lib/nakamura.rb', line 385

def set_node_acl_rule_entries(path, principal, privs, props)
  @log.info "Setting node acl for: #{principal} to #{privs.dump}"
  props["principalId"] = principal.name
  res = execute_post(url_for("#{path}.modifyRuleAce.html"), 
    props.update(
      privs.keys.inject(Hash.new) do |n,k| 
        n.update("privilege@#{k}" => privs[k])
      end))
  return res
end

#switch_user(user) ⇒ Object



108
109
110
111
112
113
114
115
# File 'lib/nakamura.rb', line 108

def switch_user(user)
  @log.info "Switched user to #{user}"
  @cookies = Hash.new()
  @user = user
  if ( @trustedauth ) 
     @loggedin = false
  end
end

#text_to_multipart(key, value) ⇒ Object



118
119
120
121
122
# File 'lib/nakamura.rb', line 118

def text_to_multipart(key,value)
  return "Content-Disposition: form-data; name=\"#{CGI::escape(key)}\"\r\n" + 
         "\r\n" + 
         "#{value}\r\n"
end

#update_node_props(path, props) ⇒ Object



355
356
357
# File 'lib/nakamura.rb', line 355

def update_node_props(path, props)
  return execute_post(url_for(path), props)
end

#update_properties(principal, props) ⇒ Object



321
322
323
# File 'lib/nakamura.rb', line 321

def update_properties(principal, props)
  principal.update_properties(self, props)
end

#url_for(path) ⇒ Object



314
315
316
317
318
319
# File 'lib/nakamura.rb', line 314

def url_for(path)
  if (path.slice(0,1) == '/')
    path = path[1..-1]
  end
  return "#{@server}#{path}"
end

#version(path, version, extension) ⇒ Object



419
420
421
# File 'lib/nakamura.rb', line 419

def version(path, version, extension)
  return execute_get(url_for("#{path}.version.,#{version},.#{extension}"))
end

#versions(path) ⇒ Object



415
416
417
# File 'lib/nakamura.rb', line 415

def versions(path)
  return get_node_props("#{path}.versions")["versions"].keys
end