Module: JSONModel

Defined in:
common/jsonmodel_utils.rb,
common/jsonmodel.rb,
common/jsonmodel_client.rb
more...

Overview

Contains methods to manipulate JSON representations

Defined Under Namespace

Modules: Client, HTTP, Notification, Validations Classes: ModelNotFound, ValidationException

Constant Summary collapse

REFERENCE_KEY_REGEX =

Parse a URI reference like /repositories/123/archival_objects/500 into

It turns out that when resolving thousands of records, the miss-rate of trying every model every time can be quite significant. Trying to be a bit cleverer…

/(\/[0-9]+)/
@@models =
java.util.concurrent.ConcurrentHashMap.new
@@custom_validations =
java.util.concurrent.ConcurrentHashMap.new
@@strict_mode =
false
@@model_lookup_cache =
Atomic.new({})
@@error_handlers =
[]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_error_handler(&block) ⇒ Object

[View source]

53
54
55
# File 'common/jsonmodel_client.rb', line 53

def self.add_error_handler(&block)
  @@error_handlers << block
end

.all(uri, type_descriptor) ⇒ Object

Grab an array of JSON objects from ‘uri’ and use the ‘type_descriptor’ property of each object to cast it into a JSONModel.

[View source]

24
25
26
27
28
# File 'common/jsonmodel_client.rb', line 24

def self.all(uri, type_descriptor)
  JSONModel::HTTP.get_json(uri).map do |obj|
    JSONModel(obj[type_descriptor.to_s]).new(obj)
  end
end

.allow_unmapped_enum_value(val, magic_value = 'other_unmapped') ⇒ Object

[View source]

153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'common/jsonmodel.rb', line 153

def self.allow_unmapped_enum_value(val, magic_value = 'other_unmapped')
  if val.is_a? Array
    val.each { |elt| allow_unmapped_enum_value(elt) }
  elsif val.is_a? Hash
    val.each do |k, v|
      if k == 'enum'
        v << magic_value
      else
        allow_unmapped_enum_value(v)
      end
    end
  end
end

.backend_urlObject

[View source]

42
43
44
45
46
47
48
# File 'common/jsonmodel_client.rb', line 42

def self.backend_url
  if Module.const_defined?(:BACKEND_SERVICE_URL)
    BACKEND_SERVICE_URL
  else
    init_args[:url]
  end
end

.check_valid_refs(properties) ⇒ Object

[View source]

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'common/jsonmodel.rb', line 252

def self.check_valid_refs(properties)
  if properties.is_a?(Hash)
    properties.each do |key, value|
      if key == 'ref'
        unless value.is_a?(Hash)
          raise "ref value should be an object.  Got type: #{value.class}"
        end
      else
        check_valid_refs(value)
      end
    end
  elsif properties.is_a?(Array)
    properties.each do |elt|
      check_valid_refs(elt)
    end
  else
    # Scalar...
  end
end

.client_mode?Boolean

Returns:

  • (Boolean)
[View source]

349
350
351
# File 'common/jsonmodel.rb', line 349

def self.client_mode?
  @@init_args[:client_mode]
end

.custom_validationsObject

[View source]

21
22
23
# File 'common/jsonmodel.rb', line 21

def self.custom_validations
  @@custom_validations
end

.destroy_model(type) ⇒ Object

[View source]

129
130
131
# File 'common/jsonmodel.rb', line 129

def self.destroy_model(type)
  @@models.delete(type.to_s)
end

.enum_default_value(name) ⇒ Object

[View source]

344
345
346
# File 'common/jsonmodel.rb', line 344

def self.enum_default_value(name)
  @@init_args[:enum_source].default_value_for(name)
end

.enum_values(name) ⇒ Object

[View source]

339
340
341
# File 'common/jsonmodel.rb', line 339

def self.enum_values(name)
  @@init_args[:enum_source].values_for(name)
end

.handle_error(err) ⇒ Object

[View source]

57
58
59
60
61
# File 'common/jsonmodel_client.rb', line 57

def self.handle_error(err)
  @@error_handlers.each do |handler|
    handler.call(err)
  end
end

.init(opts = {}) ⇒ Object

[View source]

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'common/jsonmodel.rb', line 272

