bash scripting: search Java STDOUT for a variable - java

When I run myTest.jar, it outputs alot of information in STDOUT (not in a file) and I am trying to read/search that file for a specific string to put as a variable in my bash script.
java stdout:
line 1 info............
line 2 info...........
....
...
Successful (either 'Successful' or 'Failed')
How do I search for, in bash, the last line in the stdout or for ('Successful' or 'Failed') without redirecting the stdout to a file?
Thanks in advance

This is not a good way of checking for success or failure.
You should instead rewrite myTest.jar to use System.exit(0) on success and System.exit(1) (or higher) on error. If the program is well written, it will already do this.
You can then check for success or failure in bash using e.g.
if java -jar mytest.jar
then
echo "The command succeeded :D"
else
echo "The command failed :("
fi
All UNIX programs work this way, and you should make sure that myTest.jar is no exception.

To make this work, you would need to redirect stdout to a file and then cat/vim/search that file. Bash doesn't save the output of commands on its own.
Alternatively, you could use a program like screen that allows you to save a transcript of your session to a file. You would get the output of everything and the command lines though.

for future users, I used "that other guys' " method with some minor adjustments:
1) the exit code and what your doing have to be right after the running jar, wouldn't work for me in other segments
2) I read the exit code I was receiving and made an if loop for my conditions (0-2) exit code was given in java
3) piece of my bash code
EXIT_CODE=$?
echo Exit code: $EXIT_CODE
if [ $EXIT_CODE = "0" ]
then
...............do something
elif [$EXIT_CODE = "1"]
then
...............do something
else
...............do something
fi

Related

Need to move on after java error when Python script uses subprocess to run a java program

In a python2.7 script, I'm using subprocess.call to run a java program like this:
java_command = "java -jar /path/to/java_program.jar %s %s >> %s" % (infile, outfile, logfile)
subprocess.call(java_command, shell=True)
...
#Do other stuff unrelated to this output
Most of the time, this works fine, but in some cases the java program errs:
Exception in thread "main" java.lang.NullPointerException
at MyProgram.MainWindow.setProcessing(MainWindow.java:288)
The problem is that my python script is then stalled on the subprocess.call() line and can't do the "other stuff".
Is there a way I can edit either the java_command I'm using or the way I'm using subprocess to continue the python script even when the java program hangs?
Note that I can't modify the java program's code.
I think you want the check_call method from that same package:
try:
status = subprocess.check_call(java_command, shell=True)
except CalledProcessError as e:
# The exception object contains the return code and
# other failure information.
... react to the failure and recover

Starting Mule for remote debugging without modifying wrapper.conf

I'm stuck on Mule version 3.4.0 due to requirements at work. I'm writing a service script to manage the service lifecycle of Mule and would really like to be able to have it hang and wait for a debugger to connect based on whether a certain option is present in the parameters.
I'm comfortable with Bash and implementing this, but I'm having an extremely hard time trying to get Mule to pass along the
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9989
to the underlying Java process, as it uses its own (stupid) wrapper to address Java.
I'm trying to modify the bin/mule script to have a mode called debug which will pass the above debugger options to the JVM when invoked with:
bin/mule debug
My current work can be found here on PasteBin, and here is the relevant part near line 511:
debug() {
echo "Debugging $APP_LONG_NAME..."
getpid
if [ "X$pid" = "X" ]
then
# The string passed to eval must handle spaces in paths correctly.
COMMAND_LINE="$CMDNICE \"$WRAPPER_CMD\" \"$WRAPPER_CONF\" wrapper.syslog.ident=$APP_NAME wrapper.pidfile=\"$PIDFILE\" $ANCHORPROP $LOCKPROP"
######################################################################
# Customized for Mule
######################################################################
echo "command line: $COMMAND_LINE"
echo "mule opts: $MULE_OPTS"
echo "JPDA_OPTS: $JPDA_OPTS"
eval $COMMAND_LINE $JPDA_OPTS $MULE_OPTS
######################################################################
else
echo "$APP_LONG_NAME is already running."
exit 1
fi
}
I cannot upgrade to a newer version of Mule. I need to find a way to modify this script to simply wait for a debugger when invoked with bin/mule debug. I've modified it enough to get into this debug function I've defined which is basically a copy of their own console function for starting in console mode. I can't seem to figure out how to get my debug opts passed to the JVM. Any ideas?
The parameter -debug, following documentation, was present in 3.4.x:
./mule -debug
Give it a try.

