How to call cplex .mod and .data from Java - java

I have an optimization problem modelled and written in IBM ILOG CPLEX Optimization Studio. I want to call .mod and .dat from Java. I found some example to do it. However, I got some error.
My code is shown below. I also added all cplex and opl library
package cplexJava;
import ilog.concert.*;
import ilog.cplex.*;
import ilog.opl.*;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
model();
}
public static void model() {
int status = 127;
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod");
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();
cplex.setOut(null);
IloOplModel opl = oplF.createOplModel(def, cplex);
IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat");
opl.addDataSource(dataSource);
opl.generate();
if (cplex.solve())
{
System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue());
opl.postProcess();
opl.printSolution(System.out);
}
else
{
System.out.println("No solution!");
}
oplF.end();
status = 0;
System.exit(status);
}
}
In my code, the errors came from from oplF.createCplex() and cplex.solve(). When I tried to run it, this is the error I got.
I could not figure out why I got the errors from oplF.createCplex() and cplex.solve() although I already added the cplex and opl library

Actually your IDE tells you what the problem is: There are possible IloExceptions thrown and you do not handle them. You need to either surround your code with a try catch block, or your main-method should have a "throws IloException" in the signature:
package cplexJava;
import ilog.concert.*;
import ilog.cplex.*;
import ilog.opl.*;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
model();
}
public static void model() {
int status = 127;
try {
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod");
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();
cplex.setOut(null);
IloOplModel opl = oplF.createOplModel(def, cplex);
IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat");
opl.addDataSource(dataSource);
opl.generate();
if (cplex.solve())
{
System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue());
opl.postProcess();
opl.printSolution(System.out);
}
else
{
System.out.println("No solution!");
}
oplF.end();
} catch (IloException ilx) {
// log error message or something like that
}
status = 0;
System.exit(status);
}
}
And please use class names with upper case first letter and package names with all lower case.

For the OPL Java API, you should only need oplall.jar.
SETUP
On my x86-64 Linux machine with Eclipse 3.6, this is done, like so (hopefully it's similar for you):
Right click on your Java Project and select Properties
Select "Java Build Path" on the left and the Libraries tab on the right
Click on the "Add External JARs..." button and select COS_INSTALL_DIR/opl/lib/oplall.jar (where COS_INSTALL_DIR is the location where you installed CPLEX Optimization Studio)
Click OK
One more thing to do is make sure that your LD_LIBRARY_PATH environment variable is set to COS_INSTALL_DIR/opl/bin/x86-64_linux. (NOTE: On Windows, I think you should set the PATH environment variable instead.) You can set this in Eclipse, like so:
Select "Run > Run Configurations..." in the menu
On the left, select your java application
On the right, select the Environment tab and click on the "New..." button
Enter LD_LIBRARY_PATH in the Name field (try PATH on Windows)
Enter COS_INSTALL_DIR/opl/bin/x86-64_linux in the Value field (again, where COS_INSTALL_DIR is the location where you installed CPLEX Optimization Studio)
Click OK
FIX COMPILER ERRORS
Once you have that set up, you'll probably notice that you are still getting compiler errors (the little red squiggle lines indicate this). Hover your mouse over the those and you'll be presented with a list of quick fixes: 1) add throws declaration; 2) Surround with try/catch. Pick one of those to fix the issue. After all of the red squiggly lines are gone you should be able to run your program.
If you're not familiar with fixing compiler errors in Eclipse, maybe this Eclipse tutorial with help. Sometimes you have to select "Project > Clean" to force a recompile.

I also faced the the same problem.
After some trial and error I realized that the correct name is DYLD_LIBRARY_PATH for macos.
Referral link

Related

java class getResource can't find icons listed in jar file

