1 package jester; 2 3 import java.io.*; 4 import java.util.Vector ; 5 6 public class Util { 7 public static Vector runCommand(String [] cmd, Logger aLogger) throws IOException { 8 9 StringBuffer sb = new StringBuffer (cmd[0]); 10 for (int i = 1; i < cmd.length; i++) { 11 sb.append(' '); 12 sb.append(cmd[i]); 13 } 14 String commandLine = sb.toString(); 15 16 aLogger.log("Trying to run command \"" + commandLine + "\""); 17 Process proc = Runtime.getRuntime().exec(cmd); 18 19 BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); 20 BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream())); 21 22 Vector output = new Vector (); 23 String str; 24 while ((str = br.readLine()) != null) { 25 output.addElement(str); 26 } 27 boolean firstLine = true; 28 while ((str = err.readLine()) != null) { 29 if (firstLine) { 30 System.out.println("ERR> NOTE - jester has tried to 'exec' \"" + commandLine + "\""); 31 } 32 firstLine = false; 33 System.out.println("ERR> " + str); 34 if (str.indexOf("NoClassDefFound") != -1) { 35 System.out.println("ERR> NOTE - the simplest way to get Jester to work is to put everything on the static classpath"); 36 } 37 } 38 try { 39 proc.waitFor(); 40 } catch (InterruptedException e) { 41 aLogger.log("process was interrupted for " + commandLine); 42 } 43 br.close(); 44 err.close(); 45 46 aLogger.log("running command \"" + commandLine + "\" resulted in \"" + output + "\""); 47 48 int exitValue = proc.exitValue(); 49 if (exitValue != 0) { 50 throw new IOException("runCommand exit value " + exitValue + " indicates that " + commandLine + " didn't work"); 51 } 52 53 return output; 54 } 55 56 public static String readFile(String fileName) throws IOException { 57 Reader reader = new FileReader(fileName); 58 try { 59 return readContents(reader); 60 } finally { 61 reader.close(); 62 } 63 } 64 65 private static String readContents(Reader reader) throws IOException { 66 StringBuffer buff = new StringBuffer (); 67 68 int currentCharacter; 69 while (true) { 70 currentCharacter = reader.read(); 71 if (currentCharacter == -1) { 72 break; 73 } 74 buff.append((char) currentCharacter); 75 } 76 77 return buff.toString(); 78 } 79 80 private static String readContentsIgnoringCarrageReturns(Reader reader) throws IOException { 82 StringBuffer buff = new StringBuffer (); 83 BufferedReader lineReader = new BufferedReader(reader); 84 85 String line = lineReader.readLine(); 86 while (line != null) { 87 buff.append(line+"\n"); 88 line = lineReader.readLine(); 89 } 90 91 return buff.toString(); 92 } 93 94 public static String readFileOnClassPath(String fileName) throws IOException { 95 InputStream fileInputStream = ClassLoader.getSystemResourceAsStream(fileName); 96 if (fileInputStream==null){ 97 throw new FileNotFoundException("Could not find "+fileName+" on the classpath"); 98 } 99 return readContentsIgnoringCarrageReturns(new InputStreamReader(fileInputStream)); 100 } 101 } | Popular Tags |