Eclipse can't find my installed Ruby gems (JRuby) - java

So, I am trying to use my ruby scripts inside my java code with the help of JRuby. But there is a problem, eclipse is not being able to use the gems I have installed. For testing purposes, I've been trying to run a piece of code that requires the "nokogiri" ruby gem, which I have installed. When I try to run the java code, here's what I get:
LoadError: no such file to load -- nokogiri
require at org/jruby/RubyKernel.java:939
<top> at /home/amng/workspace/scripts/xx/x/getMSPatches:4
Exception in thread "main" org.jruby.embed.EvalFailedException: (LoadError) no such file to load -- nokogiri
at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:131)
at org.jruby.embed.ScriptingContainer.runUnit(ScriptingContainer.java:1307)
at org.jruby.embed.ScriptingContainer.runScriptlet(ScriptingContainer.java:1352)
at jobs.Teste.run(Teste.java:17)
at jobs.Teste.main(Teste.java:11)
Caused by: org.jruby.exceptions.RaiseException: (LoadError) no such file to load -- nokogiri
at org.jruby.RubyKernel.require(org/jruby/RubyKernel.java:939)
at RUBY.(/home/amng/workspace/scripts/myPrecious/MSPatches/getMSPatches:4)
I downloaded the jruby.jar from the website and added to the build path of the project. I also pointed the eclipse to the JRuby binary using the Dynamic Languages Toolkit (DLTK) plugin. What do I have to do to make sure that eclipse can use the gems I have installed?
Edit: My java code:
import org.jruby.embed.ScriptingContainer;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
public class Main {
public static void main(String[] args) {
ScriptingContainer ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
Object result = ruby.runScriptlet(PathType.ABSOLUTE, "/home/amng/workspace/scripts/myPrecious/MSPatches/getMSPatches");
System.out.println(result);
}
}
The first two lines of my (working) ruby code (getMSPatches) are:
# encoding: UTF-8
require 'nokogiri'

Try setting the jruby home directory
ScriptingContainer ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
ruby.setHomeDirectory("/jruby-9.0.5.0");
This solved the issue for me.

Related

Problem connecting Java and Prolog with JPL

I wanted to connect Java and Swi Prolog together using JPL.
When I added the library to my project on Intellij the code compiled and when I tried to run a query I got a runtime error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jpl in java.library.path: [C:\Program Files\Java\jdk-12\bin, C:\WINDOWS\Sun\Java\bin, C:\WINDOWS\system32, C:\WINDOWS, c:\swipl\bin, ${env_var:PATH}, .]
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2660)
at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:827)
at java.base/java.lang.System.loadLibrary(System.java:1902)
at org.jpl7.JPL.loadNativeLibrary(JPL.java:114)
at org.jpl7.fli.Prolog.<clinit>(Prolog.java:71)
at org.jpl7.Query.open(Query.java:369)
at org.jpl7.Term.textToTerm(Term.java:155)
at org.jpl7.Query.<init>(Query.java:169)
at Main.main(Main.java:7)
I have the swi prolog 64 bit.
I've tried uninstalling it and use the 32 bit but it did not work.
What I did so far:
I added SWI_HOME_DIR to my Environment Variables.
I also added the swi path to Path variable.
I added the jpl library to my project (and it added it successfully).
The code I was trying to run:
import org.jpl7.*;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Query q = new Query("true");
q.hasSolution();
Map<String,Term>[] res = q.allSolutions();
for (int i = 0; i < res.length; i++) {
System.out.println(res[i]);
}
}
}
So, is jpl.dll in any of the listed directories:
C:\Program Files\Java\jdk-12\bin ... probably not
C:\WINDOWS\Sun\Java\bin ... probably not
C:\WINDOWS\system32 ... probably not
C:\WINDOWS ... probably not
c:\swipl\bin ... apparently yes as c:\swipl\bin\jpl.dll exists?
${env_var:PATH} ... apparently not
Try the suggestion from this question in your Java program:
File nativeFile = new File(filename + ".dll");
if (!nativeFile.exists())
System.exit(1);
System.load(nativeFile);
Note that just having jpl.jar is not enough. One needs the jpl.dll file, too. jpl.jar is good for the Java part of the Java-Prolog bridge, but to be able to call a non-JVM compilate, we need to get into system-level details, Hence the dll file.
See troubleshooting tips here: JPL Deploying for users - on Windows
From the above page:
If the Java examples complain that
The dynamic link library libpl.dll could not be found in the specified path
or
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\paul\bin\jpl.dll: Can't find dependent libraries
then there is no SWI-Prolog library libpl.dll in any folder on your
PATH: you should have a PATH entry such as C:\Program Files\pl\bin.
The libpl.dll should contain the code for SWI-Prolog itself.

