Class: Java::OrgMitre::ApiHelper

Inherits:
Object
  • Object
show all
Includes:
StixRuby::Marshall
Defined in:
lib/ruby_stix/api/api_helper.rb

Constant Summary collapse

BLACKLIST =
["getClass", "hashCode", "equals", "toString", "notify", "notifyAll", "wait"]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from StixRuby::Marshall

included

Constructor Details

#initialize(*args) ⇒ ApiHelper

Returns a new instance of ApiHelper.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby_stix/api/api_helper.rb', line 19

def initialize(*args)
  # Every time we create an object, we try to annotate that object's class. If the class has been annotated already,
  # this does nothing.
  annotate_class!

  # Call the super constructor to create the java object backing
  super()

  # We add several options for creating new objects. This method figures out what the particular object we're creating
  # supports and then processes the arguments. It will throw an error if invalid arguments are passed.
  process_constructor_args(*args)

  # (TODO: This may not be the right place to put this?)
  # Generate an ID if the object supports it and we didn't set something manually
  self.generate_id! if should_create_id?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object

Theoretically method_missing might be used for more, but currently it just tries to catch “add_” calls and direct them to the appropriate child. TODO: Should we just define these methods manually by iterating over all methods and finding lists?



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/ruby_stix/api/api_helper.rb', line 142

def method_missing(method_name, *args)
  # Catch us trying to "add_observable" to "ObservablesType" and correctly handle it
  if matches = method_name.to_s.match(/^add_(.+)$/)
    if matches[1] && self.respond_to?(matches[1].pluralize)
      java_method_name = java_method_name_for_key(matches[1].pluralize)
      if respond_to?(java_method_name)
        # If the method is a list, try to add the object
        if send(java_method_name).class == Java::JavaUtil::ArrayList # Need to do an equality check on the class because sometimes other classes masquerade as lists
          argument_type = find_generic_argument_for(java_method_name)
          self.send(java_method_name).add(auto_create_object(argument_type, args.first))
        elsif send(java_method_name).nil?
          # Use the setter...
          send(java_method_name.gsub(/^get/, "set"), args)
        else
          # We already have an item in the list, so just add the new one
          intermediate = send(java_method_name)
          argument_type = intermediate.find_generic_argument_for(java_method_name)
          intermediate.send(java_method_name).add(auto_create_object(argument_type, args.first))
        end
      else
        super
      end
    else
      super
    end
  elsif respond_to?("is_#{method_name}")
    send("is_#{method_name}")
  else
    super
  end
end

Class Method Details

.annotate!Object



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
# File 'lib/ruby_stix/api/api_helper.rb', line 190

def self.annotate!
  return if @annotated == true
  # Mark us as annotated
  @annotated = true

  # Annotate superclass if it's ok with that
  self.superclass.annotate! if self.superclass.respond_to?(:annotate!)

  # JRuby->Ruby name translation is not perfect and, for example, screws up "TTP"
  # This will go through all methods and correct the ruby methods
  StixRuby::IRREGULARS.each do |irregular_pattern, correct_pattern|
    self.instance_methods.select {|m| m.to_s =~ irregular_pattern}.each do |irregular|
      alias_method irregular.to_s.gsub(irregular_pattern, correct_pattern), irregular
    end
  end

  # Hooks into both Ruby and Java-style setters and makes them a little more intelligent by trying
  # to handle arrays appropriately and call constructors automatically when necessary
  self.setter_methods.each do |method_name, java_method|
    # Find the type of the argument and the name of the method
    argument_type = java_method.argument_types.first.ruby_class

    # Do not annotate this method if it's already annotated or has a basic value constructor
    next if argument_type == Java::JavaLang::Object || self.annotated_method?(method_name)

    # Mark this method as annotated
    self.annotated_method(method_name)

    # Alias the raw version
    alias_method method_name + "Raw", method_name

    # Re-define the method
    define_method method_name, ->(*args) do
      # Must have at least one argument
      raise ArgumentError.new("Wrong number of arguments (0 for 1)") if args.nil? || args.length == 0

      # Pass the argument to the raw setter if it's already of the correct type
      if args.first.kind_of?(argument_type)
        send(method_name + "Raw", *args)
      # This handles cases where we have essentially a wrapper element around an array
      # and allows us to just set the array
      elsif args.first.kind_of?(Array)
        new_obj = argument_type.new
        handle_array_argument(new_obj, args.first)
        send(method_name + "Raw", new_obj)
      else
        # Try to auto-create the object (magic happens here)
        object = auto_create_object(argument_type, args.first)

        send(method_name + "Raw", object)
      end
    end
  end
end

.annotated?Boolean

A bunch of crap for detecting when things have already been annotated

Returns:

  • (Boolean)


