class Usd

Constants

CN

Attributes

access_key[R]
base_url[R]
debug[RW]
expiration_date[R]
user[R]

Public Class Methods

loadcon() click to toggle source
# File lib/usd.rb, line 144
def self.loadcon
  # load from env
  Usd.new(ENV["usduser"],ENV["usdpass"],ENV["usdurl"])
end
new(user, password="", base_url = "http://localhost:8050", hash={}) click to toggle source
# File lib/usd.rb, line 89
def initialize(user, password="", base_url = "http://localhost:8050", hash={})
  hash = {:expiration_date => 0, :access_key => "",:save_access_key => true }.update hash
  make_new = true
  @base_url = base_url
  @user = user
  @debug = false
  remfile = "#{ENV["HOME"]}/.usd_#{user}"
  if File.exist?(remfile) and hash[:save_access_key]
    tt = YAML.load(File.open(remfile,"r"))
    if (tt.expiration_date - Time.now.to_i ) > 900 and tt.base_url == base_url
      @access_key = tt.access_key
      @expiration_date = tt.expiration_date
      make_new = false
      puts "cache key loaded..." if @debug
    end
  end
  if hash[:save_access_key] and hash[:access_key].length > 0
    if (hash[:expiration_date] - Time.now.to_i ) > 900
      @access_key = hash[:access_key]
      @expiration_date = hash[:expiration_date]
      make_new = false
      puts "use existing access_key ..." if @debug
    end
  end
  if make_new
    encoded=Base64.encode64( "#{@user}:#{password}")
    begin
      response = RestClient::Request.execute(method: :post, url: "#{@base_url}/caisd-rest/rest_access?_type=json",
        payload: '<rest_access/>',
        headers: {
          'content-type' => "application/xml",
          "accept" => "application/json",
          "authorization" =>  "Basic #{encoded}",
          "cache-control" => "no-cache"
        },
        log: Logger.new("/dev/null")
      )
      authData=JSON.parse(response.body)
      if authData['rest_access']['access_key'] > 0
        @access_key = authData['rest_access']['access_key']
        @expiration_date = authData['rest_access']['expiration_date']
        if hash[:save_access_key]
          f=File.open(remfile,"w")
          f.puts self.to_yaml
          f.close
        end
      else
        "keinen Accesskey erhalten. \nresponse.body:\n#{response.body}"
      end
    rescue RestClient::ExceptionWithResponse => e
      e.response
    end
  end
end

Public Instance Methods

create(hash = {}) click to toggle source
# File lib/usd.rb, line 190
def create(hash = {})
  hash = {:type => "ruby", :data => {}}.update hash
  case hash[:type]
  when "ruby"
    data = hash[:data]
  when "json"
    data = JSON.parse(hash[:data])
  when "yaml"
    data = YAML.load(hash[:data])
  else
    "Error: 'data[:type]': '#{hash[:data]}' not found!"
  end
  puts "create - data: #{JSON.pretty_generate(data)}" if @debug
  object = data.keys[0]
  uri = "/caisd-rest/#{object}"
  request("/caisd-rest/#{object}",{:method => "post", :json => data.to_json})
end
header(hash={}) click to toggle source
# File lib/usd.rb, line 149
def header(hash={})
  hash = {
    'x-accesskey' => @access_key,
    'accept' => "application/json",
    "Content-Type" =>"application/json; charset=UTF-8",
    'X-Obj-Attrs' => "*",
    'cache-control'=> "no-cache"
  }.update hash
  hash
end
request(uri, hash={}) click to toggle source
# File lib/usd.rb, line 160
def request(uri, hash={})
  RestClient.log = STDOUT if @debug
  hash = {:method => "get", :header => header(), :unchanged => false, :json => "", :base_url => @base_url}.update hash
  puts "request - hash: #{JSON.pretty_generate(hash)}" if @debug
  parser = URI::RFC2396_Parser.new
  if (uri !~ /^http/)
    url = parser.escape("#{hash[:base_url]}#{uri}")
  else
    url = parser.escape(uri)
  end
  begin
    if hash[:method] == "get"
      response = RestClient::Request.execute(method: hash[:method], url: url, headers: hash[:header])
    elsif   hash[:method] == "post"
      response = RestClient.post(url, hash[:json], hash[:header])
    elsif   hash[:method] == "put"
      response = RestClient.put(url, hash[:json], hash[:header])
    elsif   hash[:method] =~ /delete/i
      response = RestClient.delete(url, hash[:header])
    end
    if hash[:unchanged]
      response.body
    else
      JSON.parse(response.body)
    end
  rescue RestClient::ExceptionWithResponse => e
    e
  end