java executing bash script, error=26 Text file busy

I've got a java code that is writing a Linux bash script out, then doing a chmod to add execute permission, then trying to execute it. I'm getting an IOException during the start of the process saying error=26, Text file busy. I've verified that the file is finished being written and the stream was closed. The chmod works fine, but I keep getting this error.
I've noticed that if I run a debugger and step through the code, it doesn't get the error, so clearly there is a timing issue involved. How can I make sure the chmod is done before I try to execute the bash script? I'd like to avoid non-reliable solutions like adding Thread.sleep(10000), and "hacky" things like putting the execution in a try/catch block inside a loop that tries until it succeeds.
I have a fair amount of code wrapping the startup of the process with listening threads, etc., but here is a simplified version of what it is doing (tried this code also and it has same result):
String[] cmd1 = {"/bin/chmod", "750", postFile };
new ProcessBuilder(cmd1).redirectErrorStream(true).start().waitFor();
String[] cmd2 = { postFile };
new ProcessBuilder(cmd2).redirectErrorStream(true).start().waitFor();
Every time after execution, the "postFile" has the correct 750 permissions, but it has not executed (due to the IOException).
For future reference, it may have been caused by an unclosed stream in this particular case, but setting permissions on a file immediately followed by running the file can cause this error too:
java.io.IOException: Cannot run program "...": error=26, Text file busy
It is a probable bug in JDK. In my case, it was caused by this snippet of code
Files.setPosixFilePermissions(Paths.get(scriptPath), set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ));
ProcessBuilder processBuilder = new ProcessBuilder(scriptPath).directory(workingDir);
processBuilder.start();
even if nothing was editing the script file.
Are you sure it is the chmod that is responsible for the subsequent error? Could you check that you definitely close the output file before you try to run it?
If you do close it then I'm at a loss why chmod should cause that error, but you could avoid the need to run chmod by using your shell to run the script:
String[] cmd = {"bash", postfile };
I don't know if it's related but usually you need to get or redirect the ErrorStream and the InputStream (I usually get them in a ResponseStreamReader that I create, don't know about the redirecting choice).
In my service file in /etc/systemd/system/ I have directed outputs to log files:
StandardOutput=file:/home/pi/ApplicationLogs/application_l_debug.log
StandardError=file:/home/pi/ApplicationLogs/application_l_error.log
The error message disappeared when I changed permissions on the ApplicationLogs directory to write permissions to all
(chmod a+w ApplicationLogs)

How can I execute a Java program within a php script?

I am writing a simple web upload script.
The goal is to upload a file using php, and then calling a java program to process this file.
I have done the work for uploading the file, but I cannot get a java program to be successfully run from within the php script.
I have tried exec(), shell_exec(), and system() with no results.
For the command, I have used "java Test", "java < directory >/Test", "/usr/bin/java < directory >/Test", I have even set up the application as a jar file with no results. The actual line of code I have used is:
echo shell_exec("java Test");
Usually there is no output. However, if I have just shell_exec("java"), then the last line of the help from java ("show splash screen with specified image") is displayed, which shows that the command has been executed. If I use, for example, shell_exec("whoami") I get "nobody" returned, which is correct. The only thing the java file does is create a file so that I can see that the application has been successfully run (the application runs successfully if I run it on the command line). I have set the permissions for the java file to 777 to rule out any possibility of permission errors. I have been struggling with this for a while trying all sorts of options with no results - the file is never created (the file is created with an absolute path so it's not being created and I just can't find the file). Does anyone have any ideas?
Thanks.
I have been struggling with this for a
while trying all sorts of options with
no results - the file is never created
(the file is created with an absolute
path so it's not being created and I
just can't find the file). Does anyone
have any ideas?
What I think the problem is. Apache runs as "nobody" group??(apache user??) which will execute the java script which will try to create a file on disc somewhere. I assume it does not have permission to write to that location. you should chown that folder so that apache user can write to that folder.
==
First off I would like to point out to you that calling exec() from a script could really blow up your server. I would advice you to use something like redis(see below) instead.
==
Second I think I know what the problem is. You should first try to run the simple example below which worked fine for me.
==
First be sure permission are set right. Because apache runs as nobody(most of the times).
I tried this simple test myself on ubuntu with php installed from repo.
test.java
class test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
test.php
echo exec('java test');
Ran test.php
$ php test.php
Hello World!
==
Or you could try 1 of the following solutions(which would even be a better solution):
Write your java program as a webservice for example on top of atmosphere-spade-server(simple/embedded jar). This could be written insanely fast. But on high load this will not be best option I guess. Still I think this will be more than fast enough for you probably. Even this way it will be much faster as executing it, because you won't have the overhead running JVM. Could blow up your server, not as fast as exec()
Do a blocking pop/push from a redis(*nix) list structure. This will be pretty easy to write on *nux because there are client libraries for both java/php. The speed will best I guess because redis is written in C. I use redis myself.
Use a JMS like for example activemq. Also pretty easy to write because good library support. I have not used a JMS myself. I use redis solution. The speed I guess would be a little less then with redis solution.
I dont realy know, but i came a cross PHP-JAVA bridge maybe it can help
http://php-java-bridge.sourceforge.net/pjb/
Update:
I tested this with Jasper Reports, and it is working really nice. It will allow you to Extend Java classes with PHP or just use Java class lik it was PHP.
use java\lang\String as JString;
require_once("javabridge/java/Java.inc");
class String extends JString {
function toString () {
return "hello " . parent::toString();
}
}
$str = new String("Java");
echo $str->toString();
or
$temp = new Java('java.sql.Timestamp');
$javaObject = $temp->valueOf('2007-12-31 0:0:0');
$params = new Java("java.util.HashMap");
$params->put("text", "This is a test string");
$params->put("date",$javaObject);
More examples: http://php-java-bridge.sourceforge.net/pjb/FAQ.html
It's possible it has to do with the path that the exec is defaulting to. You may need to explicitly define your classpath with an absolute path to your .class or jar files when calling java.
<?php
$PATH="C:\Program Files\Java\jdk1.7.0_09\bin";
echo exec("javac theNameOfYourJavaProgram.java 2>&1");//shows # of errors
echo "<br />";
echo exec("java theNameOfYourJavaProgram 2>&1");//this line executes it
echo "<br />";
echo shell_exec("javac theNameOfYourJavaProgram.java 2>&1 ");//compiles it
?>

How to get the error from exec?

I am executing a.jar file from PHP through Command Line. However, if there is any error/exception, the error is not being displayed.
I am using the following PHP script.
<?php
exec('java -jar D:\\ABC\\JavaApplication2\\dist\\JavaApplication2.jar', $result, $returnCode);
var_dump($result);
$count = count($result);
for($i=0; $i<$count;$i++){
print($result[$i]);
}
?>
The output for the above code is : 'array(0) { }'
don't use exec() if you want to handle I/O, instead use popen() for simple stuff (either read or write) or proc_open() for full fd connectivity, with stdin, stdout, stderr, and possibly other fd's connected (e.g. for openssl).
Probably you need to pipe the output of the jar to some file and listen to that file in PHP.

Categories

Resources