I am really stumped. I'm just an old C X11/Motif programmer trying to write a little Java program. After a week of reading the Oracle Java Documentation, as well as the
Stack Overflow answers related to getResource, I still can not figure out how to retrieve the path to the icon files in my jar file.
My icons are contained within the jar file for my application. I wish to access them using the relative position within jar file. I am assuming the best way to do this is through the getResource method.
The core part of my code for my program called Fŭd (pronounced food - like the cat spells it in the comic strip "Get Fuzzy") is as follows:
package localhost.system1;
imports not shown for brevity.
public class Fud extends JPanel
implements FocusListener, ActionListener, ItemListener
{
private static final long serialVersionUID = 1L;
static Food data = null;
static int prev = 0;
static int next = 1;
static int plus = 2;
static int minus = 3;
public static void main(String args[]) throws Exception
{
LocalDate now = LocalDate.now();
int dateDifference = 0;
// load in the existing data
data = new Food(programName);
data.loadFood(programName);
// test to see if data is up to date. Add days if not
dateDifference = Math.abs((int)ChronoUnit.DAYS.between(now, data.day[0].date));
if ( dateDifference != 0)
{
data.adjustToToday(dateDifference, programName);
}
/////////////////////////////////////////////////
// create the GUI and switch running over to it.
/////////////////////////////////////////////////
Fud fud = new Fud();
Class<? extends Fud> fudClass = fud.getClass();
String className = fudClass.getName();
System.out.println("fudClass getname returns " + className);
URL testURL = fudClass.getResource("prev.png");
System.out.println("fudClass getResource returned " + testURL);
// Create GUI and turn the control over to it
javax.swing.SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
URL[] iconURL = new URL[4];
iconURL[prev] = Fud.class.getResource("prev.png");
iconURL[next] = Fud.class.getResource("next.png");
iconURL[plus] = Fud.class.getResource("plus.png");
iconURL[minus] = Fud.class.getResource("minus.png");
createAndShowGUI(fud, iconURL);
}
}
);
} // end of main
.
.
.
Rest of methods and subroutines needed
.
.
.
}
When run, the code returns the following results:
fudClass getname returns localhost.system1.Fud
fudClass getResource returned null
This has me quite frustrated. No matter what I try (and I have tried a number of things) the result remains the same. I keep getting NULL for a response from the getResource method. When I query the jar file with jar -tf Fud.jar I get the following:
jar tf Fud.jar
META-INF/MANIFEST.MF
localhost/
localhost/system1/
localhost/system1/Day.class
localhost/system1/Food.class
localhost/system1/Fud$1.class
localhost/system1/Fud$2.class
localhost/system1/Fud$3.class
localhost/system1/Fud$4.class
localhost/system1/Fud$5.class
localhost/system1/Fud$6.class
localhost/system1/Fud$7.class
localhost/system1/Fud.class
minus.png
next.png
plus.png
prev.png
So the icons are in the Jar file. Can anyone tell me what I am doing wrong? In Eclipse, my project explorer looks like:eclipse Project Explorer
I added the Image directory to my project Java build in eclipse as follows: Eclipse Java Build
I built the program using Eclipse Version: 2021-12 (4.22.0) Build id: 20211202-1639. Furthermore, I am using Java 17.0.1 2021-10-19 LTS on Windows 11 Pro build 22000.434.
You have to add a slash in front of the resource:
Fud.class.getResource("/prev.png");
otherwise java searching in the same folder as the class is located,
so it will search in localhost/system1

Java-wrapped Matlab function: `java` can't load/find `main` sample invoker class

