Java CPLEX Concert UnsatisfiedLinkError - java

I am trying to use cplex in java using eclipse IDE on Ubuntu 16.4
and I am getting an exception "UnsatisfiedLinkError" as follows
Does anybody have an idea how to overcome this exception?
Exception in thread "main" java.lang.UnsatisfiedLinkError: 'void ilog.concert.cppimpl.concert_wrapJNI.swig_module_init()'
at ilog.concert.cppimpl.concert_wrapJNI.swig_module_init(Native Method)
at ilog.concert.cppimpl.concert_wrapJNI.<clinit>(concert_wrapJNI.java:1619)
at ilog.concert.cppimpl.IloEnv.<init>(IloEnv.java:49)
at ilog.opl.IloOplFactory.<init>(IloOplFactory.java:84)
at cplex.Mulprod.main(Mulprod.java:15)
I am using the following example provided by ensta-paris Java version of mulprod.cpp of OPL distrib
import ilog.concert.*;
import ilog.opl.*;
import ilog.opl.IloCplex;
public class Mulprod {
static final String DATADIR = ".";
static public void main(String[] args) throws Exception {
int status = 127;
try {
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource(DATADIR + "/mulprod.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(DATADIR + "/mulprod.dat");
opl.addDataSource(dataSource);
opl.generate();
if (cplex.solve()) {
System.out.println("OBJECTI " + opl.getCplex().getObjValue());
opl.postProcess();
opl.printSolution(System.out);
} else {
System.out.println("No solution!");
}
oplF.end();
status = 0;
} catch (IloOplException ex) {
System.err.println("### OPL excepti " + ex.getMessage());
ex.printStackTrace();
status = 2;
} catch (IloException ex) {
System.err.println("### CONCERT excepti " + ex.getMessage());
ex.printStackTrace();
status = 3;
} catch (Exception ex) {
System.err.println("### UNEXPECTED UNKNOWN ERROR ...");
ex.printStackTrace();
status = 4;
}
System.exit(status);
}
}
my VM arguments in run configuration are
-Djava.library.path=[cplexStudioPath]/cplex/bin/x86-64_linux:[cplexStudioPath]/opl/bin/x86-64_linux

You also have to set the LD_LIBRARY_PATH environment variable so that it includes the OPL directory (which you also specified in java.library.path).
Also note that specifying the CPLEX directory in java.library.path is not required. I recommend removing it since you don't want libraries to get loaded from this place. You only want the libraries from the OPL directory (the required CPLEX libraries are there as well).

Related

Call SAP methods from Java

I am trying to make a connection with the sap systems and I have all the connection properties which are required in order to do so.
I am trying my best but I am facing some issues I have no idea how to resolve.
All I need is a simple code example by which I will be able to integrate my java app with the sap systems.
I have gone through some websites but could not find a solution for making the connection with the sap system.
I am trying with the below code but i do not know that what to write inside createDataFile method.
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoDestinationManager;
import java.util.Properties;
public class TestMySAP {
public static void main(String[] args) {
// This will create a file called mySAPSystem.jcoDestination
String DESTINATION_NAME1 = "mySAPSystem";
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "10.129.19.151"); //host
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "00"); //system number
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "442"); //client number
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "MPOSRFC");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "123456");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDataFile(DESTINATION_NAME1, connectProperties);
// This will use that destination file to connect to SAP
try {
JCoDestination destination = JCoDestinationManager.getDestination("mySAPSystem");
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
destination.ping();
} catch (JCoException e){
e.printStackTrace();
}
}
}
Related to the second part of your question in the comments, for BAPI functions you can try the following snippet:
public static void getCompanyCodes throws JCoException {
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
JCoFunction function = destination.getRepository().getFunction("BAPI_COMPANYCODE_GETLIST");
if (function == null)
throw new RuntimeException("Function not found in SAP.");
try {
function.execute(destination);
} catch (AbapException e) {
System.out.println(e.toString());
return;
}
JCoStructure returnStructure = function.getExportParameterList().getStructure("RETURN");
if (!(returnStructure.getString("TYPE").equals("") || returnStructure.getString("TYPE").equals("S"))) {
throw new RuntimeException(returnStructure.getString("MESSAGE"));
}
JCoTable codes = function.getTableParameterList().getTable("COMPANYCODE_LIST");
for (int i = 0; i < codes.getNumRows(); i++) {
codes.setRow(i);
System.out.println(codes.getString("COMP_CODE") + '\t' + codes.getString("COMP_NAME"));
}
}
You can find a list of BAPI functions here: http://www.sapnet.ru/m/list_BAPI.html

java class not compiling code via cmd

