/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

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