Java-wrapped Matlab function: java can't load/find main sample invoker class
I'm following a MATLAB example of wrapping a MATLAB function in a Java interface. The sample driver (i.e., invoker of the wrapped function) compiles without errors or any messages, but java says that it can't find/load the main class, i.e., the sample driver.
The MATLAB function to be wrapped is exactly as it is on the web page (and in fact, it comes with the MATLAB installation):
" makesqr.m
"----------
function y = makesqr(x)
y = magic(x);
The sample invoker is extremely simple:
" makesqrSample1.m
"-----------------
% Sample script to demonstrate execution of function y = makesqr(x)
x = 3; % Initialize x here
y = makesqr(x);
Everything is exactly as shown in the webpage. I get all the files described in this file summary.
Things start to depart from expected in the "Install and Implement MATLAB Generated Java Application" section. Step 3 refers to a sample invoker getmagic.java instead of the makesqrSample1.java (automagically generated by MATLAB from makesqrSample1.m above). I assume that this is a typo.
With makesqr.jar and makesqrSample1.java in the same (current working) directory, the following compilation issues no messages or errors.
javac -cp \
"makesqr.jar;C:\Program Files\MATLAB\R2019a\toolbox\javabuilder\jar\javabuilder.jar" \
makesqrSample1.java
This creates makesqrSample1.class in the same folder. Here is the error from execution:
java -cp \
"makesqr.jar;C:\Program Files\MATLAB\R2019a\toolbox\javabuilder\jar\javabuilder.jar" \
makesqrSample1
Error: Could not find or load main class makesqrSample1
I checked that the that auto-generated makesqrSample1.java does have main (see ANNEX below).
This is a minimal example, following the documentation faithfully. What is causing main to not be recognized?
CONTEXTUAL DETAILS
Version output (select details):
MATLAB Version: 9.6.0.1072779 (R2019a)
Operating System: Microsoft Windows 10 Pro Version 10.0 (Build 18362)
Java Version: Java 1.8.0_181-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
MATLAB Compiler Version 7.0.1 (R2019a)
MATLAB Compiler SDK Version 6.6.1 (R2019a)
Installed JDK:
C:\Program Files\AdoptOpenJDK\jdk-8.0.265.01-hotspot
Since I have MATLAB installed, I didn't get the MATLAB Runtime (and from past experience, it has never been clear how/whether the Runtime is being used when MATLAB is installed). The the problem is occurring right up front finding/loading main.
ANNEX: AUTO-GENERATED makesqrSample1.java
import com.mathworks.toolbox.javabuilder.*;
import makesqr.Class1;
/**
*
* Sample driver code that is integrated with a compiled MATLAB function
* generated by MATLAB Compiler SDK.
*
* Refer to the MATLAB Compiler SDK documentation for more
* information.
*
* #see com.mathworks.toolbox.javabuilder.MWArray
*
*/
public class makesqrSample1 {
private static Class1 class1Instance;
private static void setup() throws MWException {
class1Instance = new Class1();
}
/**
* Sample code for {#link Class1#makesqr(int, Object...)}.
*/
public static void makesqrExample() {
MWArray xIn = null;
MWNumericArray yOut = null;
Object[] results = null;
try {
double xInData = 3.0;
xIn = new MWNumericArray(xInData, MWClassID.DOUBLE);
results = class1Instance.makesqr(1, xIn);
if (results[0] instanceof MWNumericArray) {
yOut = (MWNumericArray) results[0];
}
System.out.println(yOut);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Dispose of native resources
MWArray.disposeArray(xIn);
MWArray.disposeArray(results);
}
}
public static void main(String[] args) {
try {
setup();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
makesqrExample();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// Dispose of native resources
class1Instance.dispose();
}
}
}
This answer is definitely for the Java newbies. The class path for java needs to include the directory . of the newly-compiled makesqrSample1.class:
java -cp \
"makesqr.jar;C:\Program Files\MATLAB\R2019a\toolbox\javabuilder\jar\javabuilder.jar;." \
makesqrSample1
Running C:\cygwin64\tmp\User.Name\mcrCache9.6\makesq0\makesqr\startup
8 1 6
3 5 7
4 9 2
What I find odd is that this java is a Windows installation, yet it seems to recognize that I'm invoking it from Cygwin, and it creates a working folder in C:\cygwin64\tmp\User.Name.

netbeans makefile java execution

