Find status of Windows service from Java application? - java

How to check the status of the windows services from a java program?

on the following example you can find how can you check windws service status and you can parsed to do certain action
import java.util.*;
import java.sql.*;
import java.io.*;
import java.text.*;
public class doscmd
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("sc query browser");
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
if(line.trim().startsWith("STATE"))
{
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("1"))
System.out.println("Stopped");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("2"))
System.out.println("Startting....");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("3"))
System.out.println("Stopping....");
else
if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("4"))
System.out.println("Running");
}
line=reader.readLine();
}
}
catch(IOException e1) { }
}
}

At the very least you should be able to launch a cmd.exe process with the command sc query service-name and parse the output to determine the status. Not pretty, but lacking a Java API to the Windows service manager this would be a viable alternative.
EDIT - Read the Javadoc for java.lang.ProcessBuilder, which will allow you to execute an external command. You should probably set the redirectErrorStream property so that you don't have to handle two input streams (stdout and stderr), making for a much simpler design.

This method will return true or false depending upon service is running or not.
public boolean checkIfServiceRunning(String serviceName) {
Process process;
try {
process = Runtime.getRuntime().exec("sc query " + serviceName);
Scanner reader = new Scanner(process.getInputStream(), "UTF-8");
while(reader.hasNextLine()) {
if(reader.nextLine().contains("RUNNING")) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

Related

getRuntime().exec() does nothing

I want a java program to execute the following shell command:
apktool.jar d /path/to/my/app.apk
This command perfectly works when executing it directly on command line.
Java Code:
public static void main(String[] args) {
String command = "apktool d /path/to/my/app.apk";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
e1.printStackTrace();
}
}
There is no error, no exception. Nothing happens and i have the impression that I already searched the entire internet for a solution. Does anybody know what I am doing wrong? A simple command like
mkdir /path/to/a/new/folder
works without problems.
I tried the same using ProcessBuilder:
try {
Process process = new ProcessBuilder(command).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This time i only get "Cannot run program "apktool d /path/to/my/app.apk, No such file or directory". I can't even run the mkdir command.
You need to call the jar with java.exe, and you're not doing that. Also you need to trap the input and error streams from the process, something you can't do the way you're running this. Use ProcessBuilder instead, get your streams and then run the process.
For example (and I can only do a Windows example),
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ProcessEg {
private static Process p;
public static void main(String[] args) {
String[] commands = {"cmd", "/c", "dir"};
ProcessBuilder pBuilder = new ProcessBuilder(commands);
pBuilder.redirectErrorStream();
try {
p = pBuilder.start();
InputStream in = p.getInputStream();
final Scanner scanner = new Scanner(in);
new Thread(new Runnable() {
public void run() {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
try {
int result = p.waitFor();
p.destroy();
System.out.println("exit result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Try doing it like this:
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec("./path/apktool d /path/to/my/app.apk");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
system.out.println(output.toString());
Creating first a process allows you to wait for a response and reads the output of the execution of your process.
If something is failing while running your shell command, you will have the error printed at the end.
Also, make sure your java program can access your shell script, or better provide the full path to it like:
./path/to/shell/apktool d /path/to/my/app.apk

Setting a hotkey in a Java program that exits, without a GUI

I'm writing a program that will run continuously and I was wondering if there was a Java equivalent to the Autoit SetHotKey(Key, Action()). I saw an answer on here that related to a GUI interface, but my program does not have a GUI. I just want the program to exit whenever I press a certain key, preferably ESC.
I'd have the program running in an infinite loop using the awt.Robot's keyevents, I'd like to be able to quit the program by pressing a certain key.
There are no core Java solutions since Java was built to be as operating system agnostic as possible, and to achieve your goal, you need a program that can integrate closer to the OS. The main solutions that I know of are to integrate your program to the OS via JNA, JNI, or (my favorite), AutoIt. Of done something similar by simply having my Java program and AutoIt communicate through standard IO and sockets.
A simple example:
Java program, TrialAutoIt3a.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class TrialAutoIt3a {
// ***** of course your path to program will be different
private static final String AUTOIT_PATH = "C:/Users/Pete/Documents/Programming/AutoIt/Experiment/";
private static final String AUTOIT_EXEC = "TestWithJava.exe";
protected static final CharSequence EXIT = "exit";
private static Process proc = null;
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("Type \"exit\" to exit program");
try {
proc = rt.exec(AUTOIT_PATH + AUTOIT_EXEC);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
InputStream iStream = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(iStream);
final BufferedReader bufReader = new BufferedReader(isr);
OutputStream oStream = proc.getOutputStream();
final PrintWriter pw = new PrintWriter(oStream, true);
Runnable bufReaderRunnable = new Runnable() {
public void run() {
String output;
try {
while ((output = bufReader.readLine()) != null) {
System.out.println(output);
if (output.toLowerCase().contains(EXIT)) {
proc.destroy();
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(bufReaderRunnable).start();
Runnable myRun = new Runnable() {
public void run() {
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
pw.println(line);
}
scan.close();
}
};
new Thread(myRun).start();
}
}
AutoIt program, TestWithJava.au3:
Local $line = ""
While (True)
$line = $line & ConsoleRead()
If StringInStr($line, #CR) Or StringInStr($line, #LF) Then
ConsoleWrite($line & "to java" & #CRLF)
$line = ""
EndIf
Sleep(25)
WEnd
The AutoIt program will be compiled to an exe file prior to running this program

Java Applet to ping an IP address

I made this code and it gives the following 3 errors! I need help to get away with these errors that are there in the attached image. The 3 errors that are arising aren't going away since i don't have much info about how to include system commands.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EventListeners extends Applet
implements ActionListener{
public void init(){
Button b = new Button("Ping");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent e){
runSystemCommand(String command)
{try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}}
catch (Exception e) {
e.printStackTrace();
}}
public static void main(String[] args) {
String ip = "google.com";
runSystemCommand("ping " + ip);
}
}
![Errors][1]
You seem to be trying to write a function within a method. This is illegal in Java
Place you runSystemCommand method out side the actionPerformed method
public void actionPerformed(ActionEvent e) {
// Call runSystemCommand(...);
}
public void runSystemCommand(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Some caveats...
Applets run in a tight security sandbox. It will NOT allow you to run system commands. Even if it, you could possible be running on a Linux or Mac box instead of Windows.
If you want to start with GUI program, start with something like JFrame, much easier to work with
I would also suggest getting your hands on a suitable IDE

Java Runtime.exec() -- Is it possible to synchronize stream output with wait()/notify()?

I have implemented a simple external process executor in Java using Runtime.exec(). I have implemented a "stream gobbler" class that consumes process output from the process's output stream and error stream. My code waits for the external process to complete using Process.waitFor(), then I print the process return code.
The problem I'm experiencing is that the process ends before the "stream gobblers" have finished printing, so in my Java output (System.out), the returned exit code appears in the middle of the process output/error lines.
My question is, Is it possible to synchronize the output on System.out using wait()/notify() instead of polling the alive status of each StreamGobbler in a while loop?
Here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class RuntimeExecExample
{
private enum StreamType
{
OUTPUT,
ERROR
}
public class MyStreamGobbler extends Thread
{
private InputStream is;
StreamType type;
public MyStreamGobbler(InputStream is, StreamType type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line=null;
while ( (line = br.readLine()) != null)
{
System.out.println(type.toString() + ">" + line);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public void executeCommand(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
String commandLine = "";
for(String cmdItem : args)
{
commandLine += " " + cmdItem;
}
System.out.println("Exec-ing " + commandLine);
Process proc = rt.exec(args);
// any error message?
MyStreamGobbler errorGobbler = new MyStreamGobbler(proc.getErrorStream(), StreamType.ERROR);
// any output?
MyStreamGobbler outputGobbler = new MyStreamGobbler(proc.getInputStream(), StreamType.OUTPUT);
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
/*
* Wait for both to finish before printing exit value
* IS THERE A WAY TO DO THIS WITH wait()/notify() ??
*/
while(errorGobbler.isAlive())
;
while(outputGobbler.isAlive())
;
System.out.println("ExitValue: " + exitVal);
}
catch (Throwable t)
{
t.printStackTrace();
}
}
public static void main(String args[])
{
if(args.length < 1)
{
System.out.println("USAGE: java RuntimeExecExample <cmd> [<arg1> <arg2> ..]");
System.exit(1);
}
else
{
RuntimeExecExample runtimeExecExample = new RuntimeExecExample();
runtimeExecExample.executeCommand(args);
}
}
}
In your main thread, as well as doing a waitFor() the sub-process to finish, also do errorGobbler.join() and outputGobbler.join(), then you won't need the while(xGobbler.isAlive()).
First, you should call join() on any thread that you start.
Second, System.out is buffered, so that might explain it. Try calling System.out.flush() before reading the contents.
A way to know whether it's a buffering issue would be to temporarily change your invoked process to write into System.err instead of System.out. System.err is not buffered.

Pinging computer by name in Java

I am in the process of writing a simple program that extracts computer names from MySQL Database then stores those names into a String array list (this part works fine). After that I wrote a class and a method that takes a String as a parameter (which will be the computer name) and tries to ping it. Here is the code for that class:
public class Ping
{
public void pingHost(String hostName)
{
try
{
InetAddress inet = InetAddress.getByName(hostName);
boolean status = inet.isReachable(5000);
if (status)
{
System.out.println(inet.getHostName() + " Host Reached\t" + inet.getHostAddress());
}
else
{
System.out.println(inet.getHostName() + " Host Unreachable");
}
}
catch (UnknownHostException e)
{
System.err.println(e.getMessage() + " Can't Reach Host");
}
catch (IOException e)
{
System.err.println(e.getMessage() + " Error in reaching the Host");
}
}
The problem is that I keep getting UnknownHostException thrown for most computers even if I can ping them manually or if I hard code the computer name as the "hostName".
Here is what my main looks like:
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
ArrayList <String> list = new ArrayList<String>();
MySQLConnect myConnection = new MySQLConnect();
myConnection.importData(list);
Ping pingComputer = new Ping();
pingComputer.pingHost(list.get(87));
}
Right now I'm just trying to experiment with one computer which is throwing UnknownHostException but can be pinged manually. Anyone have any idea why this is happening?
EDIT...
Just to explain this a little bit more. For example in main, if I pass these parameters to pingHost:
pingComputer.pingHost("ROOM-1234");
It pings fine and returns correct host name/address. But list.get(87) returns same host name "ROOM-1234" but throws UnknownHostException? This has got me really confused and not sure why its not working.
EDIT
Wow finally figured it out. Reason ping was working when I was passing the string directly like so "ROOM-1234", was because there were no white spaces and getting is from array like so list.get(87) returned same thing but when I checked charLength, it returned a different value :) So I just ended up using trim to get rid of white spaces and now itworks great.
pingComputer.pingHost(list.get(87).trim());
Thanks for all the suggestions!
Dear Actually the code you are using is to check whether the host is reachable or not.
Use following class to ping windows pc use ping method but for other than windows pc use isreachable.
package com.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Ping {
public Boolean IsReachable(String ipaddress) {
try {
final InetAddress host = InetAddress.getByName(ipaddress);
try {
return host.isReachable(3000);
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return false;
}
public Boolean ping(String ipaddress) {
Runtime runtime = Runtime.getRuntime();
String cmds = "ping " + ipaddress;
System.out.println(cmds);
Process proc;
try {
proc = runtime.exec(cmds);
proc.getOutputStream().close();
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
if (line.contains("Reply from " + ipaddress + ":")) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
And use as below code
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
MySQLConnect myConnection = new MySQLConnect();
myConnection.importData(list);
Ping ping = new Ping();
if (ping.ping(list.get(87)) {
System.out.prinln("Online / Host is reachable");
} else {
System.out.prinln("Offline /Host is unreachable");
}
}
But I would suggest ping by ip address is better than pinging with computer name.

Categories

Resources