307
308
309
# File 'lib/ruby_stix/api/api_helper.rb', line 307

def self.annotated?
  @annotated == true
end

.annotated_method(method) ⇒ Object



320
321
322
323
# File 'lib/ruby_stix/api/api_helper.rb', line 320

def self.annotated_method(method)
  @annotated_methods ||= Set.new
  @annotated_methods.add(method)
end

.annotated_method?(name) ⇒ Boolean

Returns:

  • (Boolean)


315
316
317
318
# File 'lib/ruby_stix/api/api_helper.rb', line 315

def self.annotated_method?(name)
  @annotated_methods ||= Set.new
  @annotated_methods.include?(name) || (self.superclass.respond_to?(:annotated_method?) && self.superclass.annotated_method?(name))
end

.ruby_name(method) ⇒ Object



302
303
304
# File 'lib/ruby_stix/api/api_helper.rb', line 302

def self.ruby_name(method)
  method.underscore
end

.setter_methodsObject

Returns the Ruby or Java setter method name and the corresponding java setter method reference



246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/ruby_stix/api/api_helper.rb', line 246

def self.setter_methods
  self.java_class.java_instance_methods.select {|method| method.name =~ /^set/ && !(method.name =~ /Raw$/)}.map { |method|
    # If the method accepts more than one argument, ignore it
    if method.argument_types.length == 1
      methods = [[method.name, method]]
      methods << [ruby_name(method.name), method] if self.instance_methods.find {|m| m.to_s == ruby_name(method.name)}
      ruby_setter = ruby_name(method.name.gsub("set", "") + "=")
      methods << [ruby_setter, method] if self.instance_methods.find {|m| m.to_s == ruby_setter}
      methods
    else
      nil
    end
  }.compact.flatten(1)
end

.suppress_idObject

Some behavior to determine whether to generate an ID



181
182
183
# File 'lib/ruby_stix/api/api_helper.rb', line 181

def self.suppress_id
  @suppress_id = true
end

.suppress_id?Boolean

TODO: This would be better without the multiple checks…

Returns:

  • (Boolean)


186
187
188
# File 'lib/ruby_stix/api/api_helper.rb', line 186

def self.suppress_id?
  @suppress_id == true || (superclass.respond_to?(:suppress_id) && superclass.suppress_id?)
end

Instance Method Details

#annotate_class!Object



325
326
327
# File 'lib/ruby_stix/api/api_helper.rb', line 325

def annotate_class!
  self.class.annotate! unless annotated?
end

#annotated?Boolean

Returns:

  • (Boolean)


311
312
313
# File 'lib/ruby_stix/api/api_helper.rb', line 311

def annotated?
  self.class.annotated?
end

#auto_create_object(argument_type, arg) ⇒ Object



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
# File 'lib/ruby_stix/api/api_helper.rb', line 275

def auto_create_object(argument_type, arg)
  subclass = arg.kind_of?(Hash) && arg.delete('@@class')

  if arg.nil?
    nil
  elsif arg.kind_of?(argument_type)
    arg
  elsif argument_type.respond_to?(:from_value) && (arg.kind_of?(String) || arg.keys == ['@@class', 'value'])
    argument_type.from_value(arg.kind_of?(String) ? arg : arg['value'])
  # Handle an array argument
  # JAXB dates are really F'd up, so autoconvert them
  elsif argument_type == javax.xml.datatype.XMLGregorianCalendar
    calendar = java.util.GregorianCalendar.new
    if arg.kind_of?(String)
      arg = Time.parse(arg)
      calendar.setTime(arg.to_java)
      DatatypeFactory.newInstance.newXMLGregorianCalendar(calendar)
    else
      nil
    end
  elsif subclass
    subclass.constantize.new(arg)
  else
    argument_type.new(arg)
  end
end

#find_generic_argument_for(k) ⇒ Object

Finds the expected class for a list by parsing it out of the Java signature. This kind of blows but the way Java implements generics (type erasure) means the JRuby code does not have access to the generic type.



124
125
126
# File 'lib/ruby_stix/api/api_helper.rb', line 124

def find_generic_argument_for(k)
  Java::JavaClass.for_name(self.java_class.java_method(k).to_generic_string.match(/<(.+)>/)[1]).ruby_class
end

#generate_id!Object

Generate a random ID. Uses the ID namespace if it’s been set.



135
136
137
# File 'lib/ruby_stix/api/api_helper.rb', line 135

def generate_id!
  self.id = StixRuby.generate_id(self.class.name.split('::').last.gsub('Type', '').downcase)
end

#handle_array_argument(assign_to, argument) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/ruby_stix/api/api_helper.rb', line 261

