Saturday 28 June 2014

Read Process Id From Console For Port Using Java

Read Process Id From Console For Port Using Java




/**
 * ProcessFromConsole.java
 * Jun 20, 2014
 *
 */
package org.util.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

public class ProcessFromConsole {

protected static Logger logger = Logger.getLogger(ProcessFromConsole.class);

private String portNO;

/**
* @return the portNO
*/
public String getPortNO() {
return portNO;
}

/**
* @param portNO
*            the portNO to set
*/
public void setPortNO(String portNO) {
this.portNO = portNO;
}

/**
* method used to get process id
*
* @return
* @throws IOException
*/
public String getProcessId() throws IOException {
return readProcessIdFromConsole();
}

/**
* read process id from console
*
* @return
* @throws IOException
*/
private String readProcessIdFromConsole() throws IOException {
logger.info(" Enter method readProcessIdFromConsole ");
String processId = "";
String os = System.getProperty("os.name");
if (os.toLowerCase().indexOf("win") >= 0) {
// URL path = ProcessFromConsole.class.getResource("pid.bat");

File file = new File("pid.bat");
String command = "netstat -a -n -o | find \"" + this.portNO + "\"";
if (!file.exists()) {
file.delete();
file.createNewFile();
}
logger.info(" ReadProcessIdFromConsole Path " + file.getPath());
FileWriter fw = new FileWriter(file.getPath());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(command);
bw.close();
Process process = Runtime.getRuntime().exec(file.getPath());
BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
// System.out.println(" line " + line);
int startIndex = line.indexOf("LISTENING");
int len = "LISTENING".length();
if (startIndex > 0) {
// System.out.println("line: " + line + " Port " +
// (line.substring(startIndex + len)));
processId = line.substring(startIndex + len);
processId = processId.trim();
}

}
}
logger.info(" Enter method readProcessIdFromConsole ");
return processId;
}

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ProcessFromConsole fromConsole = new ProcessFromConsole();
fromConsole.setPortNO("8383");
System.out.println(fromConsole.getProcessId());
}

}