Class: Usd

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

Constant Summary collapse

CN =
{
  "chg" => "chg_ref_num",
  "cnt" => "combo_name",
  "arcpur_rule" => "name",
  "ca_tou" => "name",
  "cost_cntr" => "name",
  "country" => "name",
  "dept" => "name",
  "gl_code" => "name",
  "job_func" => "name",
  "loc" => "name",
  "nr" => "name",
  "opsys" => "name",
  "org" => "name",
  "tab" => "name",
  "auto_close" => "sym",
  "aty" => "sym",
  "act_type_assoc" => "sym",
  "ca_cmpny" => "sym",
  "closure_code" => "sym",
  "cmth" => "sym",
  "symptom_code" => "sym",
  "state" => "sym",
  "crt" => "sym",
  "ctab" => "sym",
  "ctp" => "sym",
  "dcon_typ" => "sym",
  "dlgsrvr" => "sym",
  "dmn" => "sym",
  "doc_rep" => "sym",
  "fmgrp" => "sym",
  "ical_alarm" => "sym",
  "ical_event_template" => "sym",
  "imp" => "sym",
  "intfc" => "sym",
  "kwrd" => "sym",
  "mfrmod" => "sym",
  "mgsstat" => "sym",
  "nrf" => "sym",
  "options" => "sym",
  "outage_type" => "sym",
  "perscnt" => "sym",
  "position" => "sym",
  "pr_trans" => "sym",
  "prod" => "sym",
  "quick_tpl_types" => "sym",
  "rc" => "sym",
  "resocode" => "sym",
  "resomethod" => "sym",
  "response" => "sym",
  "rrf" => "sym",
  "rss" => "sym",
  "seq" => "sym",
  "sev" => "sym",
  "site" => "sym",
  "slatpl" => "sym",
  "special_handling" => "sym",
  "svc_contract" => "sym",
  "typecnt" => "sym",
  "tz" => "sym",
  "tspan" => "sym",
  "transition_type" => "sym",
  "urg" => "sym",
  "vpt" => "sym",
  "wrkshft" => "sym",
  "cr" => "ref_num",
  "in" => "ref_num",
  "pr" => "ref_num"
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Usd.



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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/usd.rb', line 88

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"
  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(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(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

Instance Attribute Details

#access_keyObject (readonly)

Returns the value of attribute access_key.



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

def access_key
  @access_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



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

def base_url
  @base_url
end

#debugObject

Returns the value of attribute debug.



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

def debug
  @debug
end

#expiration_dateObject (readonly)

Returns the value of attribute expiration_date.



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

def expiration_date
  @expiration_date
end

#userObject (readonly)

Returns the value of attribute user.



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

def user
  @user
end

Class Method Details

.loadconObject



143
144
145
146
# File 'lib/usd.rb', line 143

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

Instance Method Details

#create(hash = {}) ⇒ Object



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

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



148
149
150
151
152
153
154
155
156
157
# File 'lib/usd.rb', line 148

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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/usd.rb', line 159

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



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/usd.rb', line 245

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","")
  # if wc contains no sql-compare operater, it will be changed to "COMMON_NAME like '%<wc-before>%'"
  wc = attr.pop
  wc.gsub!(/^WC=/,'')
  if ([" like ","<",">","="," is "].find {|e| wc =~ /#{e}/}).nil?
    wc = "#{CN[object]} like '%#{wc}%'"
  end
  attr.push "WC=#{wc}"
  # puts attr.jp # debug
  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



241
242
243
# File 'lib/usd.rb', line 241

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



229
230
231
232
233
234
235
236
237
238
239
# File 'lib/usd.rb', line 229

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



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/usd.rb', line 206

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