Following is my batch script
#echo off
set /a java_output=43350674
set /a img_id=1
setlocal enableDelayedExpansion
:top
for /f "tokens=1-2 delims= " %%A in ( 'java -jar test.jar %java_output%,%img_id%' ) do (
set /a java_output=%%A
set /a img_id=%%B
)
echo %java_output%
SET /A "err=error"
if "%java_output%" EQU "%err%" (
echo %img_id% > batch_log.txt
echo "End of batch script"
exit /b %ERRORLEVEL%
) else (
if %java_output% LSS 43350681 (
goto top
)
)
endlocal
Getting expected output but I am getting "Missing operand" error each time the for loops runs.
Error in " set /a img_id=%%B "
I have doubt in this line for /f "tokens=1-2 delims= " %%A in ( 'java -jar test.jar %java_output%,%img_id%' ) do (
Is this the correct way to pass 2 batch variables to jar file ?
Following is my java code in jar file.
public class Test {
public static void main(String[] args)
{
System.out.println(args[0]);
int ret = Integer.parseInt(args[0]);
// for error scenarios
String err = "error";
if(ret == 43350677)
{
System.out.println(err+" "+ret);
}
else
{
System.out.println(ret+1+" "+ret);
}
}
}
Following is my output :
C:>test.bat
Missing operand.
43350675
Missing operand.
43350676
Missing operand.
43350677
Missing operand.
0
"End of batch script"
If you want to start a jar file together with parameters out of a Windows script use the following syntax:
call java -jar my-jar-file.jar parm1 parm2 ...
The call is essential, otherwise the parameters are ignored.
Related
I am running the command below with is passing two argument to my script file(This below command is being constructed from java):
sh /home/accure/Desktop/scripts/cronhandler.sh "/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf" "* * * * */5"
Where "/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf" is the first argument and "* * * * */5" is the second argument which is basically a cron expression.
cronhandler.sh is my script file which contain this code:
if [ "$#" -eq 2 ]
then
echo "Crontab with create & update functionality"
command=$1
cron_exp=$2
echo "cron_exp=$cron_exp"
echo "command=$command"
cron_exp=`echo $cron_exp | sed 's/"//g' `
command=`echo $command | sed 's/"//g' `
echo "cron_exp=$cron_exp"
echo "command=$command"
if [[ "$cron_exp" != " " && "$command" != " " ]]
then
crontab -l | grep -q "$command"
if [ $? -eq 0 ]
then
crontab -l | grep -v "$command" | crontab -
echo "CRON entry deleted successfully.."
else
echo "CRON entry deletion failed."
fi
crontab -l | grep -q "$command" || (crontab -l 2>/dev/null; echo "$cron_exp $command") | crontab -
if [ $? -eq 0 ]
then
echo "CRON entry added successfully.."
else
echo "CRON entry addition failed."
fi
fi
fi
The error I'm getting while running the script is below. Actually it's listing out my files and folders from current working directory instead of adding the cron expression to cron tab.
Crontab with create & update functionality cron_exp=* * * * */5
command=/home/accure/Desktop/scripts/pipeline.sh
028d8ccb-4c46-4e02-a9b0-3c97a383daaf cron_exp=14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod */5
command=/home/accure/Desktop/scripts/pipeline.sh
028d8ccb-4c46-4e02-a9b0-3c97a383daaf CRON entry deletion failed.
"-":2: bad minute errors in crontab file, can't install. CRON entry
addition failed.
Note: Rather being added to crontab, * in cron expression is listing out my files and folder from current working directory.
Java code from where i am calling the command line is given below :
String pipelineFilePath="sh /home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf";
String cronExp="* * * * */5";
pipelineFilePath = "\"" + pipelineFilePath + "\"";
cronExp = "\"" + cronExp + "\"";
command = "sh " + /home/accure/Desktop/scripts/cronhandler.sh + " " + pipelineFilePath + " " + cronExp;
runScript(command);
public void runScript(String script) throws InterruptedException {
final String cmd = script;
Thread runScript = new Thread(new Runnable() {
public void run() {
try {
DefaultExecutor executor = new DefaultExecutor();
CommandLine commandLine = CommandLine.parse(cmd);
executor.setExitValue(1);
int exitValue = executor.execute(commandLine);
} catch (Exception ex) {
}
}
});
runScript.start();
Thread.sleep(10000);
}
Try to put single quotes (') instead of double quotes (") around your arguments:
sh /home/accure/Desktop/scripts/cronhandler.sh '/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf' '* * * * */5'
It will prevent your shell's filename expansion.
Trying to experiment with other DYLD_ properties I've found that jvm is manipulating with properties and they are ignored during execution.
My Java test:
class Env {
public static void main(String... args) {
System.getenv().entrySet().stream().forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
}
}
Invocation:
$ export DYLD_PRINT_LIBRARIES=1
$ export MY_PRINT_LIBRARIES=2
$ javac Env.java && java Env|grep PRINT
MY_PRINT_LIBRARIES = 2
$
On the other side, my C test:
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
while (*envp) {
printf("%s\n", *envp);
envp++;
}
return 0;
}
Invocation:
$ gcc env.c && ./a.out|grep PRINT
dyld: loaded: /Users/okutane/test/java/./a.out
dyld: loaded: /usr/lib/libSystem.B.dylib
dyld: loaded: /usr/lib/system/libcache.dylib
...
dyld: loaded: /usr/lib/libc++.1.dylib
dyld: loaded: /usr/lib/libDiagnosticMessagesClient.dylib
MY_PRINT_LIBRARIES=2
DYLD_PRINT_LIBRARIES=1
$
I expected jvm test to work too, is there are any workaround?
With the introduction of SIP, all environment variables matching DYLD_* will be stripped before executing a restricted binary. That includes the /usr/bin/java binary you would be using:
$ ls -lOL /usr/bin/java
-rwxr-xr-x 1 root wheel restricted,compressed 58560 Sep 7 06:41 /usr/bin/java*
Everthing on Java.
Environment: RedHat Linux 12.3
Lets get into details of the communication flow:
fig1.
NOTE: 1. Old model: There was NO A.java
"script.sh" starts/stops B.java as process
2. New model: There IS A.java
"script.sh" never uses A
"script.sh" starts B.java as process.
"myGraceful.sh" stops process Gracefully
"script.sh" is NEVER used for stopping
Server(B.java in server.jar):
Java Process triggered as: ./script.sh {start|stop}
Its a legacy class existing for 10 yrs or more
has RemoteB Interface
has
graceFul(){ ..handles all DB ,user states,connection...etc
..works perfectly from Admin
..invoked as RMI from JSP
..never invoked by script till now
}
initServer(){...}
getUsers(){...}
Requirement & My Effort:
Everyone knows how the code RMI Looks or .sh to invoke java. Hence I dont think pasting a proprietary code should be expected here.
Graceful needs to be done from shell script on same Server node. On Server everything runniing by Spring. I will die if I try to Inject a Bean as there is going to be 100x1000 dependencies coming in queue. Hence I created
RMI Client(com/common/task/A.java in same server.jar):
A can be triggered by: ./myGraceful.sh stop (eg. java -cp... com.A 2>&1)
in same server.jar - hence inevitaby loaded (note not running) on same Server node.
having p s v main(String args[])
Forks Thread ..thread calls RMI shutdown on B ...and thread expected
to die on own.
Problem:
Server shutting down perfectly. Then If I isssue following command AGAIN and AGAIN:
./script.sh start
Server starts up. But within a minute it stops automatically. I dont have any clue what and which is stopping the Server. I Observed
Prior to any of my new modifications:
"./script.sh stop" [used to work flawlessly calling kill -9 $pid ]
"ps - aefwww | grep java" used to show:
pid ppid.. /usr/java/jdk/bin/java ........java -D.... -Djava.timeout=.. -D....
pid ppid.. .../abc/ ....java...
pid ppid.. .../xyz/ .................java...
But now
"./myGraceful.sh stop" triggers modified server.jar(which now has A.java):
"ps - aefwww | grep java" shows:
pid ppid.. .../abc/ ....java...
pid ppid.. .../xyz/ .................java...
Here goes some code:
myGraceful.sh:
----------------
#!/bin/bash
CLASSPATH=$COMMON_CLASS_PATH:$LIB_INHOUSE/server.jar
rmiIp=x.y.zz.www [hidden]
rmiPort=xxxx [hidden]
peerId=1
period=5
function kill_server(){
echo -n "Shutting down Server ($pid): "
echo "executing Arnab"
echo "arg0 : $0 pid : $pid"
java -Djava.rmi.server.hostname=localhost \
com.common.task.GracefulRunner $rmiIp $rmiPort $peerId $period 2>&1
echo Done
}
case "$1" in
start)
get_pids "CustomBootstrap" $2
if [ "$pid" != "" ] ; then
get_processname "CustomBootstrap" $2
if [ "$server" != "" ] ; then
echo "Server already running. pid = $pid"
exit 1
fi
if [ "$ctserver" != "" ] ; then
echo "Shutting down CT Server($pid): "
kill -SIGQUIT $pid
kill -9 $pid
echo Done
fi
fi
$0 run $2 1>&2 &
sleep 2
$0 status $2
# $0 err
;;
stop)
$0 kill $2
;;
kill)
get_pids "CustomBootstrap" $2
if [ "$pid" != "" ] ; then
kill_server
echo "Server ended at `date`"
else
get_pids "Launcher" $2
if [ "$pid" != "" ] ; then
kill_server
else
echo "Server is not running !"
fi
fi
;;
esac
A.java
public class A {
class GracefulStopperThread implements Runnable{
private String serverRMIIp = null;
private int serverRmiPort =0;
private String serverPeerId =null;
private int shutDownPeriod =0;
public GracefulStopperThread(String rmiIp,String rmiPort,String peerId,String period){
serverRMIIp = rmiIp;
serverRmiPort = Integer.parseInt(rmiPort);
serverPeerId = peerId;
shutDownPeriod =Integer.parseInt(period);
}
public void run() {
System.out.println("***************************************** GracefulStopper is running *******************************************");
System.out.println("serverPeerId :="+serverPeerId+" , shutDownPeriod :="+shutDownPeriod);
try {
IRemoteServer serverRef = null;
String rmiUrl = getURL(serverRMIIp,serverRmiPort,serverPeerId);
System.out.println("THE RMI URL : "+rmiUrl);
serverRef = (IRemoteServer) Naming.lookup(rmiUrl );
com.server.ds.IRemoteServer pcServerRef = (com.server.ds.IRemoteServer) serverRef;
pcServerRef.graceful(SHUTDOWN_TYPE_SERVER_NOTSYSTEM,"Gracefully Shutting down withing 10 mins", shutDownPeriod);
System.out.println("GracefulStopperThread completed ");
} catch (Exception e) {
e.printStackTrace();
}
}
private String getURL(String rmiIp,int rmiPort,String peerId) {
return new StringBuffer(32).append("rmi://").append(serverRMIIp).append(':').append(serverRmiPort)
.append('/').append(serverPeerId).toString();
}
}
public static void main(String args[]) throws InterruptedException {
A agent = new A();
Runnable stopper = agent.new GracefulStopperThread(args[0],args[1],args[2],args[3]);
Thread t = new Thread(stopper);
t.start();
t.join();
System.out.println("MainThread completed ");
}
}
From catalina and tomcat logs it became clear - there was a wrong missing JMX entry in the jmx config file which has nothing to do with all above. This caused Tomcat to stop after 85 % of its start. Hence it actually never started. Question can be closed and marked solved.
I can ps-session to a remote machine, run the following, and successfully uninstall Java:
invoke-expression "msiexec /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "
I am trying to create a script that will uninstall from all domain computers:
Import-Module ActiveDirectory
function uninstallJava {
$badcomp = #()
$CompList = Get-ADComputer -Filter 'name -like "*"' | select -ExpandProperty Name
foreach ($c in $CompList) {
Try {
Enter-PSSession -ComputerName $computer
Invoke-expression "msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "
}
Catch {
$badcomp += $c
}
}
}
uninstallJava
"the following servers could not be reached:"
$badcomp
I don't receive any errors, but it doesn't uninstall Java from the remote machines.
Any ideas appreciated.
Import-Module ActiveDirectory
$badcomp = #()
Function uninstallJava {
$CompList = Get-ADComputer -Filter 'name -like "*"' | Select -ExpandProperty Name
ForEach ($c In $CompList) {
Try {
Invoke-Command -ComputerName $c {
C:\Windows\System32\cmd.exe /C msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}'
}
} Catch {
$badcomp += $c
}
}
}
uninstallJava
Write-Host "the following servers could not be reached:"
$badcomp
You should be using Invoke-Command, not Enter-PSSession. The latter is for interactively working in another machine. The former is for running a command in the other machine and getting back results (if any).
Basically, your try block should look like this:
Try {
Invoke-Command -ComputerName $c -ScriptBlock { msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' }
}
If you want more detailed control and error information, consider using WMI to uninstall the product instead of shelling out to msiexec.
Problem: I am running java files via PHP that a user submits. It is possible for a java file to cause an infinite loop. How can I handle this in the php execution process?
Here is my code:
$proc = proc_open($javaCmd, array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w")), $pipes);
// Check status here logic ?
proc_close($proc);
It currently waits for the process to finish, but I want it to timeout after 30 seconds or a minute. I tried set_time_limit(x), but that does not terminate java.exe.
My question is, is it possible for me to check the status of java.exe process after X seconds, then terminate if it is still running? Or, do I need to use a timeout functionality in java (i.e. have a main class that executes the user's submitted classes on a thread)
Yes, it's possible. I don't think a java process is any different than any other process in this regard. See these links for unix exec with timeout and windows exec with timeout.
I didn't write this code, but here it is copy-pasted in case the original disappears from the Internet:
For unix:
<?php
function PsExecute($command, $timeout = 60, $sleep = 2) {
// First, execute the process, get the process ID
$pid = PsExec($command);
if( $pid === false )
return false;
$cur = 0;
// Second, loop for $timeout seconds checking if process is running
while( $cur < $timeout ) {
sleep($sleep);
$cur += $sleep;
// If process is no longer running, return true;
echo "\n ---- $cur ------ \n";
if( !PsExists($pid) )
return true; // Process must have exited, success!
}
// If process is still running after timeout, kill the process and return false
PsKill($pid);
return false;
}
function PsExec($commandJob) {
$command = $commandJob.' > /dev/null 2>&1 & echo $!';
exec($command ,$op);
$pid = (int)$op[0];
if($pid!="") return $pid;
return false;
}
function PsExists($pid) {
exec("ps ax | grep $pid 2>&1", $output);
while( list(,$row) = each($output) ) {
$row_array = explode(" ", $row);
$check_pid = $row_array[0];
if($pid == $check_pid) {
return true;
}
}
return false;
}
function PsKill($pid) {
exec("kill -9 $pid", $output);
}
For windows:
<?php
// pstools.inc.php
function PsExecute($command, $timeout = 60, $sleep = 2) {
// First, execute the process, get the process ID
$pid = PsExec($command);
if( $pid === false )
return false;
$cur = 0;
// Second, loop for $timeout seconds checking if process is running
while( $cur < $timeout ) {
sleep($sleep);
$cur += $sleep;
// If process is no longer running, return true;
if( !PsExists($pid) )
return true; // Process must have exited, success!
}
// If process is still running after timeout, kill the process and return false
PsKill($pid);
return false;
}
function PsExec($command) {
exec( dirname(__FILE__). "\\psexec.exe -s -d $command 2>&1", $output);
while( list(,$row) = each($output) ) {
$found = stripos($row, 'with process ID ');
if( $found )
return substr($row, $found, strlen($row)-$found-strlen('with process ID ')-1); // chop off last character '.' from line
}
return false;
}
function PsExists($pid) {
exec( dirname(__FILE__). "\\pslist.exe $pid 2>&1", $output);
while( list(,$row) = each($output) ) {
$found = stristr($row, "process $pid was not found");
if( $found !== false )
return false;
}
return true;
}
function PsKill($pid) {
exec( dirname(__FILE__). "\\pskill.exe $pid", $output);
}