how can i use jruby in java code to call a method in ruby script

Viewed 43

here is my ruby script(test.rb):

# coding=utf-8
require 'net/ssh'

def sshConnection (host, username, password)
     Net::SSH.start(host.to_s, username.to_s, password: password.to_s) do |ssh|
         result = ssh.exec!("command")
         return result
     end
end

so, how can i use jruby to call this method in java code, i hava tried to search it and here is my code:

package com.example;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JrubyDemo1 {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("ruby");

        try{
         engine.eval(Files.newBufferedReader(Paths.get(".....\\test.rb"),StandardCharsets.UTF_8));
         Invocable invocable = (Invocable) engine

         Object o = invocable.invokeFunction("sshConnection", "xx.xx.xx.xx", "xxx", "xxx");   
         System.out.println(o);
        }catch(Exception e){
          //...
        }
    }
}

but it didn't work, error is as this picture shows:

0 Answers
Related