def self.init(opts = {})
  @@init_args ||= nil

  # Skip initialisation if this model has already been loaded.
  if @@init_args
    return true
  end

  if opts.has_key?(:strict_mode)
    @@strict_mode = true
  end

  @@init_args = opts

  if !opts.has_key?(:enum_source)
    if opts[:client_mode]
      require_relative 'jsonmodel_client'
      opts[:enum_source] = JSONModel::Client::EnumSource.new
    else
      raise "Required JSONModel.init arg :enum_source was missing"
    end
  end

  # Load all JSON schemas from the schemas subdirectory
  # Create a model class for each one.
  Dir.glob(File.join(File.dirname(__FILE__),
                     "schemas",
                     "*.rb")).sort.each do |schema|
    schema_name = File.basename(schema, ".rb")
    load_schema(schema_name)
  end

  require_relative "validations"

  # For dynamic enums, automatically slot in the 'other_unmapped' string as an allowable value
  if @@init_args[:allow_other_unmapped]
    enum_wrapper = Struct.new(:enum_source).new(@@init_args[:enum_source])

    def enum_wrapper.valid?(name, value)
      value == 'other_unmapped' || enum_source.valid?(name, value)
    end

    def enum_wrapper.editable?(name)
      enum_source.editable?(name)
    end

    def enum_wrapper.values_for(name)
      enum_source.values_for(name) + ['other_unmapped']
    end

    def enum_wrapper.default_value_for(name)
      enum_source.default_value_for(name)
    end

    @@init_args[:enum_source] = enum_wrapper
  end

  true

rescue
  # If anything went wrong we're not initialised.
  @@init_args = nil

  raise $!
end

.JSONModel(source) ⇒ Object

[View source]

62
63
64
65
66
67
68
# File 'common/jsonmodel.rb', line 62

def self.JSONModel(source)
  if !@@models.has_key?(source.to_s)
    load_schema(source.to_s)
  end

  @@models[source.to_s] or raise ModelNotFound.new("JSONModel not found for #{source}")
end

.load_schema(schema_name) ⇒ Object

[View source]

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
216
217
218
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
# File 'common/jsonmodel.rb', line 168

def self.load_schema(schema_name)
  if not @@models[schema_name]
    old_verbose = $VERBOSE
    $VERBOSE = nil
    src = schema_src(schema_name)

    return if !src

    entry = eval(src)
    $VERBOSE = old_verbose

    parent = entry[:schema]["parent"]
    if parent
      load_schema(parent)

      base = @@models[parent].schema["properties"].clone
      properties = ASUtils.deep_merge(base, entry[:schema]["properties"])

      # Maybe we'll eventually want the version of a schema to be
      # automatically set to max(my_version, parent_version), but for now...
      if entry[:schema]["version"] < @@models[parent].schema_version
        raise ("Can't inherit from a JSON schema whose version is newer than ours " +
               "(our (#{schema_name}) version: #{entry[:schema]['version']}; " +
               "parent (#{parent}) version: #{@@models[parent].schema_version})")
      end

      entry[:schema]["properties"] = properties
    end

    # All records have a lock_version property that we use for optimistic concurrency control.
    entry[:schema]["properties"]["lock_version"] = {"type" => ["integer", "string"], "required" => false}

    # All records must indicate their model type
    entry[:schema]["properties"]["jsonmodel_type"] = {"type" => "string", "ifmissing" => "error"}

    # All records have audit fields
    entry[:schema]["properties"]["created_by"] = {"type" => "string", "readonly" => true}
    entry[:schema]["properties"]["last_modified_by"] = {"type" => "string", "readonly" => true}
    entry[:schema]["properties"]["user_mtime"] = {"type" => "date-time", "readonly" => true}
    entry[:schema]["properties"]["system_mtime"] = {"type" => "date-time", "readonly" => true}
    entry[:schema]["properties"]["create_time"] = {"type" => "date-time", "readonly" => true}

    # Records may include a reference to the repository that contains them
    entry[:schema]["properties"]["repository"] ||= {
      "type" => "object",
      "subtype" => "ref",
      "readonly" => "true",
      "properties" => {
        "ref" => {
          "type" => "JSONModel(:repository) uri",
          "ifmissing" => "error",
          "readonly" => "true"
        },
        "_resolved" => {
          "type" => "object",
          "readonly" => "true"
        }
      }
    }


    if @@init_args[:allow_other_unmapped]
      allow_unmapped_enum_value(entry[:schema]['properties'])
    end

    ASUtils.find_local_directories("schemas/#{schema_name}_ext.rb").
            select {|path| File.exist?(path)}.
            each do |schema_extension|
      entry[:schema]['properties'] = ASUtils.deep_merge(entry[:schema]['properties'],
                                                        eval(File.open(schema_extension).read))
    end

    validate_schema(entry[:schema])

    self.create_model_for(schema_name, entry[:schema])
  end
end

