optimize Java Map initialization

This commit is contained in:
Colin Surprenant 2016-05-19 16:30:40 -04:00
parent 6c886845e6
commit 5cdd434612
2 changed files with 25 additions and 6 deletions

View file

@ -4,6 +4,7 @@ require "spec_helper"
require "logstash/util"
require "logstash/event"
require "json"
require "java"
TIMESTAMP = "@timestamp"
@ -286,4 +287,24 @@ describe LogStash::Event do
end
end
end
context "initialize" do
it "should accept Ruby Hash" do
e = LogStash::Event.new({"foo" => 1, TIMESTAMP => "2015-05-28T23:02:05.350Z"})
expect(e.get("foo")).to eq(1)
expect(e.timestamp.to_iso8601).to eq("2015-05-28T23:02:05.350Z")
end
it "should accept Java Map" do
h = Java::JavaUtil::HashMap.new
h.put("foo", 2);
h.put(TIMESTAMP, "2016-05-28T23:02:05.350Z");
e = LogStash::Event.new(h)
expect(e.get("foo")).to eq(2)
expect(e.timestamp.to_iso8601).to eq("2016-05-28T23:02:05.350Z")
end
end
end

View file

@ -20,6 +20,7 @@ import org.jruby.RubyInteger;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.java.proxies.MapJavaProxy;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Arity;
import org.jruby.runtime.ObjectAllocator;
@ -127,12 +128,9 @@ public class JrubyEventExtLibrary implements Library {
if (data == null || data.isNil()) {
this.event = new Event();
} else if (data instanceof RubyHash) {
HashMap<String, Object> newObj = Javafier.deep((RubyHash) data);
this.event = new Event(newObj);
} else if (data instanceof Map) {
this.event = new Event((Map) data);
} else if (Map.class.isAssignableFrom(data.getJavaClass())) {
this.event = new Event((Map)data.toJava(Map.class));
this.event = new Event(Javafier.deep((RubyHash) data));
} else if (data instanceof MapJavaProxy) {
this.event = new Event((Map)((MapJavaProxy)data).getObject());
} else {
throw context.runtime.newTypeError("wrong argument type " + data.getMetaClass() + " (expected Hash)");
}