Error: "UnsatisfedLinkError: com.aparapi.internal.jni.OPENCLJNI.getPlatforms()" JNI configuration

I would try to execute an example script based on Aparapi, on MAC OS. I'm using the last version of Eclipse, but when I execute DeviceInfo example to get all the available devices:
public class DeviceInfo {
public static void main(String[] args) {
KernelPreferences preferences = KernelManager.instance().getDefaultPreferences();
System.out.println("-- Devices in preferred order --");
for (Device device : preferences.getPreferredDevices(null)) {
System.out.println(device);
}
}
}
it generates the
java.lang.UnsatisfiedLinkError: com.amd.aparapi.OpenCLJNI.getPlatforms()Ljava/util/List"
Is there someone who can help me?
build the native assembly for Mac (x86_64) and add it into jniLibs; here's the source code.
java.lang.UnsatisfiedLinkError generally means, that it cannot find the native assembly.
Despite macOS Mojave 10.14.4 don't support directly OpenCL, I've executed Aparapi Framework.
I founded that the problem is the Aparapi Library. In particular, to resolve generated error I followed these steps:
Download this repository https://github.com/aparapi/aparapi for AMD Graphic Cards
Open the directory "com.amd.aparapi" and from terminal execute
ant -f build.xml
This command generates .jar file of this library
Add the generate jar to the project's classpath in Eclipse
Add the specific Aparapi library for your OS in:
<your-workspace-path>/<your-project>/src/main/resources/osx/
Before to execute the code, add the VM argument in "Run Configuration"
-Djava.library.path=<your-workspace-path>/<your-project>/src/main/resources/osx/
Execute your script!

Ensuring files are available to the JVM