I have a Java Class Called Listenermain.java which has dependencies on external libraries the class is a s below.
import Luxand.FSDK;
import php.java.bridge.JavaBridgeRunner;
public class Listenermain {
public static final String JAVABRIDGE_PORT = "1699";//8080
static final JavaBridgeRunner runner
= JavaBridgeRunner.getInstance(JAVABRIDGE_PORT);
/**
* #param args the command line arguments
*
*/
public static void main( String[] args ) {
// TODO code application logic here
try {
System.loadLibrary("facesdk");
int res = FSDK
.ActivateLibrary("pZo9jhbhbybgvbh");
FSDK.Initialize();
FSDK.SetFaceDetectionParameters(true, true, 384);
FSDK.SetFaceDetectionThreshold(5);
if (res == FSDK.FSDKE_OK) {
System.out.printf("FaceSDK activated", "FaceSDK activated\n");
} else {
System.out.printf("Error activating FaceSDK: ", res + "\n");
}
} catch (java.lang.UnsatisfiedLinkError e) {
System.out.printf("exception ", e.getMessage());
}
try {
runner.waitFor();
} catch (Exception ex) {
System.out.printf("Error: ", ex.getMessage() + "\n");
}
// System.exit(0);
}
}
I compile my class with following on cmd line syntax
javac -classpath ".;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\JavaBridge.jar;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\FaceSDK.jar;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\jna.jar" Listenermain.java
and it doesn't spit any errors, but when I try to run the code via command line interface again with this syntax
`java -classpath . Listenermain`
I get the error below
Exception in thread "main" java.lang.NoClassDefFoundError: php/java/bridge/JavaBridgeRunner at Listenermain.(Listenermain.java:19)
Caused by: java.lang.ClassNotFoundException: php.java.bridge.JavaBridgeRunner
So am confused as to why the Listenermain.class wasn't compiled with the dependencies I specified.
When you run the program, you also need to specify the classpath to resolve class dependencies.
Try like that :
java -classpath ".;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\JavaBridge.jar;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\FaceSDK.jar;C:\Users\daviestobialex\Workarea\openshiftmatcher\libs\jna.jar" Listenermain

Java RMI ClassNotFound exception

