Google OR-Tools in Intellij: UnsatisfiedLinkError - java

I am setting up a java framework that should use the Google OR-Tools. The code below compiles successfully, but throws an exception at runtime:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get()I
at com.google.ortools.linearsolver.operations_research_linear_solverJNI.MPSolver_CLP_LINEAR_PROGRAMMING_get(Native Method)
at com.google.ortools.linearsolver.MPSolver$OptimizationProblemType.<clinit>(MPSolver.java:221)
at Main.main(Main.java:15)
I am using Intellij 2018.3 on Windows 10. I spent a lot of time trying to get this run, but unsuccessful. Based on what I found on the internet, the exception might be caused by poor linking and/or missing external libraries on which OR-Tools depends. However, I don't have the background to resolve this issue, and also Intellij does not highlight anything. Any idea what the problem is?
For completion, this is the code I run:
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
public final class Main {
public static void main(String[] args) {
// Create the linear solver with the GLOP backend.
MPSolver solver =
new MPSolver("SimpleLpProgram", MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING);
// Create the variables x and y.
MPVariable x = solver.makeNumVar(0.0, 1.0, "x");
MPVariable y = solver.makeNumVar(0.0, 2.0, "y");
System.out.println("Number of variables = " + solver.numVariables());
// Create a linear constraint, 0 <= x + y <= 2.
MPConstraint ct = solver.makeConstraint(0.0, 2.0, "ct");
ct.setCoefficient(x, 1);
ct.setCoefficient(y, 1);
System.out.println("Number of constraints = " + solver.numConstraints());
// Create the objective function, 3 * x + y.
MPObjective objective = solver.objective();
objective.setCoefficient(x, 3);
objective.setCoefficient(y, 1);
objective.setMaximization();
solver.solve();
System.out.println("Solution:");
System.out.println("Objective value = " + objective.value());
System.out.println("x = " + x.solutionValue());
System.out.println("y = " + y.solutionValue());
}
}

In my case solution was simple - I just needed to add this singe line of code:
Loader.loadNativeLibraries();
where loader comes from com.google.ortools.Loader

Disclaimer: more a long comment than an answer...
note: I supposed you are using the github repository of or-tools if you used the binary package it should be more or less the same...
1) You must load the jni library which will load the OR-Tools C++ libraries and its dependencies...
/** Simple linear programming example.*/
public class Main {
static {
System.loadLibrary("jniortools");
}
public static void main(String[] args) throws Exception {
2) Did you manage to run the java samples ?
make run SOURCE=ortools/linear_solver/samples/SimpleLpProgram.java
ref: https://developers.google.com/optimization/introduction/java#simple_example
3) As Kayaman pointed out, you must pass the folder where the java runtime can find the native libraries (i.e. the JNI wrapper jniortools.dll and its dependencies libortools.dll)
if you look at the console log you'll see the full command line:
java -Xss2048k -Djava.library.path=lib -cp lib\sample.jar;lib\com.google.ortools.jar;lib\protobuf.jar ...\sample
Which comes from, the makefiles/Makefile.java file:
JAVAFLAGS = -Djava.library.path=$(LIB_DIR)
...
ifeq ($(SOURCE_SUFFIX),.java) # Those rules will be used if SOURCE contain a .java file
$(CLASS_DIR)/$(SOURCE_NAME): $(SOURCE) $(JAVA_OR_TOOLS_LIBS) | $(CLASS_DIR)
-$(DELREC) $(CLASS_DIR)$S$(SOURCE_NAME)
-$(MKDIR_P) $(CLASS_DIR)$S$(SOURCE_NAME)
"$(JAVAC_BIN)" -d $(CLASS_DIR)$S$(SOURCE_NAME) \
-cp $(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_PATH)
...
.PHONY: run # Run a Java program.
run: build
"$(JAVA_BIN)" -Xss2048k $(JAVAFLAGS) \
-cp $(LIB_DIR)$S$(SOURCE_NAME)$J$(CPSEP)$(LIB_DIR)$Scom.google.ortools.jar$(CPSEP)$(LIB_DIR)$Sprotobuf.jar \
$(SOURCE_NAME) $(ARGS)
endif
src: https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L15
and
https://github.com/google/or-tools/blob/46173008fdb15dae1dca0e8fa42a21ed6190b6e4/makefiles/Makefile.java.mk#L328-L333
note: you can run make detect_java to know the flags i.e. value of LIB_DIR
note: if you did use the precompiled package the Makefile is here:
https://github.com/google/or-tools/blob/stable/tools/Makefile.cc.java.dotnet
Then after you can try to add this option in Intellij...
You must understand that or-tools is a set of C++ native libraries which are wrapped to Java using the SWIG generator.

