Path: blob/master/test/functional/CacheManagement/src/tests/sharedclasses/RunCommand.java
6004 views
/*******************************************************************************1* Copyright (c) 2010, 2019 IBM Corp. and others2*3* This program and the accompanying materials are made available under4* the terms of the Eclipse Public License 2.0 which accompanies this5* distribution and is available at https://www.eclipse.org/legal/epl-2.0/6* or the Apache License, Version 2.0 which accompanies this distribution and7* is available at https://www.apache.org/licenses/LICENSE-2.0.8*9* This Source Code may also be made available under the following10* Secondary Licenses when the conditions for such availability set11* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU12* General Public License, version 2 with the GNU Classpath13* Exception [1] and GNU General Public License, version 2 with the14* OpenJDK Assembly Exception [2].15*16* [1] https://www.gnu.org/software/classpath/license.html17* [2] http://openjdk.java.net/legal/assembly-exception.html18*19* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception20*******************************************************************************/2122package tests.sharedclasses;2324import java.io.InputStream;2526import java.util.*;27import java.io.*;2829/**30* Instances of StreamGobbler are used to capture output from the spawned process31*/32class StreamGobbler extends Thread {33private InputStream is; // Can be used for stderr/stdout34private String type; // some identifier tag for this gobbler (possibly STDERR or STDOUT)3536private List<String> expected = new ArrayList<String>(); // Expected lines of output to be found in the gobbled output37private String waitForMessage;3839private StringBuffer gobbledData = new StringBuffer();40private List lines = new ArrayList();41public volatile boolean finished = false;42public volatile boolean waitForMessageFound = false;43public volatile boolean ignoreRest = false;4445StreamGobbler(InputStream is, String type, String[] expected, String waitForMessage) {46this.is = is;47this.type= type;48this.waitForMessage = waitForMessage;49if (expected!=null) {50for (int i = 0; i < expected.length; i++) {51String string = expected[i];52if (string!=null)53this.expected.add(string);54}55}56}5758public String getType() { return type; }5960public void run() {61try {62InputStreamReader isr = new InputStreamReader(is);63BufferedReader br = new BufferedReader(isr);64String line=null;65while ( (line = br.readLine()) != null) {66//System.out.println(type + ">" + line);67gobbledData.append(/*type + ">" + */line+"\n");68lines.add(line);69int pos = 0;70int found =-1;71for (Iterator iterator = expected.iterator(); iterator.hasNext();) {72String name = (String) iterator.next();73if (line.indexOf(name) != -1) {74found = pos;75break;76}77pos++;78}79if (found != -1) {80expected.remove(found);81}82if ((false == waitForMessageFound) && (null != waitForMessage) && (line.indexOf(waitForMessage) != -1)) {83waitForMessageFound = true;84}85}86finished=true;87} catch (IOException ioe) {88if (ignoreRest == false) {89ioe.printStackTrace();90}91}92}9394public boolean allExpectedMessagesWereFound() {95return expected.isEmpty();96}9798public void dumpOutput() {99System.out.println(gobbledData.toString());100}101102public String getOutput() {103return gobbledData.toString();104}105106public String[] getOutputAsLines() {107return (String[])lines.toArray(new String[]{});108}109}110111public class RunCommand {112private static Process lastProcess;113public static String lastCommand, the2ndLastCommand;114public static String lastCommandStdout, the2ndLastCommandStdout;115public static String[] lastCommandStdoutLines;116public static String lastCommandStderr, the2ndLastCommandStderr;117public static String[] lastCommandStderrLines;118public static boolean logCommands = false;119public static int processRunawayTimeout = 120000; // 2 min timer, kill process if its taking longer!120121/* if the process executed last is still running, it returns the process object, else returns null */122public static Process getLastProcess() {123try {124if (null != lastProcess) {125lastProcess.exitValue();126}127/* process got terminated */128return null;129} catch (IllegalThreadStateException e) {130/* process is still running */131return lastProcess;132}133}134135public static void executeMayFail(String cmd) {136execute(cmd,(String[])null,(String[])null,true,true, null);137}138139public static void execute(String cmd) {140execute(cmd,(String[])null,(String[])null,true,false, null);141}142143public static void execute(String cmd,boolean careAboutExitValue) {144execute(cmd,(String[])null,(String[])null,careAboutExitValue,false, null);145}146147public static void execute(String cmd, String waitForMessage) {148execute(cmd,(String[])null, (String[])null, false, false, waitForMessage);149}150151public static void execute(String cmd,String sysoutMessages,String syserrMessages,boolean careAboutExitValue) {152execute(cmd,new String[]{sysoutMessages},new String[]{syserrMessages},careAboutExitValue,false, null);153}154155public static void execute(String cmd,String[] expectedSysoutMessages,String[] expectedSyserrMessages,boolean careAboutExitValue, boolean MayFail, String waitForMessage)156{157int exitVal = 0;158Runtime rt = Runtime.getRuntime();159the2ndLastCommand = lastCommand;160the2ndLastCommandStdout = lastCommandStdout;161the2ndLastCommandStderr = lastCommandStderr;162lastCommand = null;163lastCommandStdout = null;lastCommandStderr = null;164lastCommandStdoutLines = null;lastCommandStderrLines = null;165lastProcess = null;166167try {168if (logCommands) {169System.out.println("Executing command: "+cmd);170}171long processStartTime = System.currentTimeMillis();172lastProcess = rt.exec(cmd);173// any error message?174StreamGobbler errorGobbler = new175StreamGobbler(lastProcess.getErrorStream(), "ERROR",expectedSyserrMessages, null);176177// any output?178StreamGobbler outputGobbler = new179StreamGobbler(lastProcess.getInputStream(), "OUTPUT",expectedSysoutMessages, waitForMessage);180181// kick them off182errorGobbler.start();183outputGobbler.start();184185// any error???186if (null == waitForMessage) {187exitVal = lastProcess.waitFor();188while (!outputGobbler.finished || !errorGobbler.finished) {189try { Thread.sleep(250); } catch (Exception e) {}190if ((System.currentTimeMillis()-processStartTime)>processRunawayTimeout) {191// kill the process, it is taking too long!192lastProcess.destroy();193try {194lastProcess.waitFor();195} catch (java.lang.InterruptedException e) {196e.printStackTrace();197}198System.err.println("Process killed, was executing for longer than "+(processRunawayTimeout/1000)+"seconds");199}200}201202lastCommandStdout = outputGobbler.getOutput();203lastCommandStderr = errorGobbler.getOutput();204lastCommandStdoutLines = outputGobbler.getOutputAsLines();205lastCommandStderrLines = errorGobbler.getOutputAsLines();206lastCommand = cmd;207if (!outputGobbler.allExpectedMessagesWereFound()) {208outputGobbler.dumpOutput();209errorGobbler.dumpOutput();210throw new RuntimeException("Not all expected messages were found");211}212if (!errorGobbler.allExpectedMessagesWereFound()) {213outputGobbler.dumpOutput();214errorGobbler.dumpOutput();215throw new RuntimeException("Not all expected messages were found");216}217//System.out.println("ExitValue: " + exitVal);218if (careAboutExitValue && exitVal!=0) {219if (MayFail==false) {220outputGobbler.dumpOutput();221errorGobbler.dumpOutput();222throw new RuntimeException("TestFailed: exitvalue="+exitVal);223}224}225} else {226while (false == outputGobbler.waitForMessageFound) {227try {228Thread.sleep(250);229} catch (Exception e) {230}231if ((System.currentTimeMillis() - processStartTime) > processRunawayTimeout) {232// kill the process, it is taking too long!233lastProcess.destroy();234try {235lastProcess.waitFor();236} catch (java.lang.InterruptedException e) {237e.printStackTrace();238}239System.err.println("Process killed, was taking longer than "+(processRunawayTimeout/1000)+" seconds to generate expected output");240}241}242outputGobbler.ignoreRest = true;243errorGobbler.ignoreRest = true;244}245} catch (IOException ioe) {246throw new RuntimeException("Problem invoking command: "+ioe.toString());247} catch (InterruptedException ie) {248throw new RuntimeException("Problem invoking command: "+ie.toString());249}250251}252}253254