Here I have attached the source code and make file of it.
I use netbeans. How should I build my project to execute this java code in netbeans. please help me with detailed steps. I am new to netbeans and java.
I use netbeans 8.0.2 for windows 10 64 bit OS.
Source code:
package net.sourceforge.jpcap.tutorial.example15;
import net.sourceforge.jpcap.capture.*;
import net.sourceforge.jpcap.net.*;
/*
* This example utilizes the endCapture() feature.
*/
public class Example15 {
private static final int INFINITE = -1;
private static final int PACKET_COUNT = INFINITE;
// BPF filter for capturing any packet
private static final String FILTER = "";
private PacketCapture m_pcap;
private String m_device;
public Example15() throws Exception {
// Step 1: Instantiate Capturing Engine
m_pcap = new PacketCapture();
// Step 2: Check for devices
m_device = m_pcap.findDevice();
// Step 3: Open Device for Capturing (requires root)
m_pcap.open(m_device, true);
// Step 4: Add a BPF Filter (see tcpdump documentation)
m_pcap.setFilter(FILTER, true);
// Step 5: Register a Listener for Raw Packets
m_pcap.addRawPacketListener(new RawPacketHandler(m_pcap));
// Step 6: Capture Data (max. PACKET_COUNT packets)
m_pcap.capture(PACKET_COUNT);
}
public static void main(String[] args) {
try {
Example15 example = new Example15();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
class RawPacketHandler implements RawPacketListener
{
private static int m_counter = 0;
private PacketCapture m_pcap = null;
public RawPacketHandler(PacketCapture pcap) {
m_counter = 0;
m_pcap = pcap;
}
public synchronized void rawPacketArrived(RawPacket data) {
m_counter++;
System.out.println("Packet " + m_counter + "\n" + data + "\n");
if(condition())
m_pcap.endCapture();
}
private boolean condition() {
return (m_counter == 5) ? true : false;
}
}
make file:
# $Id: makefile,v 1.1 2002/07/10 23:05:26 pcharles Exp $
#
# package net.sourceforge.jpcap.tutorial.example15
#
PKG = net.sourceforge.jpcap.tutorial.example15
PKG_DIR = $(subst .,/, $(PKG))
REL = ../../../../..
include ${MAKE_HOME}/os.makefile
include ${MAKE_HOME}/rules.makefile
JAVA = \
Example15
JAVA_SOURCE = $(addsuffix .java, $(JAVA))
JAVA_CLASSES = $(addsuffix .class, $(JAVA))
all: $(JAVA_CLASSES)
include ${MAKE_HOME}/targets.makefile
include ${MAKE_HOME}/depend.makefile
Netbeans uses Makefiles for C++ code but not for Java code. It is easy to get this code to build but there is no need for the Makefile.
File -> New Project
Select Category Java on the left and "Java Application with Existing Sources" (with this option the project and sources will be in different directories) on the right.
Click Next
Change the Project name and/or directory to create the project in.
Add the original source directory in the dialog.
Click Finish to Create the project.
Within netbeans you can now use the Run-> Build Project to build it.
If you really have to have a Makefile just make one that just runs the Netbeans project( which is actually an ant project).
eg.
build:
ant jar

Java grph library: Exception on toools.os.OperatingSystem.getLocalOS()

I'm using grph library for a university project (www.i3s.unice.fr/~hogie/grph/)
but i have a problem only on Linux with that library, when i create a new Graph object, i receive the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.elendev.wesproject.graph.GraphFactory.main(GraphFactory.java:19)
Caused by: java.lang.NullPointerException
at toools.os.OperatingSystem.getLocalOS(OperatingSystem.java:47)
at grph.Grph.setCompilationDirectory(Grph.java:353)
at grph.Grph.<clinit>(Grph.java:246)
... 1 more
I tried to call directly getLocalOS function, with:
System.out.println(toools.os.OperatingSystem.getLocalOS());
and i receive the same exception. I cannot find information about that library, and the project launched on a macbook works perfectly.
The operating system i'm currently using is gentoo linux 32bit.
And the jdk version is: 1.7.0_65
Any idea of what could be the problem?
Not sure whether this can count as an answer, but it could at least help to solve the issue:
The exception comes from the toools.os.OperatingSystem.getLocalOS method. Although the .JAR file from the website that you mentioned has a whopping 39 megabytes, the source code of this class is not contained in it.
There seems to be no information available about this class at all. Neither Google nor Maven finds anything related to the toools package. One has to assume that it is an abandoned utility class that passed away a long time ago.
However, the method in question can be disassembled to the following code:
public static OperatingSystem getLocalOS()
{
if (localOS == null)
{
if (new RegularFile("/etc/passwd").exists())
{
if (new Directory("/proc").exists())
{
if (new RegularFile("/etc/fedora-release").exists()) {
localOS = new FedoraLinux();
} else if (ExternalProgram.commandIsAvailable("ubuntu-bug")) {
localOS = new UbuntuLinux();
} else {
localOS = new Linux();
}
}
else if (new Directory("/Applications").exists()) {
localOS = new MacOSX();
} else {
localOS = new Unix();
}
}
else if (System.getProperty("os.name").startsWith("Windows")) {
localOS = new Windows();
} else {
localOS = new OperatingSystem();
}
localOS.name = System.getProperty("os.name");
localOS.version = System.getProperty("os.version");
}
return localOS;
}
From this, you can possibly derive the conditions that must be met in order to properly detect your OS as a linux OS. Particularly, when there is a file named /etc/passwd, and a directory /proc, this should be sufficient to identify the OS as a Linux. You may want to give it a try...

Can Java launch the Windows UAC?

As the title says, I'm wondering if it is possible for a program written in Java (and only java) to relaunch himself (preferably a .jar) with administrator privileges, showing in the way the native Windows UAC (in order to make it more trustable for the user), i did my homework and found out that it is possible to accomplish this using bridges between c++ and java, but i would really like to do this as a pure java project.
P.S: In the remote case that this result to be impossible, can someone show me the "easy" way to do this using another language (i mean, I've found tutorials, but they are to complicated for something I think it should not be that complicated).
P.S2: In case it is possible to accomplish this, would it work, on other platforms (OS X, Linux)
It cannot be done in pure java.
Best bet would be to write this to a file:
#echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
#echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
#echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
#cscript %temp%\sudo.tmp.vbs
and save it as something.bat in Windows temp directory (as we have access to this).
You would then execute this from your application using Runtime or ProcessBuilder and exit your application (System.exit(0);).
You should add an immediate start up check to your application that checks if the program has elevation, if it has proceed if not re-run the batch and exit.
Here is an example I made (this must be run when compiled as a Jar or it wont work):
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
*
* #author David
*/
public class UacTest {
public static String jarName = "UacTest.jar", batName = "elevate.bat";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (checkForUac()) {//uac is on
JOptionPane.showMessageDialog(null, "I am not elevated");
//attempt elevation
new UacTest().elevate();
System.exit(0);
} else {//uac is not on
//if we get here we are elevated
JOptionPane.showMessageDialog(null, "I am elevated");
}
}
private static boolean checkForUac() {
File dummyFile = new File("c:/aaa.txt");
dummyFile.deleteOnExit();
try {
//attempt to craete file in c:/
try (FileWriter fw = new FileWriter(dummyFile, true)) {
}
} catch (IOException ex) {//we cannot UAC muts be on
//ex.printStackTrace();
return true;
}
return false;
}
private void elevate() {
//create batch file in temporary directory as we have access to it regardless of UAC on or off
File file = new File(System.getProperty("java.io.tmpdir") + "/" + batName);
file.deleteOnExit();
createBatchFile(file);
runBatchFile();
}
private String getJarLocation() {
return getClass().getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);
}
private void runBatchFile() {
//JOptionPane.showMessageDialog(null, getJarLocation());
Runtime runtime = Runtime.getRuntime();
String[] cmd = new String[]{"cmd.exe", "/C",
System.getProperty("java.io.tmpdir") + "/" + batName + " java -jar " + getJarLocation()};
try {
Process proc = runtime.exec(cmd);
//proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createBatchFile(File file) {
try {
try (FileWriter fw = new FileWriter(file, true)) {
fw.write(
"#echo Set objShell = CreateObject(\"Shell.Application\") > %temp%\\sudo.tmp.vbs\r\n"
+ "#echo args = Right(\"%*\", (Len(\"%*\") - Len(\"%1\"))) >> %temp%\\sudo.tmp.vbs\r\n"
+ "#echo objShell.ShellExecute \"%1\", args, \"\", \"runas\" >> %temp%\\sudo.tmp.vbs\r\n"
+ "#cscript %temp%\\sudo.tmp.vbs\r\n"
+ "del /f %temp%\\sudo.tmp.vbs\r\n");
}
} catch (IOException ex) {
//ex.printStackTrace();
}
}
}
Use a batch file and the runas command.
I doubt "only Java". At best you would have to have a JNI wrapper around the MSFT module. Unless just invoking the exe using ProcessBuilder counts as "only Java" -- your code to bring up the user console would be only Java but not what it invokes. IOW, Win does not come with a Java API
To relaunch your application elevated, you have to call ShellExecute or ShellExecuteEx function from Windows API and use runas verb.
You can use these API in pure Java with JNA library.
To relaunch yourself, you would have to know the full path to java.exe or javaw.exe, the command-line parameters (class path, if any, and the path to your jar). Obviously you can get this information by using Windows API.
What do you mean by remote case?
You cannot start remote elevated process this way.
You can re-launch your application elevated from a network share. Yet it won't work with mapped drives: after elevation there's no access to user's mapped drives.
No, this can't work on other platforms. UAC is a Windows feature. It's similar to sudo in Linux in some ways, so for Linux you can use sudo $pathtojava/java.exe <yourparameters>. However this won't work nicely if your application is not started from a console. Window Managers usually have wrappers which prompt for password in a GUI dialog.
Just do this with Hackaprofaw (v29). Also it was released in 2002 and started development in 1997 soooooo ye. in 2021 its on version 29.10.7 but-
if raw ram = 0
disable "featureII" program = "JAVA(math = any)"
run on "Hackaprofaw (math = v29(x))
when "featureII" disabled
end

Categories

Resources