Is there any way to catch a java exception from a JAR call by a php script? I have (!) to use some external JAVA libraries, which throws Exceptions. The Question is how can i extract valuable information for developers and show some explanation to the customer?
PHP Script
try{
$cmd = "java -jar myjar.jar";
$output = shell_exec(escapeshellcmd($cmd));
}
catch(Javaexception $e){
//do some error handling ....
}
Java Jar
//....
public class Main{
public static void main(String[] args){
throw new Exception("Testexception");
}
}
//...
shell_exec only returns a String or Null, so you can't catch the Java Exception like that, try to create your own Exception and "catch it" with a if
$cmd = "java -jar myjar.jar";
$output = shell_exec(escapeshellcmd($cmd));
if($output == 'expected output') throw new MyException();
Basic answer: not directly.
You can use exit statuses to communicate processing status from the Java application.
In Java:
public class Main{
public static void main(String[] args){
try {
// work
} catch (MyException e) {
// handle error
// write exception to file or STDOUT
System.exit(1);
}
}
}
In PHP you can get the exit status via return_var in exec call:
string exec ( string $command [, array &$output [, int &$return_var ]] )
You can also write Exception details to STDOUT or file and process its content in the PHP when status code is non 0.
Related
I am using Lobo Browser in NetBeans 11.2 and I cant run the program because NetBeans cannot read which file has the Main class which is in the main browser file (main class of main browser code below)
I would like to get this working because I need some code that I want to steal but I would like to see how the browser runs first.
public static void main(final String[] args) {
// Detect if we are running on mac
if (isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("dock.name", "LoboBrowser");
}
// Checking for stack allows us to call AccessController.doPrivileged()
// which in turn allows us to reduce the permissions on Uno codesource
final int stackDepth = Thread.currentThread().getStackTrace().length;
if (stackDepth > 11) {
System.err.println("Stack depth (" + stackDepth + ") is too deep! Quitting as a safety precaution");
Thread.dumpStack();
System.exit(1);
} else {
privilegedLaunch(args);
}
}
private static void launch(final String[] args) {
try {
final SSLSocketFactory socketFactory = TrustManager.makeSSLSocketFactory(ReuseManager.class.getResourceAsStream("/trustStore.certs"));
ReuseManager.getInstance().launch(args, socketFactory);
} catch (final Exception err) {
final StringWriter swriter = new StringWriter();
final PrintWriter writer = new PrintWriter(swriter);
err.printStackTrace(writer);
writer.flush();
JOptionPane.showMessageDialog(new JFrame(),
"An unexpected error occurred during application startup:\r\n" + swriter.toString(),
"ERROR", JOptionPane.ERROR_MESSAGE);
System.err.println(swriter.toString());
System.exit(1);
}
}
I believe you have to put the main method with in a class as described here http://tutorials.jenkov.com/java/main-method.html. I know in net beans you can tell it what class to try to run by I think right clicking the run then selecting what file to run and if its set up correctly it will run the file.
I'm trying to use tesseract to do OCR on an image in java. I realize there are wrappers like Tess4J that provide a bunch more functionality and stuff, but I've been struggling to get it set up properly. Simply running a one-line command with Runtime is really all I need anyways since this is just a personal little project and doesn't need to work on other computers or anything.
I have this code:
import java.io.IOException;
public class Test {
public static void main(String[] args) {
System.out.println(scan("full-path-to-test-image"));
}
public static String scan(String imgPath) {
String contents = "";
String cmd = "[full-path-to-tesseract-binary] " + imgPath + " stdout";
try { contents = execCmd(cmd); }
catch (IOException e) { e.printStackTrace(); }
return contents;
}
public static String execCmd(String cmd) throws java.io.IOException {
java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
When it's compiled and run directly from terminal, it works perfectly. When I open the exact same file in eclipse, however, it gives an IOException:
java.io.IOException: Cannot run program "tesseract": error=2, No such file or directory
What's going on? Thank you for any help.
Check the working folder in the run configuration for the Test class in Eclipse. I bet it's different from the one when you run the same program from a terminal.
I made spark+hadoop yarn enviroment and spark-submit command works well. So I made SparkLauncher java code to do this in my application jar, BUT somehow it doesn't work (actually computer fan is spinning at first but not as long as i did with spark-submit.)
It seems not work well (no application log in hadoop web ui, unlike spark-submit). I cannot see any error log when I do with 'SparkLauncher'. without log message, I can do nothing with it.
Here is how I made it so far.
public class Main {
public static void main(String[] args) {
Process spark = null;
try
{
spark = new SparkLauncher()
.setAppResource("/usr/local/spark/examples/jars/spark-examples*.jar")
.setMainClass("org.apache.spark.examples.SparkPi")
.setMaster("yarn")
.setDeployMode( "cluster")
.launch();
}
catch( IOException e)
{
e.printStackTrace();
}
}
}
executed it with ( java -jar example.jar)
I had the same problem at first. I think the main issue is that you forgot about the waitFor().
Also, it's really helpfull to extract your errorMessage and deal with it (e.g. log it or checking it while debuging ) within your java code. To allow this, you should create a streamReader thread as follows:
InputStreamReaderRunnable errorStreamReaderRunnable = new InputStreamReaderRunnable(spark.getErrorStream(), "error");
Thread errorThread = new Thread(errorStreamReaderRunnable, "LogStreamReader error");
errorThread.start();
int result= spark.waitFor();
if(result!=0) {
String errorMessage = extractExceptionMessage(errorStreamReaderRunnable.getMessage());
LOGGER.error(errorMessage);
}
This should be after your launch() command and inside your try block. Hope it helps
So my problem here is that I'm not too sure how to print a set of commands to cmd. I have a batch file that runs a Minecraft server, and I need to be able to run commands through the command prompt that shows up when I run the batch file, which will in turn perform commands to the server.
Here is my code so far:
package com.Kaelinator;
import java.io.IOException;
public class ServerManager {
public static void main(String[] args){
try {
System.out.println("Opening");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("cmd /C start /min " + "C:/Users/Owner/Desktop/rekt/Run.bat");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("Closing");
//process.destroy();
} catch (IOException e){
e.printStackTrace();
}
}
}
Yes, I understand that all this does so far is open the batch file. :P I am expecting something like this that I need to add to my code:
process.InputStream(command1);
But I am certain that there is more to it, something along the lines of bufferedWriters or something like that...
Whenever I try to get answers from Google, the answers always have a whole load of extra code, or have something completely different about them.
Thanks!
Hi I want to execute this command from java code :
cd C:/Users/Amira/junoWorkspace/TestProjectUI
mvn -Dtest=MyClassTest.java test
So I found this method but i didn't find a way to adapt it to my case :
public static void main(String[] args) throws IOException
{
try
{
// Runtime runtime = Runtime.getRuntime();
String[] cmd={"C:\\WINDOWS\\System32\\cmd.exe","/C start test.bat"};
Process p = Runtime.getRuntime().exec(cmd);
// TODO code application logic here
}
catch(IOException e)
{
System.err.println("echec de l'execution du script: "+e);
System.exit(1);
}
}
Any idea ?
Cheers
What you are looking for is ProcessBuilder which will allow you to set arguments like the working directory etc, it will also allow for multiple arguments, check here and here and ProcessBuilder Demo for some examples on how to use it