To make it work using Intellij (over a windows machine) you need to:
Install Microsoft Visual C++ Redistributable for Visual Studio
Download and extract the OR-Tools library for Java
In intellij, add jar dependency to the 2 jars under the lib folder of the extracted files (each of the 2 jars separately, do not add to lib folder itself. This is why).
Add the lib library path to VM options. In Intellij edit your run-configuration and add to vm options: -Djava.library.path=<path to the lib folder that hold the jars>
Load the jni library statically by adding the below code to your class (as mentioned here.)
static {
System.loadLibrary("jniortools");
}

Related

Include multiple source directories in Qt for Android

I want to include Java source code from multiple directories (which are shared between projects) in a Qt for Android project. On http://imaginativethinking.ca/what-the-heck-how-do-i-share-java-code-between-qt-android-projects/ an approach is described which copies the Java source files:
# This line makes sure my custom manifest file and project specific java code is copied to the android-build folder
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
# This is a custom variable which holds the path to my common Java code
# I use the $$system_path() qMake function to make sure that my directory separators are correct for the platform I'm compiling on as you need to use the correct separator in the Make file (i.e. \ for Windows and / for Linux)
commonAndroidFilesPath = $$system_path( $$PWD/../CommonLib/android-sources/src )
# This is a custom variable which holds the path to the src folder in the output directory. That is where they need to go for the ANT script to compile them.
androidBuildOutputDir = $$system_path( $$OUT_PWD/../android-build/src )
# Here is the magic, this is the actual copy command I want to run.
# Make has a platform agnostic copy command macro you can use which substitutes the correct copy command for the platform you are on: $(COPY_DIR)
copyCommonJavaFiles.commands = $(COPY_DIR) $${commonAndroidFilesPath} $${androidBuildOutputDir}
# I tack it on to the 'first' target which exists by default just because I know this will happen before the ANT script gets run.
first.depends = $(first) copyCommonJavaFiles
export(first.depends)
export(copyCommonJavaFiles.commands)
QMAKE_EXTRA_TARGETS += first copyCommonJavaFiles
With later Qt versions the code has to be changed to this:
commonAndroidFilesPath = $$system_path($$PWD/android/src)
androidBuildOutputDir = $$system_path($$OUT_PWD/../android-build)
createCommonJavaFilesDir.commands = $(MKDIR) $${androidBuildOutputDir}
copyCommonJavaFiles.commands = $(COPY_DIR) $${commonAndroidFilesPath} $${androidBuildOutputDir}
first.depends = $(first) createCommonJavaFilesDir copyCommonJavaFiles
export(first.depends)
export(createCommonJavaFilesDir.commands)
export(copyCommonJavaFiles.commands)
QMAKE_EXTRA_TARGETS += first createCommonJavaFilesDir copyCommonJavaFiles
Is this the standard way to go, or is there some built-in functionality for including multiple Java source directories in Qt for Android projects?
Regards,
A much cleaner solution is this one:
CONFIG += file_copies
COPIES += commonJavaFilesCopy
commonJavaFilesCopy.files = $$files($$system_path($$PWD/android/src))
commonJavaFilesCopy.path = $$OUT_PWD/android-build

Run matlab function in java class in absence of matlab environment

I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?
After a lot of googling, I used this toturial but in the final step, i get error "could not load file".
Also i read about MatlabControl, but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.
So i need a solution to run matlab function in java class even in absence of matlab environment.
Finally I solve my problem. the solution step by step is as follows:
write matlab function:
function y = makesqr(x)
y = magic(x);
Use deploytool in matlab and create java package.
3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import makesqr.Class1;
and main.java:
public class main {
public static void main(String[] args) {
MWNumericArray n = null;
Object[] result = null;
Class1 theMagic = null;
try
{
n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);
theMagic = new Class1();
result = theMagic.makesqr(1, n);
System.out.println(result[0]);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(n);
MWArray.disposeArray(result);
theMagic.dispose();
}
}
}
add javabuilder.jar and makesqr.jar to java build path of your project.
run it.
the Double.valueOf(3), define the input for our function and the output is as follows:
8 1 6
3 5 7
4 9 2
I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?
If your answer is the latest case, most probably you forgot the "." before the class path.
From tutorial you linked:
You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.
Also check if the matlab compiler path ("c:\Program Files\MATLAB\MATLAB Compiler Runtime\v82\toolbox\javabuilder\jar\javabuilder.jar" - in the tutorial) is correct for your system.

How use openalpr in java project