end
set_param(params_hash,attribute_name,default) click to toggle source
# File lib/usd.rb, line 243
def set_param(params_hash,attribute_name,default)
  params_hash[attribute_name]?params_hash[attribute_name]:default
end
set_url_parm(params_hash,attribute_name,default) click to toggle source
# File lib/usd.rb, line 231
def set_url_parm(params_hash,attribute_name,default)
  # disable case
  params_hash.keys.each do |k|
    if k =~ /^#{attribute_name}$/i
      v = params_hash[k]
      params_hash.delete(k)
      params_hash[attribute_name] = v
    end
  end
  "#{attribute_name}=#{params_hash[attribute_name]?params_hash[attribute_name]:default}"
end
update(hash = {}) click to toggle source
# File lib/usd.rb, line 208
def update(hash = {})
  hash = {:type => "ruby", :data => {}}.update hash
  case hash[:type]
  when "ruby"
    data = hash[:data]
  when "json"
    data = JSON.parse(hash[:data])
  when "yaml"
    data = YAML.load(hash[:data])
  else
    "Error: 'data[:type]': '#{hash[:data]}' not found!"
  end
  puts "update - data: #{JSON.pretty_generate(data)}" if @debug
  object = data.keys[0]
  if  data[object].has_key?("@id")
    request("/caisd-rest/#{object}/#{data[object]["@id"]}",{:method => "put", :json => data.to_json, :header => header({'X-Obj-Attrs' => 'COMMON_NAME'})})
  elsif data[object].has_key?("@COMMON_NAME")
    request("/caisd-rest/#{object}/COMMON_NAME-#{data[object]["@COMMON_NAME"]}",{:method => "put", :json => data.to_json, :header => header({'X-Obj-Attrs' => 'COMMON_NAME'})})
  else
    puts "specify @COMMON_NAME or @id at least."
  end
end
upload_attachment(file, baseurl = @base_url, ak = @access_key) click to toggle source
# File lib/usd.rb, line 284
def upload_attachment(file, baseurl = @base_url, ak = @access_key)
  baseurl =~ /^([^:]+):/
  server = $1
  filename = File.basename(file)
  #filename_escaped = URI.escape(filename)
  filename_escaped = filename.gsub(/[^0-9A-Za-z.\-]/, '_')
  uri = "/caisd-rest/attmnt?repositoryId=1002&serverName=#{server}&mimeType=Text&description=#{filename_escaped}"
  url = URI("#{baseurl}#{uri}")
  http = Net::HTTP.new(url.host, url.port);
  request = Net::HTTP::Post.new(url)
  request["X-AccessKey"] = ak
  request["Content-Type"] = "multipart/form-data; BOUNDARY=*****MessageBoundary*****"
  request["accept"] = "application/json"
  request["Cache-Control"] = "no-cache"
  fileObj = File.open(file, "rb")
  fileContent = fileObj.read
  fileObj.close
  request.body = "--*****MessageBoundary*****\r\n \r\nContent-Disposition: form-data; name=\"payload\" \r\nContent-Type: application/xml; CHARACTERSET=UTF-8 \r\n\r\n \r\n<attmnt> \r\n<repository id=\"1002\"></repository> \r\n<orig_file_name>#{filename_escaped}</orig_file_name> \r\n<attmnt_name>#{filename_escaped}</attmnt_name> \r\n<description>Uploaded with rusdc from rubygem usd</description> \r\n</attmnt> \r\n\r\n \r\n--*****MessageBoundary*****\r\n \r\nContent-Disposition: form-data; name=\"#{filename_escaped}\"; filename=\"#{filename_escaped}\" \r\nContent-Type: application/octet-stream \r\nContent-Transfer-Encoding: base64\r\n\r\n#{Base64.encode64(fileContent)}\r\n\r\n \r\n--*****MessageBoundary*****--\r\n"
  response = http.request(request)
  response.read_body
end