PageRenderTime 243ms CodeModel.GetById 120ms app.highlight 8ms RepoModel.GetById 113ms app.codeStats 0ms

/src/org/ooc/utils/ShellUtils.java

http://github.com/nddrylliog/ooc
Java | 102 lines | 69 code | 18 blank | 15 comment | 17 complexity | 6495298e8951ff90420fa3e81f2bffc2 MD5 | raw file
  1package org.ooc.utils;
  2
  3import java.io.File;
  4import java.io.StringWriter;
  5import java.util.Map;
  6import java.util.StringTokenizer;
  7
  8import org.ubi.CompilationFailedError;
  9
 10/**
 11 * Utilities for launching processes
 12 *  
 13 * @author Amos Wenger
 14 */
 15public class ShellUtils {
 16
 17	public static File findExecutable(String executableName) {
 18		return findExecutable(executableName, false);
 19	}
 20	
 21	/**
 22	 * @return the path of an executable, if it can be found. It looks in the PATH
 23	 * environment variable.
 24	 */
 25	public static File findExecutable(String executableName, boolean crucial) {
 26		
 27		Map<String, String> env;
 28		try {
 29			env = System.getenv();
 30		} catch(Exception e) {
 31			e.printStackTrace();
 32			return null;
 33		}
 34		
 35		String pathVar = env.get("PATH");
 36		if(pathVar == null) {
 37			pathVar = env.get("Path");
 38			if(pathVar == null) {
 39				pathVar = env.get("path");
 40			}
 41		}
 42		
 43		if(pathVar == null) {
 44			env = ReadEnv.getEnv();
 45			pathVar = env.get("PATH");
 46			if(pathVar == null) {
 47				pathVar = env.get("Path");
 48				if(pathVar == null) {
 49					pathVar = env.get("path");
 50				}
 51			}
 52		}
 53		
 54		if(pathVar == null) {
 55			System.err.println("PATH environment variable not found!");
 56			return null;
 57		}
 58	
 59		StringTokenizer st = new StringTokenizer(pathVar, File.pathSeparator);
 60		while(st.hasMoreTokens()) {
 61			String path = st.nextToken();
 62			File file = new File(path, executableName);
 63			if(file.exists() && file.isFile()) {
 64				return file;
 65			}
 66		}
 67		
 68		if(crucial) {
 69			throw new CompilationFailedError(null, "Couldn't find '"+executableName+"' on your system. PATH = "+pathVar);
 70		}
 71		return null;
 72		
 73	}
 74
 75	/**
 76	 * Run a command to get its output
 77	 * @param command
 78	 * @return the output of the command specified, once it has exited
 79	 */
 80	public static String getOutput(String... command) {
 81		
 82		String result = null;
 83		
 84		try {
 85			StringWriter writer = new StringWriter();
 86			Process p = new ProcessBuilder(command).start();
 87			ProcessUtils.redirectIO(p, writer);
 88			int exitCode = p.waitFor();
 89			if(exitCode == 0) {
 90				result = writer.toString();
 91			}
 92			writer.close();
 93		} catch (Exception e) {
 94			/* Exception? Will return null */
 95			e.printStackTrace();
 96		}
 97		
 98		return result;
 99		
100	}
101	
102}