Getting issue in adding cron expression to crontab from java and CLI - java

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.

Related

Is there any way to check password hash sync status in Java code?

I'm working with azure SDK and I need to check the status of "password hash sync" in code. Is there any way to check in Java?
below are some document I researched:
https://github.com/Azure/azure-sdk-for-java
https://learn.microsoft.com/en-us/azure/active-directory/hybrid/tutorial-password-hash-sync
https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-password-hash-synchronization
I'm afraid there's no SDK to get the status of password hash sync. Only Get-ADSyncAADCompanyFeature can help you.
You could try to create a powershell script and then invoke the powershell script from java.
Import-Module ADSync
$connectors = Get-ADSyncConnector
$aadConnectors = $connectors | Where-Object {$_.SubType -eq "Windows Azure Active Directory (Microsoft)"}
$adConnectors = $connectors | Where-Object {$_.ConnectorTypeName -eq "AD"}
if ($aadConnectors -ne $null -and $adConnectors -ne $null)
{
if ($aadConnectors.Count -eq 1)
{
$features = Get-ADSyncAADCompanyFeature
Write-Host
Write-Host "Password sync feature enabled in your Azure AD directory: " $features.PasswordHashSync
foreach ($adConnector in $adConnectors)
{
Write-Host
Write-Host "Password sync channel status BEGIN ------------------------------------------------------- "
Write-Host
Get-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector.Name
Write-Host
$pingEvents =
Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 -After (Get-Date).AddHours(-3) |
Where-Object { $_.Message.ToUpperInvariant().Contains($adConnector.Identifier.ToString("D").ToUpperInvariant()) } |
Sort-Object { $_.Time } -Descending
if ($pingEvents -ne $null)
{
Write-Host "Latest heart beat event (within last 3 hours). Time " $pingEvents[0].TimeWritten
}
else
{
Write-Warning "No ping event found within last 3 hours."
}
Write-Host
Write-Host "Password sync channel status END ------------------------------------------------------- "
Write-Host
}
}
else
{
Write-Warning "More than one Azure AD Connectors found. Please update the script to use the appropriate Connector."
}
}
Write-Host
if ($aadConnectors -eq $null)
{
Write-Warning "No Azure AD Connector was found."
}
if ($adConnectors -eq $null)
{
Write-Warning "No AD DS Connector was found."
}
Write-Host
For more details, see here.

Could not load main class from .java class file

I'm using Python to visualize a graph through a tool named wot using jupyter notebook. It utilizes Gephi, a java-based graph utility. I try to run function to return coordinate output files as below:
run_gephi(input_graph_file, output_coord_file, n_steps):
layout = 'fa'
import psutil
memory = int(0.5 * psutil.virtual_memory()[0] * 1e-9)
classpath = os.path.dirname(
pkg_resources.resource_filename('wot', 'commands/resources/graph_layout/GraphLayout.class')) + ':' + \
pkg_resources.resource_filename('wot', 'commands/resources/graph_layout/gephi-toolkit-0.9.2-all.jar')
subprocess.check_call(['java', '-Djava.awt.headless=true', '-Xmx{memory}g'.format(memory=memory), '-cp', classpath, \
'GraphLayout', input_graph_file, output_coord_file, layout, str(n_steps), str(os.cpu_count())])
Then it returns following error in my jupyter notebook:
CalledProcessError Traceback (most recent call last)
<ipython-input-18-5fc832689b87> in <module>
----> 1 df, adata = compute_force_layout(ds)
<ipython-input-7-6cb84b9e0fa0> in compute_force_layout(ds, n_neighbors, n_comps, neighbors_diff, n_steps)
24 writer.write("{u} {v} {w:.6g}\n".format(u=i + 1, v=j + 1, w=W[i, j]))
25
---> 26 run_gephi(input_graph_file, output_coord_file, n_steps)
27 # replace numbers with cids
28 df = pd.read_table(output_coord_file, header=0, index_col='id')
<ipython-input-16-28772d0d10cc> in run_gephi(input_graph_file, output_coord_file, n_steps)
7 pkg_resources.resource_filename('wot', 'commands/resources/graph_layout/gephi-toolkit-0.9.2-all.jar')
8 subprocess.check_call(['java', '-Djava.awt.headless=true', '-Xmx{memory}g'.format(memory=memory), '-cp', classpath, \
----> 9 'GraphLayout', input_graph_file, output_coord_file, layout, str(n_steps), str(os.cpu_count())])
~/anaconda3/lib/python3.7/subprocess.py in check_call(*popenargs, **kwargs)
339 if cmd is None:
340 cmd = popenargs[0]
--> 341 raise CalledProcessError(retcode, cmd)
342 return 0
343
CalledProcessError: Command '['java', '-Djava.awt.headless=true', '-Xmx25g', '-cp', '/home/iik/.local/lib/python3.7/site-packages/wot/commands/resources/graph_layout:/home/iik/.local/lib/python3.7/site-packages/wot/commands/resources/graph_layout/gephi-toolkit-0.9.2-all.jar', 'GraphLayout', '/tmp/gephiznxedn32.net', '/tmp/coordsd64x05ww.txt', 'fa', '10000', '8']' returned non-zero exit status 1.
and following message was found in terminal
Error: Could not find or load main class GraphLayout
I can found "GraphLayout.java" and "gephi-toolkit-0.9.2-all.jar" files in the path, so I really don't know why it can't be loaded.
Do you have any suggestions?
Add *
The class GraphLayout is not contained in Gephi but defined by GraphLayout.java.

Start Java Application using System.Diagnostics.Process

$startCount = 5;
$processors = Get-WmiObject -Class Win32_ComputerSystem | select -
ExpandProperty "NumberOfLogicalProcessors";
$perInstance = $processors / $startCount;
$affinityloop = 1;
$affinityvalue = 0;
for($i=1; $i -le $startCount; $i++) {
$affinityvalue = 0;
for($u=1; $u -le $perInstance ; $u++) {
$affinityvalue = $affinityvalue + $affinityloop;
$affinityloop = $affinityloop * 2;
}
$ps = new-object System.Diagnostics.Process;
$ps.StartInfo.Filename = "C:\jdk\bin\java.exe";
$ps.StartInfo.Arguments = " -server -Xms10240m -Xmx10240m -XX:+UseG1GC -cp `".;*`" Worker";
$ps.start();
Write-Host $affinityvalue ;
$ps.ProcessorAffinity = [Convert]::ToString($affinityvalue, 16);
}
I am trying to start a Windows Java application on two different NUMA nodes. Has anyone able to accomplish this with Diagnostics.Process format? This code does work fine, but all applications created are on the same NUMA node and hence only using 50% power.
I tried codes such as $mod = ($i % 2); to help prepare for some way to alternate the NUMA node but unsure how to specify it within the script.
EDIT
Tried to load balance with ProcessorAffinity and I get crashes due to Double unable to convert to IntPtr
EDIT 2
So it looks like Windows Groups the processors past 64 into Groups. Can't seem to find a way to alter that like ProcessAffinity. I guess its just not that common. You can easily do it in Task manager, just need to find a way to do it in Powershell or similar.

RMI Client invokes Graceful shutdown. Server Stops. Manually started again. But somehow gets autokilled. Why?

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.

Using Powershell invoke-expression to uninstall Java on all domain computers

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.

Categories

Resources