.modelsObject

[View source]

82
83
84
# File 'common/jsonmodel.rb', line 82

def self.models
  @@models
end

.parse_jsonmodel_ref(ref) ⇒ Object

[View source]

354
355
356
357
358
359
360
# File 'common/jsonmodel.rb', line 354

def self.parse_jsonmodel_ref(ref)
  if ref.is_a? String and ref =~ /JSONModel\(:([a-zA-Z_\-]+)\) (.*)/
    [$1.intern, $2]
  else
    nil
  end
end

.parse_reference(reference, opts = {}) ⇒ Object

[View source]

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'common/jsonmodel.rb', line 106

def self.parse_reference(reference, opts = {})
  return nil if reference.nil?
  cache_key = reference.gsub(REFERENCE_KEY_REGEX, '')

  # Try our cache
  (type, model) = @@model_lookup_cache.value[cache_key]
  if type && (id = model.id_for(reference, opts, true))
    return {:id => id, :type => type, :repository => repository_for(reference)}
  end

  # Do the slow search
  @@models.each do |type, model|
    id = model.id_for(reference, opts, true)
    if id
      @@model_lookup_cache.update {|v| v.merge({cache_key => [type, model]})}
      return {:id => id, :type => type, :repository => repository_for(reference)}
    end
  end

  nil
end

.repositoryObject

The currently selected repository (if any)

[View source]

17
18
19
# File 'common/jsonmodel_client.rb', line 17

def self.repository
  Thread.current[:selected_repo_id]
end

.repository_for(reference) ⇒ Object

[View source]

87
88
89
90
91
92
93
# File 'common/jsonmodel.rb', line 87

def self.repository_for(reference)
  if reference =~ /^(\/repositories\/[0-9]+)\//
    return $1
  else
    return nil
  end
end

.schema_src(schema_name) ⇒ Object

[View source]

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

def self.schema_src(schema_name)
  if schema_name.to_s !~ /\A[0-9A-Za-z_-]+\z/
    raise "Invalid schema name: #{schema_name}"
  end

  [*ASUtils.find_local_directories('schemas'),
   File.join(File.dirname(__FILE__), "schemas")].each do |dir|

    schema = File.join(dir, "#{schema_name}.rb")

    if File.exist?(schema)
      return File.open(schema).read
    end
  end

  nil
end

.set_publish_flags!(jsonmodel) ⇒ Object

it’s possible for a node to have publish = true and at the same time have an ancestor with publish = false. this method traverses a JSONModel and sets publish = false for any node that has an ancestor with publish = false.

[View source]

7
8
9
10
11
12
13
14
# File 'common/jsonmodel_utils.rb', line 7

def self.set_publish_flags!(jsonmodel)
  # if the parameter is not a hash, then it's a JSONModel object and the data we want is in @data.
  if (jsonmodel.is_a?(Hash))
    traverse!(jsonmodel)
  else
    traverse!(jsonmodel.instance_variable_get(:@data))
  end
end

.set_repository(id) ⇒ Object

Set the repository that subsequent operations will apply to.

[View source]

11
12
13
# File 'common/jsonmodel_client.rb', line 11

def self.set_repository(id)
  Thread.current[:selected_repo_id] = id
end

.strict_mode(val) ⇒ Object

[View source]

25
26
27
# File 'common/jsonmodel.rb', line 25

def self.strict_mode(val)
  @@strict_mode = val
end

.strict_mode?Boolean

Returns:

  • (Boolean)
[View source]

30
31
32
# File 'common/jsonmodel.rb', line 30

def self.strict_mode?
  @@strict_mode
end

.validate_schema(schema) ⇒ Object

Look for any obvious errors in our schema

[View source]

247
248
249
250
# File 'common/jsonmodel.rb', line 247

def self.validate_schema(schema)
  check_valid_refs(schema['properties'])
  schema
end

.with_repository(id) ⇒ Object

[View source]

31
32
33
34
35
36
37
38
39
# File 'common/jsonmodel_client.rb', line 31

def self.with_repository(id)
  old_repo = Thread.current[:selected_repo_id]
  begin
    self.set_repository(id)
    yield
  ensure
    self.set_repository(old_repo)
  end
end

Instance Method Details

#JSONModel(source) ⇒ Object

[View source]

71
72
73
# File 'common/jsonmodel.rb', line 71

def JSONModel(source)
  JSONModel.JSONModel(source)
end

#modelsObject

Yield all known JSONModel classes

[View source]

77
78
79
# File 'common/jsonmodel.rb', line 77

def models
  @@models
end