Module: Jvm

Defined in:
lib/mn2pdf/jvm.rb

Constant Summary collapse

MN2PDF_JAR_PATH =
Pathname.new(__FILE__)
.dirname
.join("../../bin/mn2pdf.jar")
.realpath
DEFAULT_JAVA_OPTS =
%w[-Xss10m -Xmx3g -Djava.awt.headless=true].freeze

Class Method Summary collapse

Class Method Details

.ensure_java_opts(opts, key, min_value_bytes) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mn2pdf/jvm.rb', line 25

def self.ensure_java_opts(opts, key, min_value_bytes)
  flag, idx = opts.each_with_index.find { |opt, _| opt.start_with?(key) }
  if flag
    flag_value_bytes = to_bytes(flag[key.length..-1])

    if flag_value_bytes < min_value_bytes
      min_value_str = "#{key}#{min_value_bytes / (1024 * 1024)}m"
      opts[idx] = min_value_str
    end
  else
    opts << "#{key}#{min_value_bytes / (1024 * 1024)}m"
  end
end

.optionsObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mn2pdf/jvm.rb', line 39

def self.options
  result = ENV["JAVA_OPTS"]&.split || DEFAULT_JAVA_OPTS.dup

  ensure_java_opts(result, "-Xss", to_bytes("10m"))
  ensure_java_opts(result, "-Xmx", to_bytes("3g"))

  if RbConfig::CONFIG["host_os"].match?(/darwin|mac os/)
    result << "-Dapple.awt.UIElement=true"
  end

  result << "-Duser.home=#{Dir.home}"

  result
end

.run(args = []) ⇒ Object



54
55
56
57
58
59
# File 'lib/mn2pdf/jvm.rb', line 54

def self.run(args = [])
  cmd = ["java", *options, "-jar", MN2PDF_JAR_PATH, *args].join(" ")
  puts cmd
  stdout, stderr, status = Open3.capture3(cmd)
  [stdout, stderr, status]
end

.to_bytes(value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mn2pdf/jvm.rb', line 12

def self.to_bytes(value)
  case value[-1].downcase
  when "k"
    value.to_i * 1024
  when "m"
    value.to_i * 1024 * 1024
  when "g"
    value.to_i * 1024 * 1024 * 1024
  else
    value.to_i
  end
end