I decided to write RMI (from the book) took code from the book too. i created the Stub with rmic, and started rmiregistry but when i dedided to write java Start Server i got the problem, actually here is my problem i faced with:
java -classpath D:\RMI AddServer
Exception:java.rmi.ServerException: RemoteException occurred in server thread; n
ested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: AddServerImpl_Stub
PLease i need help, i lost lot of time because of this :(
AddServerIntf.java
package rmi.app;
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1,double d2) throws RemoteException;}
AddServerImpl
package rmi.app;
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {
public AddServerImpl() throws RemoteException {}
public double add(double d1, double d2) throws RemoteException {
return d1+d2;
}
}
AddServer
package rmi.app;
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String[] args) {
try {
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch (Exception e){
System.out.println("Exception:"+e);
}
}
}
AddClient
package rmi.app;
import java.rmi.Naming;
public class AddClient {
public static void main(String[] args) {
try{
String addServerURL= "rmi://"+args[0]+ "/AddServer";
AddServerIntf addServer =(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is:"+args[1]);
double d1= Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is:"+args[2]);
double d2= Double.valueOf(args[2]).doubleValue();
System.out.println("the sum is:"+ addServer.add(d1,d2));
}
catch(Exception e){
System.out.println("Exception : "+ e);
}
}
}
I am writing a Java RMI application too and I went through a lot before being able to make it work. After a lot of research and try and error I got this "recipe":
Don't install SecurityManager;
Don't use policy files;
Make sure the classes you're moving from one VM to another are in
both client and server classpath (or in the same jar/war).
If you're using hibernate to make database access, put the jars in the
client too. Hibernate "changes" the original classes and the client
will need this to deserialize it;
If you're also using Spring on the server side you might include the spring-orm and spring-data-jpa jars in the client, if you experience ClassNotFoundException followed by JpaObjectRetrievalFailureException;
I am not running anything outside the jars (no rmi services at all);
I didn't create the stubs as I am using Java 6.
My server is purely doing this:
try {
try {
LocateRegistry.createRegistry(SERVER_PORT);
} catch (RemoteException e) {
LocateRegistry.getRegistry(SERVER_PORT);
e.printStackTrace();
}
System.setProperty("java.rmi.server.hostname", SERVER_HOST);
connectionRequestHandler = new ConnectionRequestHandlerImpl();
dataRequestHandler = new DataRequestHandlerImpl();
String rmiUrl = "rmi://" + SERVER_HOST + ":" + SERVER_PORT + "/";
Naming.rebind(rmiUrl + "ConnectionRequestHandler", connectionRequestHandler);
Naming.rebind(rmiUrl + "DataRequestHandler", dataRequestHandler);
} catch (RemoteException e1) {
e1.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Then on client I am doing:
String rmiUrl = "rmi://" + SERVER_HOST + ":" + SERVER_PORT + "/";
try {
connectionRequestHandler = (ConnectionRequestHandler)Naming.lookup(rmiUrl + "ConnectionRequestHandler");
dataRequestHandler = (DataRequestHandler)Naming.lookup(rmiUrl + "DataRequestHandler");
} catch (MalformedURLException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (RemoteException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (NotBoundException e) {
throw new RmiServicesDownException(e.getMessage());
} catch (Exception e ){
e.printStackTrace();
return;
}
This is how it's working for me. Any other problems you may have are easy to solve compared to the first setup.
Short answer: the registry needs to have the stubs on its classpath.
Long answer: find an rmi tutorial from within the last 10 years which doesn't use rmic, cause you haven't need to do all that for a long time.
Change the AddServerImpl constructor to call super(0). Then you don't even need to generate a stub, let alone deploy it. See the preamble to the Javadoc of UnicastRemoteObject.
start rmiregistry from the server code directory. (or) Execute with -j option Please refer How do I set the classpath that rmiregistry uses? and javadoc reference [here]

SVN Commit Log Issue

I am currently working on a project about calculations.I have done the main part of my project,Also integrated SVN Commit function to my code (using .ini file to read the specific address etc. )
I can easily Commit the files, what I am trying is I want to implement the real-time log to my console. Is there any way to implement the log to the console ? Not the general log but the commit log which should be real time.
I am using eclipse for mac, I've heard about SVNKit but I am really poor about SVN.
Thanks in advance for any information
--- EDIT ---
This is the code for reading the svn commands from .ini file
public static String iniSVNOkut(String deger, String getObje, String fetchObje){
Ini uzantilariAlIni = null;
try
{
String uzantiAyarlari = "Uzantilar.ini";
try
{
uzantilariAlIni = new Ini(new FileReader(uzantiAyarlari));
}
catch (InvalidFileFormatException e)
{
System.err.print("Hata InvalidFileFormat : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch(FileNotFoundException e)
{
System.err.print("Hata FileNotFoundException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch (IOException e)
{
System.err.print("Hata IOException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
return deger = uzantilariAlIni.get(getObje).fetch(fetchObje);
}
finally
{
}
}
This is what .ini includes
[svnAdresi]
svnAdresiniAl = svn co http://svn.svnkit.com/repos/svnkit/trunk/ /Users/sample/Documents/workspace/SatirHesaplaGUI/svnTestMAC
This is how I call it
String svnAdresi;
svnAdresi = IniFonksiyon.iniSVNOkut(svnAdresi, "svnAdresi", "svnAdresiniAl");
Runtime cmdCalistir = Runtime.getRuntime();
try
{
Process islem = cmdCalistir.exec(svnAdresi);
}
catch (Exception e)
{
e.printStackTrace();
}
If I understand your question correctly, you want to read the Subversion commit log into your console application.
The easiest way is to use SVNKit.
Here's how I did it.
private static List<SVNLogEntry> logEntryList;
/*
* Gets the Subversion log records for the directory
*/
LogHandler handler = new LogHandler();
String[] paths = { directory };
try {
repository.log(paths, latestRevision, 1L, false, true, handler);
} catch (SVNException svne) {
if (svne.getMessage().contains("not found")) {
logEntryList = new ArrayList<SVNLogEntry>();
} else {
CobolSupportLog.logError(
"Error while fetching the repository history: "
+ svne.getMessage(), svne);
return false;
}
}
logEntryList = handler.getLogEntries();
directory - string pointing to a particular directory or module
latestRevision - largest revision number from Subversion. Placing the latestRevision second in the log method invocation returns the log records in most recent order.
If you want the log records in sequential order, from 1 to latestRevision, then the 1L would be placed second, and the latestRevision would be placed third.
repository - Subversion repository that you've already authenticated.
Here's LogHandler.
public class LogHandler implements ISVNLogEntryHandler {
protected static final int REVISION_LIMIT = 5;
protected List<SVNLogEntry> logEntryList;
public LogHandler() {
logEntryList = new ArrayList<SVNLogEntry>();
}
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
logEntryList.add(logEntry);
}
public List<SVNLogEntry> getLogEntries() {
if (logEntryList.size() <= REVISION_LIMIT) {
return logEntryList;
} else {
return logEntryList.subList(0, REVISION_LIMIT);
}
}
}

Find the directory for a FileStore

I'm trying to find a way to detect when a flash drive has been plugged into my computer. So far, the solution I found was to poll FileSystem#getFileStores for changes. This does indeed tell me when the flash drive has been inserted, but as far as I can tell there is no way to retrieve the location for it. FileStore#type and FileStore#name both seem highly unreliable as their return value is implementation specific, but they appear to be the only methods that might return any relevant information that might help find the directory for the FileStore.
With that in mind, the following code:
public class Test {
public static void main(String[] args) throws IOException {
for (FileStore store : FileSystems.getDefault().getFileStores()) {
System.out.println(store);
System.out.println("\t" + store.name());
System.out.println("\t" + store.type());
System.out.println();
}
}
}
Gave me this output:
/ (/dev/sda5)
/dev/sda5
ext4
/* snip */
/media/TI103426W0D (/dev/sda2)
/dev/sda2
fuseblk
/media/flashdrive (/dev/sdb1)
/dev/sdb1
vfat
As it turns out, FileStore#type returns the format of the drive and FileStore#name returns the location of the device file for the drive. As far as I can tell, the only method which has the location of the drive is the toString method, but extracting the path name out of it seems dangerous because I'm not sure how well that particular solution would hold up on other operating systems and future versions of Java.
Is there something I'm missing here or is this simply not possible purely with Java?
System Information:
$ java -version
java version "1.7.0_03"
OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu2)
OpenJDK Client VM (build 22.0-b10, mixed mode, sharing)
$ uname -a
Linux jeffrey-pc 3.2.0-24-generic-pae #37-Ubuntu SMP Wed Apr 25 10:47:59 UTC 2012 i686 athlon i386 GNU/Linux
Here's a temporary work around until a better solution is found:
public Path getRootPath(FileStore fs) throws IOException {
Path media = Paths.get("/media");
if (media.isAbsolute() && Files.exists(media)) { // Linux
try (DirectoryStream<Path> stream = Files.newDirectoryStream(media)) {
for (Path p : stream) {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
}
}
} else { // Windows
IOException ex = null;
for (Path p : FileSystems.getDefault().getRootDirectories()) {
try {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
} catch (IOException e) {
ex = e;
}
}
if (ex != null) {
throw ex;
}
}
return null;
}
As far as I know, this solution will only work for Windows and Linux systems.
You have to catch the IOException in the Windows loop because if there is no CD in the CD drive an exception is thrown when you try to retrieve the FileStore for it. This might happen before you iterate over every root.
This is what I have ended up doing. This is limited to Windows + UNIX but avoids using external tools or additional library calls. It steals the information Java already has in the FileStore objects
LinuxFileStore definitely extends UnixFileStore, so it will work. Same deal for Solaris. Since Mac OS X is UNIX, it probably works there but I'm not sure because I couldn't see its subclass in any place I was looking.
public class FileStoreHacks {
/**
* Stores the known hacks.
*/
private static final Map<Class<? extends FileStore>, Hacks> hacksMap;
static {
ImmutableMap.Builder<Class<? extends FileStore>, Hacks> builder =
ImmutableMap.builder();
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.WindowsFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new WindowsFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on Windows.
}
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.UnixFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new UnixFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on UNIX.
}
hacksMap = builder.build();
}
private FileStoreHacks() {
}
/**
* Gets the path from a file store. For some reason, NIO2 only has a method
* to go in the other direction.
*
* #param store the file store.
* #return the path.
*/
public static Path getPath(FileStore store) {
Hacks hacks = hacksMap.get(store.getClass());
if (hacks == null) {
return null;
} else {
return hacks.getPath(store);
}
}
private static interface Hacks {
Path getPath(FileStore store);
}
private static class WindowsFileStoreHacks implements Hacks {
private final Field field;
public WindowsFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("root");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
String root = (String) field.get(store);
return FileSystems.getDefault().getPath(root);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
private static class UnixFileStoreHacks implements Hacks {
private final Field field;
private UnixFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("file");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
return (Path) field.get(store);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
}
I've not really explored this area of java, but I found this, which seems to be related. It uses File.listRoots()
There also seems to be a number of related questions linked there too.
This works for Windows:
public Path getFileStoreRootPath(FileStore fs) throws Exception {
for (Path root : FileSystems.getDefault().getRootDirectories()) {
if (Files.isDirectory(root) && Files.getFileStore(root).equals(fs)) {
return root;
}
}
throw new RuntimeException("Root directory for filestore " + fs + " not found");
}
Basically, by filtering by condition Files.isDirectory(root) we are excluding all CD/DVD drives which will throw IOException when compact-disc is not inserted.

Categories