I want to use openalpr in my java project. What must I include to use the API? What libs must be imported in project properties in Eclipse or Netbeans?
I found the solution
Download openalpr binaries
https://github.com/openalpr/openalpr/releases
Install and configure jdk (java and javac path)
Compile openalpr java source code, start java_test.bat file
Start main.java
java -classpath java Main "us" "openalpr.conf" "runtime_data" "samples/us-1.jpg"
Copy the native libs (DLLs for windows) into the exec dir
Copy the java classes into your project (dir: /src/main/java)
Get started with:
`
Alpr alpr = new Alpr("us", "/path/to/openalpr.conf", "/path/to/runtime_data");
// Set top N candidates returned to 20
alpr.setTopN(20);
// Set pattern to Maryland
alpr.setDefaultRegion("md");
AlprResults results = alpr.recognize("/path/to/image.jpg");
System.out.format(" %-15s%-8s\n", "Plate Number", "Confidence");
for (AlprPlateResult result : results.getPlates())
{
for (AlprPlate plate : result.getTopNPlates()) {
if (plate.isMatchesTemplate())
System.out.print(" * ");
else
System.out.print(" - ");
System.out.format("%-15s%-8f\n", plate.getCharacters(), plate.getOverallConfidence());
}
}
(Source: http://doc.openalpr.com/bindings.html#java)

"Error: Could not find or load main class My.class"

Im using Java SDK 1.7 on Windows 7 via cmd.exe . Up until a few hours ago everything was working correctly when suddenly I was unable to run my compiled class files, consistently presented with the error in the title.
I seem to be able to compile my My.java file however I am unable to run the resulting class file (My.class). I am constantly given the error "Error: Could not find or load main class My.class". I have tried this with multiple other class files all resulting in the same problem.
My 'Path' environment variable is set to "C:\Program Files (x86)\Java\jdk1.7.0_05\bin" if you were wondering
I have tried reinstalling, creating and setting a classpath variable (no luck), and even directly using the
java -cp . My.class
command.
I have tried these posts all to no avail, hence why I'm posting:
Error: Could not find or load main class
Error: Could not find or load main class- Novice
Could not find or load main class
Java 1.7.0_03 Error: Could not find or load main class
If it makes any difference my code is :
import javax.swing.JOptionPane;
class My {
public static void main(String[] args) {
final double x = 3.2;
int i = (int)x;
double m = 0;
if (x < 4) {
String saySomething = JOptionPane.showInputDialog(i);
System.out.println(saySomething);
}
else {
String saySomething = JOptionPane.showInputDialog(i);
System.out.println("Hello World");
}
while (m < 10) {
System.out.print(" While Loop ");
m++;
};
for (i=1; i < 10; i++) {
System.out.println("For Loop");
};
}
}
You should specify the classname instead of the file of the class to load. The difference is a simple matter of removing the .class extension.
I would use an IDE and you shouldn't get these issues. Compile and run is just a click of the mouse.
BTW to run your program from the command line
java -cp . My
You don't add .class
Position yourself in a directory of your project (you need to have src and bin directories there, assuming you keep sources in src and binaries in bin)
java -cp bin My
I myself was facing the same problem. It was happening because I was being remiss in typing the name of the class properly. In my instance, I was typing
java doubler
instead of
java Doubler

fannj library doesn't work

I'm trying to run project which uses fannj library, but I'm getting error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'fann_create_standard_array':
at com.sun.jna.Function.<init>(Function.java:179)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:347)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:327)
at com.sun.jna.Native.register(Native.java:1355)
at com.sun.jna.Native.register(Native.java:1032)
at com.googlecode.fannj.Fann.<clinit>(Fann.java:46)
at javaapplication9.JavaApplication9.main(JavaApplication9.java:14)
Java Result: 1
This is what I did:
I put fannfloat.dll to C:\Windows\System32
I added fannj-0.3.jar to project
I added newest jna.jar to project
here is code:
public static void main(String[] args) {
System.setProperty("jna.library.path", "C:\\Windows\\System32");
System.loadLibrary("fannfloat");
Fann fann=new Fann("D:\\SunSpots.net");
fann.close();
}
SunSpots.net is file from example package. fannfloat.dll: you can get from here.
The "#8" at the end of _fann_create_standard_array indicates that the library is using the stdcall calling convention, so your library interface needs to implement that interface (StdCallLibrary) and it will automatically get the function name mapper applied that converts your simple java name to the decorated stdcall one.
This is covered in the JNA documentation.
It was the first time I had to work with FANN and it took me some time to make it work.
Downloaded Fann 2.2.0. Extract (in my case "C:/FANN-2.2.0-Source") and check the path of the fannfloat.dll file. This is the library that we will use later.
Download fannj-0.6.jar from http://code.google.com/p/fannj/downloads/list.
The dll is compiled for 32 bit environment. So, make sure you have a 32 bit Java installed (even in 64 bit Windows).
I suppose you already have the .net file with your ANN. Write something like this in Java
public class FannTest {
public static void main(String[] args) {
System.setProperty("jna.library.path", "C:/FANN-2.2.0-Source/bin");
Fann fann = new Fann("C:/MySunSpots.net" );
float[] inputs = new float[]{0.686470295f, 0.749375936f, 0.555167249f, 0.816774838f, 0.767848228f, 0.60908637f};
float[] outputs = fann.run( inputs );
fann.close();
for (float f : outputs) {
System.out.print(f + ",");
}
}
}

Categories