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
Related
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).
so i have problem where i am trying to open a file through my own written virtual machine object in java but the problem is that the virtual machine is not running and causing an error.
Error: Could not find or load main class C:\Users\dell\Trace\Main.java
we also tried modifying the CLASSPATH & PATH with no success
below is the code of the main
import com.sun.jdi.Bootstrap;
import com.sun.jdi.connect.*;
import java.util.Map;
import java.util.List;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Trace {
// Running remote VM
private final VirtualMachine vm;
// Thread transferring remote error stream to our error stream
private Thread errThread = null;
// Thread transferring remote output stream to our output stream
private Thread outThread = null;
// Mode for tracing the Trace program (default= 0 off)
private int debugTraceMode = 0;
// Do we want to watch assignments to fields
private boolean watchFields = false;
// Class patterns for which we don't want events
private String[] excludes = {"java.*", "javax.*", "sun.*",
"com.sun.*"};
/**
* main
*/
public static void main(String[] args) {
new Trace(args);
}
/**
* Parse the command line arguments.
* Launch target VM.
* Generate the trace.
*/
Trace(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
int inx;
for (inx = 0; inx < args.length; ++inx) {
String arg = args[inx];
if (arg.charAt(0) != '-') {
break;
}
if (arg.equals("-output")) {
try {
writer = new PrintWriter(new FileWriter(args[++inx]));
} catch (IOException exc) {
System.err.println("Cannot open output file: " + args[inx]
+ " - " + exc);
System.exit(1);
}
} else if (arg.equals("-all")) {
excludes = new String[0];
} else if (arg.equals("-fields")) {
watchFields = true;
} else if (arg.equals("-dbgtrace")) {
debugTraceMode = Integer.parseInt(args[++inx]);
} else if (arg.equals("-help")) {
usage();
System.exit(0);
} else {
System.err.println("No option: " + arg);
usage();
System.exit(1);
}
}
if (inx >= args.length) {
System.err.println("<class> missing");
usage();
System.exit(1);
}
StringBuffer sb = new StringBuffer();
sb.append(args[inx]);
for (++inx; inx < args.length; ++inx) {
sb.append(' ');
sb.append(args[inx]);
}
vm = launchTarget(sb.toString());
generateTrace(writer);
}
/**
* Generate the trace.
* Enable events, start thread to display events,
* start threads to forward remote error and output streams,
* resume the remote VM, wait for the final event, and shutdown.
*/
void generateTrace(PrintWriter writer) {
vm.setDebugTraceMode(debugTraceMode);
EventThread eventThread = new EventThread(vm, excludes, writer);
eventThread.setEventRequests(watchFields);
eventThread.start();
redirectOutput();
vm.resume();
// Shutdown begins when event thread terminates
try {
eventThread.join();
errThread.join(); // Make sure output is forwarded
outThread.join(); // before we exit
} catch (InterruptedException exc) {
// we don't interrupt
}
writer.close();
}
/**
* Launch target VM.
* Forward target's output and error.
*/
VirtualMachine launchTarget(String mainArgs) {
LaunchingConnector connector = findLaunchingConnector();
Map arguments = connectorArguments(connector, mainArgs);
try {
return connector.launch(arguments);
} catch (IOException exc) {
throw new Error("Unable to launch target VM: " + exc);
} catch (IllegalConnectorArgumentsException exc) {
throw new Error("Internal error: " + exc);
} catch (VMStartException exc) {
throw new Error("Target VM failed to initialize: " +
exc.getMessage());
}
}
void redirectOutput() {
Process process = vm.process();
// Copy target's output and error to our output and error.
errThread = new StreamRedirectThread("error reader",
process.getErrorStream(),
System.err);
outThread = new StreamRedirectThread("output reader",
process.getInputStream(),
System.out);
errThread.start();
outThread.start();
}
/**
* Find a com.sun.jdi.CommandLineLaunch connector
*/
LaunchingConnector findLaunchingConnector() {
List connectors = Bootstrap.virtualMachineManager().allConnectors();
Iterator iter = connectors.iterator();
while (iter.hasNext()) {
Connector connector = (Connector)iter.next();
if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
return (LaunchingConnector)connector;
}
}
throw new Error("No launching connector");
}
/**
* Return the launching connector's arguments.
*/
Map connectorArguments(LaunchingConnector connector, String mainArgs) {
Map arguments = connector.defaultArguments();
Connector.Argument mainArg =
(Connector.Argument)arguments.get("main");
if (mainArg == null) {
throw new Error("Bad launching connector");
}
mainArg.setValue(mainArgs);
if (watchFields) {
// We need a VM that supports watchpoints
Connector.Argument optionArg =
(Connector.Argument)arguments.get("options");
if (optionArg == null) {
throw new Error("Bad launching connector");
}
optionArg.setValue("-classic");
}
return arguments;
}
/**
* Print command line usage help
*/
void usage() {
System.err.println("Usage: java Trace <options> <class> <args>");
System.err.println("<options> are:");
System.err.println(
" -output <filename> Output trace to <filename>");
System.err.println(
" -all Include system classes in output");
System.err.println(
" -help Print this help message");
System.err.println("<class> is the program to trace");
System.err.println("<args> are the arguments to <class>");
}
}
Am running this command below in a shell script, it works on windows but can't identify why its not working in the sheell script in openshift. I have the .class files in that folder.
export JARPATH=$(JARS=("$LIB"/*.jar); IFS=:; echo "${JARS[*]}")
nohup javac -classpath $JARPATH $MATCHFACES/*.java > ${OPENSHIFT_DIY_LOG_DIR}/compile.log 2>&1 &
// the above works without errors
cd $OPENSHIFT_REPO_DIR"src/matchfaces"
nohup java -classpath $JARPATH matchfaces.Listener > ${OPENSHIFT_DIY_LOG_DIR}/Listener.log 2>&1 &
// the above spits the error below
The error I get is
Error: Could not find or load main class .var.lib.openshift.586b985a89r3cfe9fa1111bc.app-root.runtime.repo.src.matchfaces.Listener
Listener.java source code
package matchfaces;
import Luxand.FSDK;
/**
*
* #author daviestobialexz
*/
public class Listener {
public static final String JAVABRIDGE_PORT = "1699";//8080
static final php.java.bridge.JavaBridgeRunner runner =
php.java.bridge.JavaBridgeRunner.getInstance(JAVABRIDGE_PORT);
/**
* #param args the command line arguments
* #throws java.lang.InterruptedException
*/
public static void main( String[] args ) {
// TODO code application logic here
try {
System.loadLibrary("facesdk");
int res = FSDK.ActivateLibrary("OYVHSxkUjwoYalZqg=");
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 want compile Java program by making a Javac command in cmd using another Java program, then run it. How do I do that? Is there a class that i can use?
for example here is the cmd
C:\Users\UserName\Documents> Javac HelloWorld.java
How can i compile HelloWorld.java inside a java program, then run it.
Here is my initial source code wherein there is a directory and a Java file.
public class Test {
public static void main(String[] args) {
String directory = "C:\\Users\\UserName\\Documents";
String fileName = "HelloWorld.java";
}
}
Try this
try {
// Execute command
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("<execute the java class by mentioning the usual command>");
out.flush();
out.close();
} catch (IOException e) {
}
You probably want to compile the other source code first. The Java compiler is actually written in Java itself. You do not need to invoke the javac.exe, instead take a look at javax.tools.ToolProvider.getSystemJavaCompiler() ToolProvider Javadoc.
Once you compiled the source code file with that, you can use the class loader to load the compiler class file and invoke the code from there, probably by means of reflection.
Overall you are asking for an advanced use case.
if you want to compile different java files using this a program , you can try this method.
public class Laj {
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
public static void main(String[] args) {
try {
runProcess("javac YourDir/HelloWorld.java");
runProcess("java YourDir.HelloWorld");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class HelloWorld {
public static void main(String[] args) {
System.out.println("ok");
}
}
The goal is to have a simple Java class start a jar main-class. When the main-class finishes, it can be queried if it would like to be reloaded. By this method it can hot-update itself and re-run itself.
The Launcher is to load the jar via a URLClassloader and then unload/re-load the changed jar. The jar can be changed by a modification to Launcher, or by a provided dos/unix script that is called to swap the new jar into place of the old jar.
The entire program is below. Tested and it seems to work without a hitch.
java Launcher -jar [path_to_jar] -run [yourbatchfile] [-runonce]? optional]
1) Launcher looks for the "Main-Class" attribute in your jarfile so that it does not need to be giventhe actual class to run.
2) It will call 'public static void main(String[] args)' and pass it the remaining arguments that you provided on the command line
3) When your program finishes, the Launcher will call your programs method 'public static boolean reload()' and if the result is 'true' this will trigger a reload.
4) If you specified -runonce, then the program will never reload.
5) If you specified -run [batchfile] then the batchfile will run before reloading.
I hope this is helpful to some people.
Happy coding!
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class Launcher {
public static void main(String[] args) {
new Launcher().run(new ArrayList<>(Arrays.asList(args)));
}
private void run(List<String> list) {
final String jar = removeArgPairOrNull("-jar", list);
final boolean runonce = removeArgSingle("-runonce", list);
final String batchfile = removeArgPairOrNull("-run", list);
if (jar == null) {
System.out.println("Please add -jar [jarfile]");
System.out.println("All other arguments will be passed to the jar main class.");
System.out.println("To prevent reloading, add the argument to -runonce");
System.out.println("To provide another program that runs before a reload, add -run [file]");
}
boolean reload;
do {
reload = launch(list.toArray(new String[0]), new String(jar), new String(batchfile), new Boolean(runonce));
System.out.println("Launcher: reload is: " + reload);
gc();
if (reload && batchfile != null) {
try {
System.err.println("Launcher: will attempt to reload jar: " + jar);
runBatchFile(batchfile);
} catch (IOException | InterruptedException ex) {
ex.printStackTrace(System.err);
System.err.println("Launcher: reload batchfile had exception:" + ex);
reload = false;
}
}
} while (reload);
}
private boolean launch(String[] args, String jar, String batchfile, boolean runonce) {
Class<?> clazz = null;
URLClassLoader urlClassLoader = null;
boolean reload = false;
try {
urlClassLoader = new URLClassLoader(new URL[]{new File(jar).toURI().toURL()});
String mainClass = findMainClass(urlClassLoader);
clazz = Class.forName(mainClass, true, urlClassLoader);
Method main = clazz.getMethod("main", String[].class);
System.err.println("Launcher: have method: " + main);
Method reloadMethod;
if (runonce) {
// invoke main method using reflection.
main.invoke(null, (Object) args);
} else {
// find main and reload methods and invoke using reflection.
reloadMethod = clazz.getMethod("reload");
main.invoke(null, (Object) args);
System.err.println("Launcher: invoked: " + main);
reload = (Boolean) reloadMethod.invoke(null, new Object[0]);
}
} catch (final Exception ex) {
ex.printStackTrace(System.err);
System.err.println("Launcher: can not launch and reload this class:" + ex);
System.err.println("> " + clazz);
reload = false;
} finally {
if (urlClassLoader != null) {
try {
urlClassLoader.close();
} catch (IOException ex) {
ex.printStackTrace(System.err);
System.err.println("Launcher: error closing classloader: " + ex);
}
}
}
return reload ? true : false;
}
private static String findMainClass(URLClassLoader urlClassLoader) throws IOException {
URL url = urlClassLoader.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
Attributes attr = manifest.getMainAttributes();
return attr.getValue("Main-Class");
}
private static void runBatchFile(String batchfile) throws IOException, InterruptedException {
System.out.println("Launcher: executng batchfile: " + batchfile);
ProcessBuilder pb = new ProcessBuilder("cmd", "/C", batchfile);
pb.redirectErrorStream(true);
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
p.waitFor();
}
private static String removeArgPairOrNull(String arg, List<String> list) {
if (list.contains(arg)) {
int index = list.indexOf(arg);
list.remove(index);
return list.remove(index);
}
return null;
}
private static boolean removeArgSingle(String arg, List<String> list) {
if (list.contains(arg)) {
list.remove(list.indexOf(arg));
return true;
}
return false;
}
private void gc() {
for (int i = 0; i < 10; i++) {
byte[] bytes = new byte[1024];
Arrays.fill(bytes, (byte) 1);
bytes = null;
System.gc();
System.runFinalization();
}
}
}
After debugging, I determined the original difficulty was that the Launcher was not isolating the UrlClassloader.
By putting the part of the program that starts the classloader in a seperate method, I was able to allow all the system to determine that no more references existed.
After reworking the code, it all works now :)