I'm trying to install TensorFlow for Java on Windows 10 using this Article
. I followed the steps carefully but the windows commands didn't work with me so I decided to do it manually.
The first command is to make the .jar part of the classpath and I did it manually
but the second step was to ensure that the following two files are available to the JVM: the .jar file and the extracted JNI library
but I don't know how to do that manually
The code:
package securityapplication;
import org.tensorflow.TensorFlow;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class SecurityApplication {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
could someone help? cuz my program that uses TensorFlow still have the following error
The text in the image is :
Exception in thread "main" java.lang.UnsatisfiedLinkError: Cannot find TensorFlow native library for OS: windows, architecture: x86. See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md for possible solutions (such as building the library from source). Additional information on attempts to find the native library can be obtained by adding org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.TensorFlow.init(TensorFlow.java:36)
at org.tensorflow.TensorFlow.<clinit>(TensorFlow.java:40)
at org.tensorflow.Graph.<clinit>(Graph.java:194)
at securityapplication.SecurityApplication.main(SecurityApplication.java:15) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
The result after running the first command in cmd:
The result after running the second command in Windows PowerShell:
Any suggestions?!
Thank you
The first command failure (javac) suggests that the javac command is not in your PATH environment variables. See for example, this StackOverflow question
For the second command failure, I believe the space after -D is what is causing you trouble as Holger suggested.
IDEs like Eclipse and others also provide a means to set the java.library.path property for the JVM (see this StackOverflow answer for example).
Background: TensorFlow for Java consists of a Java library (packaged in a .jar file) and a native library (.dll on Windows, distributed in a .zip file). You need to ensure that the .jar file is in the classpath and the directory containing the .dll is in included in the java.library.path of the JVM when executing a program.
Hope that helps.

reportlab in Jython "import error"

I am using jdk 1.8 and Jython 2.7.0.jar to execute my python Code.
But It seems Jython does not support Python's 2.7 feature 'reportlab' module.
My Java Code :
package test;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Test{
public Test()
{
System.out.println("Done!");
engine.eval("import sys");
engine.eval("print sys");
engine.eval("import reportlab");
engine.eval("print reportlab");
System.out.println("Done Here");
}
catch (ScriptException ex)
{
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
public static void main(String args[])
{
Test t=new Test();
}
}
Error I got:
run:
Done!
<module 'sys' (built-in)>
javax.script.ScriptException: ImportError: No module named reportlab in <script> at line number 1
Dec 28, 2015 8:57:52 PM test.Test <init>
SEVERE: null
javax.script.ScriptException: ImportError: No module named reportlab in <script> at line number 1
at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:202)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:42)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at test.Test.<init>(Test.java:28)
at test.Test.main(Test.java:40)
Caused by: Traceback (most recent call last):
File "<script>", line 1, in <module>
ImportError: No module named reportlab
at org.python.core.Py.ImportError(Py.java:328)
at org.python.core.imp.import_first(imp.java:877)
at org.python.core.imp.import_module_level(imp.java:972)
at org.python.core.imp.importName(imp.java:1062)
at org.python.core.ImportFunction.__call__(__builtin__.java:1280)
at org.python.core.PyObject.__call__(PyObject.java:431)
at org.python.core.__builtin__.__import__(__builtin__.java:1232)
at org.python.core.imp.importOne(imp.java:1081)
at org.python.pycode._pyx2.f$0(<script>:1)
at org.python.pycode._pyx2.call_function(<script>)
at org.python.core.PyTableCode.call(PyTableCode.java:167)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1386)
at org.python.core.__builtin__.eval(__builtin__.java:497)
at org.python.core.__builtin__.eval(__builtin__.java:501)
at org.python.util.PythonInterpreter.eval(PythonInterpreter.java:259)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:40)
... 4 more
BUILD SUCCESSFUL (total time: 2 seconds)
If anyone could suggest me an Alternate way of remotely executing a Python script I'd be thankful to them.
Also I have a large code base in python of which rewriting in java is not feasible in scheduled time.
Jython is a completely different (and independent) Python interpreter than your system's Python. While most libraries from Python's standard library will exist in Jython, third party modules installed in your system's Python simply don't exist for the Jython version.
Jython is compatible enough that you can set a Python virtualenv with the Jython interpreter and install modules that are pure-python code (i.e. no binary modules) in that virtualenv - I don't think repotlab qualifies as such - but you might try. In a Java project setup, probably your project have its own instance of the Jython interpreter installed along other .jar files - it should feature a site-packages folder somewhere where you could try to copy pure Python third-party modules to, but again, I don't think reportlab will be jython compatible.
One option for you is to use Python itself (cPython) in an external process, and call it from Java (or Jython) using xmlrpc code - (A quickly googling didn't find me out a way to call cPython via xmlrpc from pure Java - but I know it works from Jython, if you use Python's stdlib xmlrpc as documented -
https://docs.python.org/3/library/xmlrpc.html?highlight=xmlrpc
I've got a solution on a stackExchange link - Jython embedded in Java -- ImportError: No module named yaml i.e I can simply add the packages I need under my Jython Installation directory E.g jython/Lib/site-packages I've got no Issues on reportlab for Python2.7.
most Important also append them in your program using sys.path.append()

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:
adding require 'rubygems' to the top of the script. This only changes the exception to LoadError: no such file to load -- rubygems
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?
The solution is:
jruby -S gem install winrm

Categories

Resources