Class: Usd

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user, password = "", base_url = "http://localhost:8050", hash = {}) ⇒ Usd



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
63
64
65
66
67
68
69
70
# File 'lib/usd.rb', line 18

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
  if File.exist?(".usd") and hash[:save_access_key]
    tt = YAML.load(File.open(".usd","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(STDOUT)
      )
      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(".usd","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

Instance Attribute Details

#access_keyObject (readonly)

Returns the value of attribute access_key.



15
16
17
# File 'lib/usd.rb', line 15

def access_key
  @access_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



15
16
17
# File 'lib/usd.rb', line 15

def base_url
  @base_url
end

#debugObject

Returns the value of attribute debug.



15
16
17
# File 'lib/usd.rb', line 15

def debug
  @debug
end

#expiration_dateObject (readonly)

Returns the value of attribute expiration_date.



15
16
17
# File 'lib/usd.rb', line 15

def expiration_date
  @expiration_date
end

#userObject (readonly)

Returns the value of attribute user.



15
16
17
# File 'lib/usd.rb', line 15

def user
  @user
end

Class Method Details

.loadconObject



72
73
74
75
# File 'lib/usd.rb', line 72

def self.loadcon
  # load from env
  Usd.new(ENV["usduser"],ENV["usdpass"],ENV["usdurl"])
end

Instance Method Details

#create(hash = {}) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/usd.rb', line 117

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 = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
86
# File 'lib/usd.rb', line 77

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 = {}) ⇒ Object



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

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
  if (uri !~ /^http/)
    url = URI.escape("#{hash[:base_url]}#{uri}")
  else
    url = URI.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

#search(object, params = {}) ⇒ Object



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

def search(object,params={})
  attr=[]
  attr.push set_url_parm(params,"SORT","id DESC")
  attr.push set_url_parm(params,"start","1")
  attr.push set_url_parm(params,"size","50")
  attr.push set_url_parm(params,"WC","")
  fields = set_param(params,"fields","COMMON_NAME,id")
  query_string=attr.join("&")
  res_rdata = request("/caisd-rest/#{object}?#{query_string}",{:method => "get", :header => header({'X-Obj-Attrs' => fields})})
  puts res_rdata if @debug
  count = res_rdata["collection_#{object}"]["@COUNT"].to_i
  start = res_rdata["collection_#{object}"]["@START"].to_i
  total_count = res_rdata["collection_#{object}"]["@TOTAL_COUNT"].to_i
  # turn throught the pages
  if count == 1
    [res_rdata["collection_#{object}"][object]]
  elsif count == 0
    []
  else
    retArray = res_rdata["collection_#{object}"][object]
    if total_count > (count + start - 1)
      new_params = {"start" => (start + 50)}
      params = params.update new_params
      retArray += search(object,params)
    end
    retArray
  end
end

#set_param(params_hash, attribute_name, default) ⇒ Object



165
166
167
# File 'lib/usd.rb', line 165

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) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/usd.rb', line 153

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 = {}) ⇒ Object



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

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]
  cn = data[object]["@COMMON_NAME"]
  request("/caisd-rest/#{object}/COMMON_NAME-#{cn}",{:method => "put", :json => data.to_json, :header => header({'X-Obj-Attrs' => 'COMMON_NAME'})})
end