Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, November 4, 2012

Null Check in different language


Python - Null Check

15 or "default"       # returns 15
0 or "default"         # returns "default"
None or "default"    # returns "default"
False or "default"    # returns "default"

Django Template - None Check


{{obj.item_value|default_if_none:"smile"}}

C# - Null Check

var data = val ?? "default value";

Java - Null check

Foo f = new Foo();
DummyObj obj = new Obj().getSelection();
String str = obj != null ? f.format(obj) : "";

Javscript - Null/Undefined check

if (! param) param = "abc";
//other way to check this
if (param == null) is same as if(!param)


jQuery - Null/existence check

if ( $('#myDivObj').length ) {}

Feel free to add comments and other languages Null check mechanism (inline or explicit) 

Saturday, May 8, 2010

Windows process/service killing, Get process Id using Java

Recently I came across the situation where I need to automate the finding process id, and kill some windows services based on the value provided in the dashboard. You can read the values at certain interval and complete the actions like killing services, or monitor the process ids, or get list of processes start with same prefix.., hope below helps..


Killing the Service using Java; example code is below –

log.info("Forcefully Killing Services - Taskkill command length: "+arg.length);

String cmd = "cmd.exe /c taskkill /s "+ +" /fi \"services eq "+ +"\" /f >d:\\temp\\log\\output.txt";

//e.g. taskkill /f /im notepad.exe or taskkill /PID 827

log.info("Command to Execute: "+cmd);

//execute the command
Process process = Runtime.getRuntime().exec(cmd);

If you want to get the process id of the service -
log.info("Getting PID - Tasklist command length: "+arg.length);

String cmd = "cmd.exe /c tasklist /s "+ +" /svc /fi \"services eq "+ +"\">d:\\tdp\\log\\output.txt";

//here service name can be prefix, like note*, it will list all the services which starts with note prefix.

log.info("Command to Execute: "+cmd);

Process process = Runtime.getRuntime().exec(cmd);

//to do a synchronous action till you get the result
int exitVal = process.waitFor();

//to check success or failure
log.info("Process exitValue: " + exitVal);

- You can take different actions on the services, and there are other task commands which can be automated using the above steps. However, its not much advisable to use Runtime.getRuntime().exec(). As in case of success or failure you will not always get correct results, sometimes it just stay in the hanging stage. And to read the output, it requires to read the process.getErrorStream(); or you can just move the output to some txt as I am doing in above example...