Search code examples
javarubyjrubywinrm

Executing a Ruby script from Java using JRuby results in 'LoadError: no such file to load ...'


I'd like to execute a Ruby script from Java using JRuby (Linux Mint). I can successfully execute the script from the terminal by calling ruby script.rb. However, the script contains a require that causes "no such file to load" exception when trying to execute it from Java using JRuby:

package com.company;

import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
import org.jruby.embed.ScriptingContainer;

public class Main
{
    public static void main(String[] args)
    {
        ScriptingContainer ruby;
        ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);        
        Object result = ruby.runScriptlet(PathType.ABSOLUTE, "/home/user/Scripts/script.rb");
    }
}

The problem seems to be in the require ... part of the script.rb, since this code works fine for e.g. a simple script that only displays text.

The script uses WinRb, a Ruby library for Windows Remote Management. script.rb:

require 'winrm'

endpoint = 'http://somehost.domain.org:5985/wsman'
krb5_realm = 'DOMAIN.ORG'
command = 'hostname'

winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm)

winrm.cmd(command) do |stdout, stderr|
  STDOUT.print stdout
  STDERR.print stderr
end

When I run the Java code I get this exception:

LoadError: no such file to load -- winrm
  require at org/jruby/RubyKernel.java:940
    <top> at /home/user/Scripts/script.rb:5
Exception in thread "main" org.jruby.embed.EvalFailedException: 
(LoadError) no such file to load -- winrm

Here's what I tried:

  1. adding require 'rubygems' to the top of the script. This only changes the exception to LoadError: no such file to load -- rubygems
  2. specifying full path: require '/var/lib/gems/1.9.1/gems/winrm-1.3.3/lib/winrm'. Instead of the original exception, at runtime I now get: LoadError: no such file to load -- date require at org/jruby/RubyKernel.java:940

Other:

$ ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
$ jruby -v
jruby 9.0.0.0 (2.2.2) 2015-07-21 e10ec96 Java HotSpot(TM) 64-Bit Server VM 25.45-b02

How can I get JRuby to execute this script successfully?


Solution

  • The solution is:

    jruby -S gem install winrm