def handle_array_argument(assign_to, argument)
  # Create the array destination
  # Try to find the appropriate getter method for the array
  getter = assign_to.java_class.java_instance_methods.reject {|m| BLACKLIST.include?(m.name) || m.return_type != java.util.List.java_class }
  raise "Unable to automatically determine array container, please explicitly specify it" if getter.length != 1
  getter = getter.first.name
  array = assign_to.send(getter)
  getter_reference = assign_to.java_class.java_method(getter).to_generic_string.match(/<(.+)>/)[1]
  expected_type = eval(getter_reference)
  argument.each {|item|
    array.add(auto_create_object(expected_type, item))
  }
end

#java_method_name_for_key(k) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/ruby_stix/api/api_helper.rb', line 108

def java_method_name_for_key(k)
  if self.respond_to?("get#{k}")
    "get#{k}"
  elsif self.respond_to?("get#{to_java_name(k)}")
    "get#{to_java_name(k)}"
  elsif k == 'ttps'
    "getTTPS"
  elsif k == 'coas'
    "getCOAS"
  else
    raise "Unable to find corresponding java method for #{k}"
  end
end

#process_args(args) ⇒ Object

This is a callback that children can override to add fancy helpers to constructor arguments Here though it’s a pass-through



176
177
178
# File 'lib/ruby_stix/api/api_helper.rb', line 176

def process_args(args)
  args
end

#process_constructor_args(*args) ⇒ Object

  1. A hash is passed, which will call appropriate setter methods to set each value to the key

  2. A string is passed, which will set the string value of the element

  3. A string and hash are passed, which will do both

  4. Nothing is passed, which will just create the object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby_stix/api/api_helper.rb', line 51

def process_constructor_args(*args)
  # If two arguments are passed, option #3 is the winner. The first argument will set the value and the second argument is the kv hash
  if args.length == 2 && self.respond_to?("value=")
    self.value = args[0]
    args = args[1]
  # If one argument is passed and it's not a hash, try to set it as the value (likely it's a string) and use an empty hash as the kv hash
  elsif args.length == 1 && !args[0].kind_of?(Hash) && self.respond_to?("value=")
    self.value = args[0]
    args = {}
  # If one argument is passed and it's a hash, use that as the kv hash
  elsif args.length == 1 && args[0].kind_of?(Hash)
    args = args[0]
  # If nothing was passed, use an empty hash as the kv hash
  elsif args.length == 0
    args = {}
  elsif args.first.kind_of?(Array)
    handle_array_argument(self, args.first)
    args = {}
  # Finally, throw an error if the arguments are anything else
  else
    raise "Invalid arguments to construct #{self.class.to_s}: #{args.inspect}"
  end

  # If key/value pairs were passed, use them
  process_args(args).each do |key, value|
    process_single_argument(key, value) unless key == '@@class'
  end
end

#process_single_argument(k, v) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/ruby_stix/api/api_helper.rb', line 80

def process_single_argument(k, v)
  # If we respond to the setter, call it. This effectively allows Java-style keyword argument names to be used
  if self.respond_to?("set#{k}")
    self.send("set#{k}", v)
  # If we respond to the Ruby setter, call it. This allows Ruby-style keyword argument names to be used
  elsif self.respond_to?("#{k}=")
    self.send("#{k}=", v)
  # Note that some array arguments might get caught by the setter
  elsif v.kind_of?(Array)
    # Find the Java method name even if we used a Ruby-style name. This is imperfect so may throw errors.
    java_method_name = java_method_name_for_key(k)

    expected_type = nil

    # Add each value individually to the list
    v.each do |value|
      argument_type = find_generic_argument_for(java_method_name)

      value = auto_create_object(argument_type, value)

      # Finally, set the value
      self.send(java_method_name).add(value)
    end
  else
    raise ArgumentError.new("Invalid argument to construct #{self.class.to_s}: `#{k}`")
  end
end

#should_create_id?Boolean

Returns whether or not a new object should have an auto-generated ID. The criteria are:

  1. It responds to “id” and “idref” (i.e. is a STIX-idable object)

  2. It doesn’t have “suppress_id” set

  3. There’s no id or idref set already

Returns:

  • (Boolean)


40
41
42
# File 'lib/ruby_stix/api/api_helper.rb', line 40

def should_create_id?
  self.respond_to?(:id) && self.respond_to?(:idref) && !self.class.suppress_id? && self.idref.nil? && self.id.nil?
end

#to_java_name(string) ⇒ Object

Convert a Ruby-style method name (lower snake) to a Java-style method name (camel) This is imperfect, really I would like to re-use the JRuby logic but don’t know how.



130
131
132
# File 'lib/ruby_stix/api/api_helper.rb', line 130

def to_java_name(string)
  string.to_s.camelize
end