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);
}
}
Related
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>");
}
}
I have a weird issue. I created a PHP App that reads files and then, move to another directory. The app works fine when i run it.
Now, i created a daemon on java that runs a .bat file that runs my php script.
My .bat is this "invoker.bat":
cd C:\xampp\php
PHP C:\xampp\htdocs\EDI\ler.php
exit
My daemon on java is this:
package edidemon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.Timer;
import java.util.Observable;
import java.util.Observer;
/**
*
* #author Bottago SA
*/
public class EDIDemon extends Observable {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EDIDemon edid = new EDIDemon();
edid.addObserver(new Observer() {
#Override
public void update(Observable o, Object arg) {
//se invoca por medio de cmd al php lector EDI
try {
String cmd = "invoker.bat";
Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
});
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {
}
}
public EDIDemon() {
Timer timer;
timer = new Timer(12000, new ActionListener()//6000 es un segundo
{
#Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(new Date());
}
});
timer.start();
}
}
Part of my php code that reads the file and moves it.
if ($handle = scandir('C:/xampp/htdocs/EDI/Prepared')){
foreach($handle as $entry){
if (in_array($entry, array(".",".."))) continue;
if(isset($entry)){
echo "<table><tr><td><strong>File: ".$entry."</strong></td></tr></table><br>";
//---Mover archivos de un directorio a otro almacenados una vez leidos
$subir = 'C:/xampp/htdocs/EDI/Prepared/';
$path = $subir.$entry;
$Uploaded = 'C:/xampp/htdocs/EDI/Uploaded/';
$Failed = 'C:/xampp/htdocs/EDI/Failed/';
$newName = file($path);
$ponteiro = fopen ($path,"r");
$arquivo = '';
while (!feof ($ponteiro)) {
$arquivo = $arquivo.fgets($ponteiro);
}
fclose ($ponteiro);
$padrao = fnc_resgata_padrao($arquivo);
$segmento = fnc_obter_linha_segmento ($arquivo, "UNB");
$sender = fnc_edi_recupera_compnte($segmento,2,0);
$sendername = substr($sender, 0, 3);
if ($padrao == "COARRI" && $sendername !== "TPG"){
$a = fnc_processa_coarri(trim($arquivo));
prc_mostra_coarri($a, $entry, $arquivo);
copy($path, $Uploaded.$entry);
unlink($path);
}
elseif ($padrao == "COARRI" && $sendername == "TPG"){
$a = fnc_processa_coarri_header_tpg(trim($arquivo));
$a = fnc_processa_coarri_tpg(trim($arquivo)) +$a;
prc_mostra_coarri($a, $entry, $arquivo);
copy($path, $Uploaded.$entry);
unlink($path);
}
elseif ($padrao == "CODECO") {
$a = fnc_processa_codeco(trim($arquivo));
prc_mostra_codeco($a, $entry, $arquivo);
copy($path, $Uploaded.$entry);
unlink($path);
}
elseif ($padrao == "BAPLIE") {
$a = fnc_processa_baplie(trim($arquivo));
prc_mostra_baplie($a);
}
elseif ($padrao == "WESTIM"){
$a = fnc_processa_westim(trim($arquivo));
prc_mostra_westim($a, $entry, $arquivo);
}
else {
copy($path, $Failed.$entry);
unlink($path);
echo "<table><tr><td><strong>Archivo incorrecto</strong></td></tr></table>";
}
} else {
echo "You need to select a file. Please try again.";
}
}
}
The problem is, if i just run the .bat, the files that the php app read moves to another directory as usual. But, if i run the daemon (java app), it only read the file, insert on the DB but doesn't move to another directory.
¿Can anyone have a clue?
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
I'm very new to Java and am trying to achieve the following (please forgive my lack of knowledge with any proper or known etiquette that I've broken):
I've created a project, with 2 packages; src.ext and src.utils
* src.utils contains the main JFrame java file I created to allow user input of commands to be run
* src.ext contains the executables
What I want to be able to do is utilize Runtime.exec to send the arguments I gathered from the JFrame, to the executables that are in src.ext
As I understand it, Runtime.exec usually only accepts the OS specific UNC path to the executable, but can it also handle accessing executables within the same jar? How?
Thank you.
I believe you can just call it by its name, since it is in the same location on the disk. Like so
String[] params = {mySweetExecutable, arg1,arg2};
Runtime.exec(params);
Here sample of my code:
package com.wenxiong.hiddenrecover;
import java.io.File;
import java.io.IOException;
import java.util.Stack;
public class HiddenRecover {
static Stack<File> stack = new Stack<File>();
static String rootDir;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
if (args.length != 1) {
System.out.println("Sample of usages:");
System.out.println("Command: java com.wenxiong.hiddenrecover.HiddenRecover C:\\");
System.out.println("Command: java com.wenxiong.hiddenrecover.HiddenRecover C:\\somedirectory");
} else {
rootDir = args[0];
stack.push(new File(rootDir));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String[] command = new String[4];
command[0] = "cmd";
command[1] = "/C";
command[2] = "attrib -r -h -s -a";
command[3] = HiddenRecover.rootDir;
while (!stack.isEmpty()) {
File currFile = stack.pop();
if (currFile.isDirectory()) {
File[] arr = currFile.listFiles();
for (File item : arr) {
stack.push(item);
}
}
System.out.println("Recovering: " + currFile.getAbsolutePath());
command[3] = currFile.getAbsolutePath();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Could not recover: " + command[3] + " " + e.getMessage());
}
}
}
});
t.start();
}
}
}
Just modify based on your needs.
try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat"+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
But when I run I get an exception like this
Unexpected exception Trying to Execute Job: java.io.IOException: CreateProcess:
C:/tes1.batE:/ior1.txt error=2
Press any key to continue . . .
This is the batch file content
echo "testing"
echo %1
There's a blank missing after .bat (in the rt.exec line)
Edit:
You could also try executing:
rt.exec("cmd /c c:/tes1.bat "+comd);
Try prefixing the exec call with cmd /c or call, e.g.
rt.exec("cmd /c c:/tes1.bat "+comd);
(I don't have a Windows box available right now so I can't test this but as far as I remember, launching batch files required launching the command interpreter first.)
When i see this correct, you have to put a space between the bat command and the argument
EDIT:
try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat "+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
EDIT 2:
After taking a look again and testing on my PC the other answers seems correct. The cmd is missing.
rt.exec("cmd /c c:/tes1.bat "+comd);
Be aware, that there is a number of issues related to executing an external process from within your Java program if you have to use this in a production environment.
You have e.g. to be aware of the fact, that if the output from the process is larger than the buffer used by the JVM<->OS the exec will block forever.
I normally use a wrapper with Threads to read from the buffers.
Its not perfect, but something like (see main() for details on usage):
/**
* Executes a given OS dependent command in a given directory with a given environment.
* The parameters are given at construction time and the initialized object is immutable.
* After the object initialization and execution of the blocking exec() method the state
* can't be changed. The result of the execution can be accessed through the get methods
* for the exitValue, stdOut, and stdErr properties. Before the exec() method is completed
* the excuted property is false and the result of other getters is undefined (null).
*/
public class CommandExecutor {
/**
* Specifies the number of times the termination of the process is
* waited for if the OS gives interruptions
*/
public static final int NUMBER_OF_RUNS = 2;
/**
* Used for testing and as example of usage.
*/
public static void main(String[] args) {
System.out.println("CommandExecutor.main Testing Begin");
String command_01 = "cmd.exe /C dir";
File dir_01 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_01);
System.out.println("CommandExecutor.main Testing. dir: " + dir_01);
CommandExecutor ce_01 = new CommandExecutor(command_01, null, dir_01);
ce_01.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_01.getExitValue());
System.out.println(" stdout: " + ce_01.getStdout());
System.out.println(" stderr: " + ce_01.getStderr());
String command_02 = "cmd.exe /C dirs";
File dir_02 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_02);
System.out.println("CommandExecutor.main Testing. dir: " + dir_02);
CommandExecutor ce_02 = new CommandExecutor(command_02, null, dir_02);
ce_02.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_02.getExitValue());
System.out.println(" stdout: " + ce_02.getStdout());
System.out.println(" stderr: " + ce_02.getStderr());
System.out.println("CommandExecutor.main Testing End");
}
/*
* The command to execute
*/
protected String command;
/*
* The environment to execute the command with
*/
protected String[] env;
/*
* The directory to execute the command in
*/
protected File dir;
/*
* Flag set when the command has been executed
*/
protected boolean executed = false;
/*
* Exit value from the OS
*/
protected int exitValue;
/*
* Handle to the spawned OS process
*/
protected Process process;
/*
* Std error
*/
protected List<String> stderr;
/*
* Worker Thread to empty the stderr buffer
*/
protected Thread stderrReader;
/*
* Std output
*/
protected List<String> stdout;
/*
* Worker Thread to empty the stdout buffer
*/
protected Thread stdoutReader;
/**
* Creates a new instance of the CommandExecutor initialized to execute the
* specified command in a separate process with the specified environment
* and working directory.
*
* #param env
*/
public CommandExecutor(String command, String[] env, File dir) {
this.command = command;
this.env = env;
this.dir = dir;
}
/**
* Creates a reader thread for the stderr
*/
protected void connectStderrReader() {
stderr = new ArrayList<String>();
final InputStream stream = process.getErrorStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stderrReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stderr.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStderrReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stderrReader.start();
}
/**
* Creates a reader thread for the stdout
*/
protected void connectStdoutReader() {
stdout = new ArrayList<String>();
final InputStream stream = process.getInputStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stdoutReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stdout.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStdoutReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stdoutReader.start();
}
/**
* Creates the process for the command
*/
protected void createProcess() {
try {
process = Runtime.getRuntime().exec(command, env, dir);
} catch (IOException e) {
System.out.println("CommandExecutor.exec() error in process creation. Exception: " + e);
e.printStackTrace(System.out);
}
}
/**
* Executes command in a separate process in the specified directory. Method will block until
* the process has terminated. Command will only be executed once.
*/
public synchronized void exec() {
// Future enhancement: check for interrupts to make the blocking nature interruptible.
if (!executed) {
createProcess();
connectStdoutReader();
connectStderrReader();
waitForProcess();
joinThreads();
exitValue = process.exitValue();
executed = true;
}
}
/**
* #return the command
*/
public String getCommand() {
return command;
}
/**
* #return the dir
*/
public File getDir() {
return dir;
}
/**
* #return the env
*/
public String[] getEnv() {
return env;
}
/**
* #return the exitValue
*/
public int getExitValue() {
return exitValue;
}
/**
* #return the stderr
*/
public List<String> getStderr() {
return stderr;
}
/**
* #return the stdout
*/
public List<String> getStdout() {
return stdout;
}
/**
* #return the executed
*/
public boolean isExecuted() {
return executed;
}
/**
* Joins on the 2 Reader Thread to empty the buffers
*/
protected void joinThreads() {
try {
stderrReader.join();
stdoutReader.join();
} catch (InterruptedException e) {
System.out.println("CommandExecutor.joinThreads() error. Exception: ");
e.printStackTrace(System.out);
}
}
/**
* Creates a String representing the state of the object
*/
#Override
public synchronized String toString() {
StringBuilder result = new StringBuilder();
result.append("CommandExecutor:");
result.append(" command: " + command);
result.append(" env: " + Arrays.deepToString(env));
result.append(" dir: " + dir);
result.append(" executed: " + executed);
result.append(" exitValue: " + exitValue);
result.append(" stdout: " + stdout);
result.append(" stderr: " + stderr);
return result.toString();
}
/**
* Waits for the process to terminate
*/
protected void waitForProcess() {
int numberOfRuns = 0;
boolean terminated = false;
while ((!terminated) && (numberOfRuns < NUMBER_OF_RUNS)) {
try {
process.waitFor();
terminated = true;
} catch (InterruptedException e) {
System.out.println("CommandExecutor.waitForProcess() error");
e.printStackTrace(System.out);
numberOfRuns++;
}
}
}
}
Additonal to laalto's comment:
Runntime provides several signatures of exec().
rt.exec("cmd /c c:/tes1.bat "+comd);
rt.exec(new String[] {"cmd","/c","c:/tes1.bat",comd});