Path: blob/master/test/functional/CacheManagement/src/tests/sharedclasses/TestUtils.java
6004 views
/*******************************************************************************1* Copyright (c) 2010, 2021 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.File;25import java.io.FileInputStream;26import java.io.FileOutputStream;27import java.io.IOException;28import java.io.InputStream;29import java.net.URL;30import java.util.ArrayList;31import java.util.Enumeration;32import java.util.HashSet;33import java.util.List;34import java.util.Properties;35import java.util.Set;363738/**39* A superclass for test programs that provides lots of helpful methods for setting up40* a shared classes environment and running shared classes commands.41*42* Configuration is done from a config file. The default name is config.properties, which can43* be overridden with a -Dconfig.properties=<pathToConfigFile>44*/45public class TestUtils {4647public static boolean debug = false;4849// Known commands, defined in the config file50public static final String DestroyCacheCommand = "destroyCache";51public static final String DestroyPersistentCacheCommand = "destroyPersistentCache";52public static final String DestroyNonPersistentCacheCommand = "destroyNonPersistentCache";53public static final String RunSimpleJavaProgram = "runSimpleJavaProgram";54public static final String RunComplexJavaProgramWithPersistentCache = "runComplexJavaProgram";55public static final String RunPrintStats = "runPrintStats";56public static final String RunPrintAllStats = "runPrintAllStats";57public static final String RunResetPersistentCache = "runResetPersistentCache";58public static final String RunResetNonPersistentCache = "runResetNonPersistentCache";59public static final String RunSimpleJavaProgramWithPersistentCache = "runSimpleJavaProgramWithPersistentCache";60public static final String RunSimpleJavaProgramWithPersistentCacheCheckStringTable = "runSimpleJavaProgramWithPersistentCacheCheckStringTable";61public static final String RunSimpleJavaProgramWithNonPersistentCache = "runSimpleJavaProgramWithNonPersistentCache";62public static final String CreateNonPersistentCache = "createNonPersistentCache";63public static final String CreateCacheSnapshot = "createCacheSnapshot";64public static final String ListAllCaches = "listAllCaches";65public static final String ExpireAllCaches = "expireAllCaches";66public static final String DestroyAllCaches = "destroyAllCaches";67public static final String DestroyAllSnapshots = "destroyAllSnapshots";68public static final String CreateIncompatibleCache = "createIncompatibleCache";69public static final String RunInfiniteLoopJavaProgramWithPersistentCache = "runInfiniteLoopJavaProgramWithPersistentCache";70public static final String RunInfiniteLoopJavaProgramWithNonPersistentCache = "runInfiniteLoopJavaProgramWithNonPersistentCache";71public static final String ExpireAllCachesWithTime = "expireAllCachesWithTime";72public static final String RunSimpleJavaProgramWithAgentWithPersistentCache = "runSimpleJavaProgramWithAgentWithPersistentCache";73public static final String RunSimpleJavaProgramWithAgentWithNonPersistentCache = "runSimpleJavaProgramWithAgentWithNonPersistentCache";74public static final String RunHanoiProgramWithCache = "runHanoiProgramWithCache";75public static final String CheckJavaVersion = "checkJavaVersion";7677private static final String CMD_PREFIX="cmd.";7879private static boolean isRealtimeDefined = false;8081static Properties config;8283/**84* Load the properties from the configuration file - some of these can be overridden85* with -D - these are cacheDir and controlDir86*/87static {88try {8990config = new Properties();9192// Load the target specific properties ... note that we default to windows ...93String configFile = System.getProperty("test.target.config", "config.defaults");94InputStream is = TestUtils.class.getClassLoader().getResourceAsStream(configFile);95config.load(is);9697if (config.getProperty("logCommands","false").equalsIgnoreCase("true")) {98RunCommand.logCommands=true;99}100101if (config.getProperty("debug","false").equalsIgnoreCase("true")) {102debug = true;103}104// Allow some sys props to override the config105//String override = System.getProperty("cacheDir");106//if (override!=null) config.put("cacheDir",override);107//override = System.getProperty("controlDir");108//if (override!=null) config.put("controlDir",override);109//override = System.getProperty("defaultCacheLocation");110//if (override!=null) config.put("defaultCacheLocation",override);111112// Check if the defaultCacheLocation was set, otherwise lets work it out113if (config.getProperty("defaultCacheLocation")==null) {114if (config.getProperty("cacheDir")==null && config.getProperty("controlDir")==null) {115System.out.println("Please set either defaultCacheLocation or cacheDir or controlDir in the config file or with -D!");116}117}118119if (config.get("apploc")==null) {120// work it out...121URL url = TestUtils.class.getClassLoader().getResource("testcode.jar");122String thePath = new File(url.getFile()).getParentFile().getAbsolutePath();123thePath = thePath.replace('\\','/');124config.put("apploc", thePath);125}126127/* */128String javaTestCommand = System.getProperty("JAVA_TEST_COMMAND","");129String java5home = System.getProperty("JAVA5_HOME","");130String exesuff = System.getProperty("EXECUTABLE_SUFFIX","");131String realtime = System.getProperty("REALTIME","");132javaTestCommand=javaTestCommand.replace('\\','/');133java5home=java5home.replace('\\','/');134135if (!realtime.equals("") && !realtime.equalsIgnoreCase("false")) {136isRealtimeDefined = true;137}138139config.put("java_exe",javaTestCommand);140141config.put("java5_exe",java5home + "/" + "jre" + "/" + "bin" + "/" + "java"+exesuff);142config.put("java5c_exe",java5home + "/" + "bin" + "/" + "javac"+exesuff);143config.put("java5jar_exe",java5home + "/" + "bin" + "/" + "jar"+exesuff);144145146config.put("cmd.runCompileSimpleApp","%java5c_exe% %1%/SimpleApp.java");147config.put("cmd.runCompileSimpleApp2","%java5c_exe% %1%/SimpleApp2.java");148config.put("cmd.runJarClassesInDir","%java5jar_exe% cf MySimpleApp.jar -C %1% .");149config.put("cmd.runProgramSimpleApp","%java_exe% "+(isRealtimeDefined ? "-Xrealtime " : "")+"-Xshareclasses:"+(isRealtimeDefined ? "grow," : "")+"persistent,name=%1%,verbose -classpath %2% SimpleApp");150151System.out.println("\n--------- PROGRAM RUN COMMANDLINE INFO ---------");152System.out.println("java_exe =\t" + config.get("java_exe"));153System.out.println("cmd.runProgramSimpleApp =\t" + config.get("cmd.runProgramSimpleApp" + "\n"));154155if (config.getProperty("logCommands","false").equalsIgnoreCase("true")) {156RunCommand.logCommands=true;157}158159if (exesuff.equals(".exe")==true)160{161String appdata = System.getenv("APPDATA");162String defaultCacheLocation = new File(appdata+"\\..\\Local Settings\\Application Data").getAbsolutePath();163config.put("defaultCacheLocation",defaultCacheLocation);164}165else166{167if (false == isDefaultDirTmp()) {168config.put("defaultCacheGroupAccessLocation","/tmp/");169}170config.put("defaultCacheLocation","/tmp/");171}172173} catch (Exception e) {174e.printStackTrace();175}176}177178public static boolean realtimeTestsSelected(){179return isRealtimeDefined;180}181182public static void registerCommand(String key, String command) {183config.put("cmd."+key,command);184}185186public static String getCacheDir() { return (String)config.get("cacheDir");}187public static String getCacheGroupAccessDir() { return (String)config.get("defaultCacheGroupAccessLocation");}188public static void setCacheDir(String dir) {189if (dir==null) config.remove("cacheDir");190else {191config.put("cacheDir",dir);192}193}194195public static String getControlDir() { return (String)config.get("controlDir");}196public static void setControlDir(String dir) {197if (dir==null) config.remove("controlDir");198else config.put("controlDir",dir);199}200201202203204public static String getCommand(String commandKey) {205return getCommand(commandKey,"","","");206}207208public static String getCommand(String commandKey,String insert1) {209return getCommand(commandKey,insert1,"","");210}211212public static String getCommand(String commandKey,String insert1,String insert2) {213return getCommand(commandKey,insert1,insert2,"");214}215216public static String getCommand(String commandKey,String insert,String insert2,String insert3) {217String theCommand=(String)config.get(CMD_PREFIX+commandKey);218if (theCommand==null) {219fail("Could not find command "+commandKey);220}221Enumeration keys = config.keys();222while (keys.hasMoreElements()) {223String k = (String)keys.nextElement();224if (k.startsWith(CMD_PREFIX)) continue; // not something to apply225String replaceVal = config.getProperty(k);226theCommand = theCommand.replaceAll("%"+k+"%", replaceVal);227}228if (insert!=null) {229230// need to copy with one special case, where we are using a back level231// VM to create an incompatible cache - since it wont understand cacheDir232// yet we want to create the cache in a particular directory. we will233// need to use controlDir in this case...234if (commandKey.equals(CreateIncompatibleCache)) {235if (config.get("cacheDir")!=null) {236insert = insert+",controlDir="+config.getProperty("cacheDir"); // gotta use controlDir...237}238if (config.get("controlDir")!=null) {239insert = insert+",controlDir="+config.getProperty("controlDir");240}241}242else if (commandKey.equals("runCompileSimpleApp") || commandKey.equals("runCompileSimpleApp2") ||commandKey.equals("runJarClassesInDir"))243{244245}246//getCacheFileName getCacheFileNameNonPersist247else {248249// Insert %1% is always the cache name "name=%1%"250// we can add subsequent options through a tiny extension to that251if (config.get("cacheDir")!=null) {252insert = insert+",cacheDir="+config.getProperty("cacheDir");253}254if (config.get("controlDir")!=null) {255insert = insert+",controlDir="+config.getProperty("controlDir");256}257}258theCommand = fixup(theCommand,"%1%",insert);259theCommand = fixup(theCommand,"%2%",insert2);260theCommand = fixup(theCommand,"%3%",insert3);261}262return theCommand;263}264265public static String fixup(String what,String from,String to) {266String result = what;267int idx = what.indexOf(from);268while (idx!=-1) {269StringBuffer s = new StringBuffer(what.substring(0,idx));270s.append(to);271s.append(what.substring(idx+from.length()));272what = s.toString();273idx = what.indexOf(from);274}275return what;276}277278public static void createNonPersistentCache(String cachename) {279log("Creating non-persistent cache '"+cachename+"'");280RunCommand.execute(getCommand(CreateNonPersistentCache,cachename));281}282283public static void createCacheSnapshot(String cachename) {284log("Creating snapshot of cache'" + cachename + "'");285String expectedErrorMessages[] = new String[] {286"JVMSHRC700I" /* Snapshot of non-persistent shared cache <cachename> has been created */287};288RunCommand.execute(getCommand(CreateCacheSnapshot, cachename), null, expectedErrorMessages, false, false, null);289}290291public static void createPersistentCache(String cachename) {292log("Creating persistent cache '"+cachename+"'");293RunCommand.execute(getCommand(RunSimpleJavaProgram,cachename));294}295296297public static void listAllCaches() {298RunCommand.execute(getCommand(ListAllCaches),false);299}300301public static void expireAllCaches() {302RunCommand.execute(getCommand(ExpireAllCaches),false);303}304305public static void expireAllCachesWithTime(String timeInMins) {306RunCommand.execute(getCommand(ExpireAllCachesWithTime, timeInMins),false);307}308309public static void runDestroyAllCaches() {310RunCommand.execute(getCommand(DestroyAllCaches),false);311}312313public static void runDestroyAllGroupAccessCaches() {314RunCommand.execute(getCommand(DestroyAllCaches, ",groupaccess"),false);315}316317public static void runDestroyAllSnapshots() {318RunCommand.execute(getCommand(DestroyAllSnapshots), false);319}320321public static void createIncompatibleCache(String cachename) {322RunCommand.execute(getCommand(CreateIncompatibleCache,cachename));323}324325public static void runSimpleJavaProgram(String cachename) {326RunCommand.execute(getCommand(RunSimpleJavaProgram,cachename));327}328329public static void checkJavaVersion() {330RunCommand.execute(getCommand(CheckJavaVersion), false);331}332333/**334* @example runPrintStats("foo",false,"classpath");335* @example runPrintStats("foo",false,"url");336* @example runPrintStats("foo",false,"token");337* @example runPrintStats("foo",false,"romclass");338* @example runPrintStats("foo",true,"rommethod");339* @example runPrintStats("foo",true,"aot");340* @example runPrintStats("foo",true,"jitprofile");341* @example runPrintStats("foo",true,"zipcache");342*/343public static void runPrintStats(String cachename,boolean isPersistent, String option) {344RunCommand.execute(getCommand(RunPrintStats,cachename,"="+option,(isPersistent?"":",nonpersistent")),false);345}346public static void runPrintStats(String cachename,boolean isPersistent) {347RunCommand.execute(getCommand(RunPrintStats,cachename,"",(isPersistent?"":",nonpersistent")),false);348}349350public static void runResetPersistentCache(String cachename) {351RunCommand.execute(getCommand(RunResetPersistentCache,cachename),false);352}353354public static void runResetNonPersistentCache(String cachename) {355RunCommand.execute(getCommand(RunResetNonPersistentCache,cachename),false);356}357358public static void runPrintAllStats(String cachename,boolean isPersistent) {359RunCommand.execute(getCommand(RunPrintAllStats,cachename,(isPersistent?"":",nonpersistent")),false);360}361public static void runSimpleJavaProgramWithPersistentCache(String cachename) {362RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename));363checkOutputForDump(false);364}365public static void runSimpleJavaProgramWithPersistentCacheCheckStringTable(String cachename) {366RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCacheCheckStringTable,cachename));367checkOutputForDump(false);368}369public static void runSimpleJavaProgramWithPersistentCache(String cachename,boolean careAboutExitValue) {370RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename),careAboutExitValue);371checkOutputForDump(false);372}373public static void runSimpleJavaProgramWithPersistentCacheCheckForDump(String cachename) {374RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename));375checkOutputForDump(true);376}377public static void runSimpleJavaProgramWithPersistentCacheCheckForDump(String cachename, boolean careAboutExitValue) {378RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename), careAboutExitValue);379checkOutputForDump(true);380}381/* waitForMessage is the message for which this process waits */382public static void runInfiniteLoopJavaProgramWithPersistentCache(String cachename, String waitForMessage) {383RunCommand.execute(getCommand(RunInfiniteLoopJavaProgramWithPersistentCache, cachename), waitForMessage);384checkOutputForDump(false);385}386/* waitForMessage is the message for which this process waits */387public static void runInfiniteLoopJavaProgramWithNonPersistentCache(String cachename, String waitForMessage) {388RunCommand.execute(getCommand(RunInfiniteLoopJavaProgramWithNonPersistentCache, cachename), waitForMessage);389checkOutputForDump(false);390}391392/**393* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified394* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.395* @param cachename name of the cache to use396* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"397*/398public static void runSimpleJavaProgramWithPersistentCache(String cachename,String extraSharedClassesOptions) {399// this hides the magic rule that due to the command construction, the "name=" is always the last part of the400// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append401// them to the cache name.402runSimpleJavaProgramWithPersistentCache(cachename+403(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""));404}405406/**407* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified408* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.409* @param cachename name of the cache to use410* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"411* @param waitForMessage message for which this process waits412*/413public static void runInfiniteLoopJavaProgramWithPersistentCache(String cachename,String extraSharedClassesOptions,String waitForMessage) {414// this hides the magic rule that due to the command construction, the "name=" is always the last part of the415// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append416// them to the cache name.417runInfiniteLoopJavaProgramWithPersistentCache(cachename+418(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""), waitForMessage);419}420421/**422* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified423* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.424* @param cachename name of the cache to use425* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"426*/427public static void runSimpleJavaProgramWithNonPersistentCache(String cachename,String extraSharedClassesOptions) {428// this hides the magic rule that due to the command construction, the "name=" is always the last part of the429// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append430// them to the cache name.431runSimpleJavaProgramWithNonPersistentCache(cachename+432(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""));433}434435/**436* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified437* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.438* @param cachename name of the cache to use439* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"440* @param waitForMessage message for which this process waits441*/442public static void runInfiniteLoopJavaProgramWithNonPersistentCache(String cachename,String extraSharedClassesOptions,String waitForMessage) {443// this hides the magic rule that due to the command construction, the "name=" is always the last part of the444// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append445// them to the cache name.446runInfiniteLoopJavaProgramWithNonPersistentCache(cachename+447(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""), waitForMessage);448}449450protected static void checkOutputForDump(boolean dumpGenerated) {451if (dumpGenerated) {452checkOutputContains("JVMDUMP....", "The JVM is dumping!!");453} else {454checkOutputDoesNotContain("JVMDUMP....", "The JVM is dumping!!");455}456}457458public static void runSimpleJavaProgramWithPersistentCacheAndReset(String cachename) {459RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename+",reset"));460}461462public static void runSimpleJavaProgramWithNonPersistentCacheMayFail(String cachename) {463RunCommand.executeMayFail(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename));464}465466public static void runSimpleJavaProgramWithNonPersistentCache(String cachename) {467RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename));468}469470public static void runSimpleJavaProgramWithNonPersistentCache(String cachename,boolean careAboutExitValue) {471RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename),careAboutExitValue);472}473474public static void runSimpleJavaProgramWithNonPersistentCacheAndReset(String cachename) {475RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename+",reset"));476}477/**478* @param cachename name of the cache to use479* @param agentName name of the JVMTI agent. Actually it needs to be one of the JVMTI test in com.ibm.jvmti.tests package.480* See TestSharedCacheEnableBCI.java for an example.481* @param agentArgs arguments to JVMTI agent. Again, these are the arguments passed to JVMTI test in com.ibm.jvmti.tests package.482* See TestSharedCacheEnableBCI.java for an example.483*/484public static void runSimpleJavaProgramWithAgentWithPersistentCache(String cachename, String agentName, String agentArgs) {485RunCommand.execute(getCommand(RunSimpleJavaProgramWithAgentWithPersistentCache, cachename, agentName, agentArgs));486checkOutputForDump(false);487}488/**489* Will execute a simple java program with a JVMTI agent using the named cache, extra options like "verbose,silent" can be specified490* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.491* @param cachename name of the cache to use492* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"493*/494public static void runSimpleJavaProgramWithAgentWithPersistentCache(String cachename, String extraSharedClassesOptions, String agentName, String agentArgs) {495// this hides the magic rule that due to the command construction, the "name=" is always the last part of the496// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append497// them to the cache name.498runSimpleJavaProgramWithAgentWithPersistentCache(cachename+499(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),500agentName, agentArgs);501}502/**503* @param cachename name of the cache to use504* @param agentName name of the JVMTI agent. Actually it needs to be one of the JVMTI test in com.ibm.jvmti.tests package.505* See TestSharedCacheEnableBCI.java for an example.506* @param agentArgs arguments to JVMTI agent. Again, these are the arguments passed to JVMTI test in com.ibm.jvmti.tests package.507* See TestSharedCacheEnableBCI.java for an example.508*/509public static void runSimpleJavaProgramWithAgentWithNonPersistentCache(String cachename, String agentName, String agentArgs) {510RunCommand.execute(getCommand(RunSimpleJavaProgramWithAgentWithNonPersistentCache, cachename, agentName, agentArgs));511checkOutputForDump(false);512}513/**514* Will execute a simple java program with a JVMTI agent using the named cache, extra options like "verbose,silent" can be specified515* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.516* @param cachename name of the cache to use517* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"518*/519public static void runSimpleJavaProgramWithAgentWithNonPersistentCache(String cachename, String extraSharedClassesOptions, String agentName, String agentArgs) {520// this hides the magic rule that due to the command construction, the "name=" is always the last part of the521// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append522// them to the cache name.523runSimpleJavaProgramWithAgentWithNonPersistentCache(cachename+524(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),525agentName, agentArgs);526}527528/**529* Will execute a hanoi program using the named cache, extraSharedClassesOptions like "verbose,silent" can be specified530* and they will be appended to the constructed -Xshareclasses option string. extraJavaOpt like "-Xint" can also be531* specified that is used to launch the program.532*533* @param cachename name of the cache to use534* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"535*/536public static void runHanoiProgramWithCache(String cachename,String extraSharedClassesOptions, String extraJavaOpt) {537// this hides the magic rule that due to the command construction, the "name=" is always the last part of the538// -Xshareclasses string in the defined commands. So to add more shared classes options we just have to append539// them to the cache name.540RunCommand.execute(getCommand(RunHanoiProgramWithCache,541cachename+(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),542(extraJavaOpt!=null&&extraJavaOpt.length()>0?" "+extraJavaOpt:"")543));544checkOutputForDump(false);545}546547protected static String getCacheFileLocationForNonPersistentCache(String cachename) {548String cacheDir = getCacheDir(cachename,false);549String expectedFileLocation =550cacheDir+File.separator+551getCacheFileName(cachename,false);552return expectedFileLocation;553}554protected static String getCacheFileDirectory(boolean forPersistentCache) {555String defaultLoc = getConfigParameter("defaultCacheLocation");556String cacheDirLoc = getConfigParameter("cacheDir");557String controlDirLoc=getConfigParameter("controlDir");558String theDir = null;559if (cacheDirLoc!=null) theDir = cacheDirLoc+(forPersistentCache?"":File.separator+"javasharedresources");560else if (controlDirLoc!=null) theDir = controlDirLoc+(forPersistentCache?"":File.separator+"javasharedresources");561else theDir = defaultLoc+File.separator+"javasharedresources";562return theDir;563}564565protected static String getCacheFileLocationForPersistentCache(String cachename) {566String cacheDir = getCacheDir(cachename,true);567String expectedFileLocation =568cacheDir+File.separator+569getCacheFileName(cachename,true);570return expectedFileLocation;571}572573protected static String getCacheFileLocationForCacheSnapshot(String cachename) {574String cacheDir = getCacheDir(cachename, false);575String expectedFileLocation =576cacheDir + File.separator +577getSnapshotFileName(cachename);578return expectedFileLocation;579}580581public static void checkFileExists(String location) {582if (!new File(location).exists()) {583fail("No file found at '"+location+"'");584}585}586587public static void checkFileDoesNotExist(String location) {588if (new File(location).exists()) {589fail("Did not expect to find file at '"+location+"'");590}591}592593public static void fail(String msg) {594showOutput();595System.err.println(msg);596System.err.println("\tLast command: "+RunCommand.lastCommand);597throw new TestFailedException(msg);598}599600private static String lastcmd_getCacheDir = "";601private static String lastresult_getCacheDir = "";602public static String getCacheDir(String cachename,boolean persistent)603{604//NOTE: use above statics to save some time when running tests ...605606String cmd = "";607if ( false == isDefaultDirTmp() && cachename.indexOf("groupaccess") != -1 ) {608if (persistent==true)609{610cmd = getCommand("getCacheFileNameGroupAccess",cachename);611}612else613{614cmd = getCommand("getCacheFileNameNonPersistGroupAccess",cachename);615}616} else {617if (persistent==true)618{619cmd = getCommand("getCacheFileName",cachename);620}621else622{623cmd = getCommand("getCacheFileNameNonPersist",cachename);624}625}626627if (lastcmd_getCacheDir.equals(cmd) && lastresult_getCacheDir.equals("")!=false)628{629return lastresult_getCacheDir;630}631lastcmd_getCacheDir=cmd;632633RunCommand.execute(cmd,false);634String stderr = RunCommand.lastCommandStderr;635636String[] stderrarray = stderr.split("\n");637638for (int j=0; j<stderrarray.length;j+=1)639{640String test = stderrarray[j];641if (test.indexOf("/")==0 || test.indexOf(":\\")==1)642{643644int i = test.lastIndexOf(java.io.File.separator);645if (i<1)646{647fail("Error: for cachename "+cachename+" not sure what happened but i is "+i);648return "";649}650String cacheDir = test.substring(0,i);//read just the dir651lastresult_getCacheDir = cacheDir;652return cacheDir;653}654}655fail("Error: should never hit this code.");656return "";657}658659private static String lastcmd_getCacheFileName = "";660private static String lastresult_getCacheFileName = "";661public static String getCacheFileName(String cachename,boolean persistent) {662663//NOTE: use above statics to save some time when running tests ...664665String cmd = "";666667if (persistent==true)668{669cmd = getCommand("getCacheFileName",cachename);670}671else672{673cmd = getCommand("getCacheFileNameNonPersist",cachename);674}675676if (lastcmd_getCacheFileName.equals(cmd) && lastresult_getCacheFileName.equals("")!=false)677{678return lastresult_getCacheFileName;679}680lastcmd_getCacheFileName=cmd;681682RunCommand.execute(cmd,false);683String stderr = RunCommand.lastCommandStderr;684685String[] stderrarray = stderr.split("\n");686687for (int j=0; j<stderrarray.length;j+=1)688{689String test = stderrarray[j];690if (test.indexOf("/")==0 || test.indexOf(":\\")==1)691{692int i = test.lastIndexOf(java.io.File.separator);693if (i>=test.length())694{695fail("Error: for cachename "+cachename+" not sure what happened but i is "+i);696return "";697}698String cachefile =test.substring(i+1,test.length());699//System.out.println("HERE(getCacheFileName):"+test+" "+cachefile);700lastresult_getCacheFileName = cachefile;701return cachefile;702}703}704fail("Error: should never hit this code.");705return "";706707708}709710public static String getSnapshotFileName(String snapshotname) {711712//NOTE: use above statics to save some time when running tests ...713714String cmd = getCommand("getSnapshotFileName", snapshotname);715716if (lastcmd_getCacheFileName.equals(cmd) && lastresult_getCacheFileName.equals("") != false) {717return lastresult_getCacheFileName;718}719lastcmd_getCacheFileName = cmd;720721RunCommand.execute(cmd, false);722String stderr = RunCommand.lastCommandStderr;723724String[] stderrarray = stderr.split("\n");725726for (int j = 0; j < stderrarray.length; j += 1) {727String test = stderrarray[j];728if (test.indexOf("/") == 0 || test.indexOf(":\\") == 1) {729int i = test.lastIndexOf(java.io.File.separator);730if (i >= test.length()) {731fail("Error: for snapshotname " + snapshotname + " not sure what happened but i is " + i);732return "";733}734String snapshotfile = test.substring(i + 1, test.length());735lastresult_getCacheFileName = snapshotfile;736return snapshotfile;737}738}739fail("Error: should never hit this code.");740return "";741}742743protected static String getConfigParameter(String string) {744return (String)config.get(string);745}746747protected static void setConfigParameter(String key,String value) {748if (value==null) config.remove(key);749else config.put(key,value);750}751752public static boolean destroyCache(String cachename) {753RunCommand.execute(getCommand(DestroyCacheCommand,cachename),false);754if (messageOccurred("JVMSHRC023E")) return false;755else return true;756}757758public static boolean destroyPersistentCache(String cachename) {759RunCommand.execute(getCommand(DestroyPersistentCacheCommand,cachename),false);760if (messageOccurred("JVMSHRC023E")) return false;761else return true;762}763764public static boolean destroyNonPersistentCache(String cachename) {765RunCommand.execute(getCommand(DestroyNonPersistentCacheCommand,cachename),false);766if (messageOccurred("JVMSHRC023E")) return false;767else return true;768}769770public static boolean messageOccurred(String msgId) {771if (RunCommand.lastCommandStderr.indexOf(msgId)!=-1) return true;772if (RunCommand.lastCommandStdout.indexOf(msgId)!=-1) return true;773return false;774}775776public static void showOutput() {777System.out.println("Command executed: '"+RunCommand.lastCommand+"'");778System.out.println("vvv STDOUT vvv");779System.out.println(RunCommand.lastCommandStdout);780System.out.println("^^^ STDOUT ^^^");781System.out.println("vvv STDERR vvv");782System.out.println(RunCommand.lastCommandStderr);783System.out.println("^^^ STDERR ^^^");784System.out.println("vvv STACK TRACE vvv");785new Throwable().printStackTrace(System.out);786System.out.println("^^^ STACK TRACE ^^^");787788if (RunCommand.the2ndLastCommand != null) {789System.out.println("2nd last command executed: '"+RunCommand.the2ndLastCommand+"'");790System.out.println("vvv 2ND LAST STDOUT vvv");791System.out.println(RunCommand.the2ndLastCommandStdout);792System.out.println("^^^ 2ND LAST STDOUT ^^^");793System.out.println("vvv 2ND LAST STDERR vvv");794System.out.println(RunCommand.the2ndLastCommandStderr);795System.out.println("^^^ 2ND LAST STDERR ^^^");796}797}798799public static void checkOutputContains(String regex,String explanation) {800String[] lines = RunCommand.lastCommandStderrLines;801boolean found = false;802if (lines!=null) {803for (int i = 0; i < lines.length; i++) {804if (lines[i].matches("^.*"+regex+".*$")) {805// System.out.println("this line '"+lines[i]+"' matches "+regex);806found=true;807break;808}809}810}811if (!found) {812// check stdout813lines = RunCommand.lastCommandStdoutLines;814found = false;815if (lines!=null) {816for (int i = 0; i < lines.length; i++) {817if (lines[i].matches("^.*"+regex+".*$")) {818// System.out.println("this line '"+lines[i]+"' matches "+regex);819found=true;820}821}822}823}824if (!found) {825fail(explanation);826}827}828public static void checkOutputDoesNotContain(String regex,String explanation) {829String[] lines = RunCommand.lastCommandStderrLines;830boolean isFound = false;831if (lines!=null) {832for (int i = 0; i < lines.length; i++) {833if (lines[i].matches("^.*"+regex+".*$")) {834// System.out.println("this line '"+lines[i]+"' matches "+regex);835isFound=true;836}837}838}839if (isFound) {840fail(explanation);841}842}843844public static void checkForMessage(String msgid, String explanation) {845if (!messageOccurred(msgid)) {846fail(explanation);847}848}849public static void checkNoFileForPersistentCache(String cachename) {850checkFileDoesNotExist(getCacheFileLocationForPersistentCache(cachename));851}852//TODO isnt this the same as that other method below?853public static void checkNoFileForNonPersistentCache(String cachename) {854if (isWindows()) {855checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));856} else { checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));857checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));858}859}860861public static void checkFileDoesNotExistForPersistentCache(String cachename) {862checkFileDoesNotExist(getCacheFileLocationForPersistentCache(cachename));863}864865public static void checkFileDoesNotExistForCacheSnapshot(String cachename) {866checkFileDoesNotExist(getCacheFileLocationForCacheSnapshot(cachename));867}868869public static void checkFileDoesNotExistForNonPersistentCache(String cachename) {870if (isWindows()) {871checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));872} else {873checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));874checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));875}876}877878public static void checkFileExistsForPersistentCache(String cachename) {879checkFileExists(getCacheFileLocationForPersistentCache(cachename));880}881882public static void checkFileExistsForNonPersistentCache(String cachename) {883Properties p = System.getProperties();884if (isWindows()) {885checkFileExists(getCacheFileLocationForNonPersistentCache(cachename));886} else {887// linux is harder, there is a memory file and a semaphore file to worry about888checkFileExists(getCacheFileLocationForNonPersistentCache(cachename));889checkFileExists(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));890}891}892893public static void checkFileExistsForCacheSnapshot(String cachename) {894checkFileExists(getCacheFileLocationForCacheSnapshot(cachename));895}896897898public static boolean isWindows() {899return System.getProperty("os.name").toLowerCase().startsWith("windows");900}901902public static boolean isMVS() {903return System.getProperty("os.name").toLowerCase().startsWith("z/os");904}905906public static boolean isLinux() {907return System.getProperty("os.name").toLowerCase().startsWith("linux");908}909910public static String getOS() {911return System.getProperty("os.name");912}913914public static boolean isCompressedRefEnabled() {915checkJavaVersion();916if (messageOccurred("Compressed References")) {917return true;918} else {919return false;920}921}922923public static void checkForSuccessfulPersistentCacheOpenMessage(924String cachename) {925checkOutputContains("JVMSHRC237I.*" + cachename,926"Did not get expected message about successful cache open");927}928929public static void checkForSuccessfulPersistentCacheCreationMessage(930String cachename) {931checkOutputContains("JVMSHRC236I.*" + cachename,932"Did not get expected message about successful cache creation");933}934935public static void checkForSuccessfulPersistentCacheDestroyMessage(936String cachename) {937checkOutputContains(cachename + ".*has been destroyed",938"Did not get expected message about successful cache destroy");939}940941public static void checkForSuccessfulNonPersistentCacheOpenMessage(942String cachename) {943checkOutputContains("JVMSHRC159I.*" + cachename,944"Did not get expected message about successful cache open");945}946947public static void checkForSuccessfulNonPersistentCacheCreationMessage(948String cachename) {949checkOutputContains("JVMSHRC158I.*" + cachename,950"Did not get expected message about successful cache creation");951}952953public static void checkForSuccessfulNonPersistentCacheDestoryMessage(954String cachename) {955checkOutputContains(cachename + ".*is destroyed",956"Did not get expected message about successful cache destroy");957}958959public static void checkOutputForCompatiblePersistentCache(String cachename,boolean shouldBeFound) {960checkOutputForCompatibleCache(cachename, true, shouldBeFound);961}962963public static void checkOutputForCompatibleNonPersistentCache(String cachename,boolean shouldBeFound) {964checkOutputForCompatibleCache(cachename, false, shouldBeFound);965}966967/**968* In the most recent command output (RunCommand.lastCommandStderrLines) this method checks for969* the named cache in the 'Incompatible caches' section. The flag shouldBeFound indicates whether970* it should be named in the section.971*/972public static void checkOutputForIncompatibleCache(String name,boolean shouldBeFound) {973String[] lines = RunCommand.lastCommandStderrLines;974boolean isFound = false;975if (lines!=null) {976int i=0;977boolean inCompatSection = false;978while (i<lines.length) {979if (inCompatSection) {980// Ok, this might be our entry981if (lines[i].matches(name+"[ \\t].*$")) {982isFound=true;983}984}985if (lines[i].startsWith("Incompatible")) inCompatSection=true;986if (lines[i].trim().equals("")) inCompatSection=false;987i++;988}989}990if (shouldBeFound) {991if (!isFound) {992fail("Cache '"+name+"' was not found to be incompatible");993}994} else {995if (isFound) {996fail("Cache '"+name+"' was unexpectedly found to be incompatible");997}998}999}1000100110021003public static void checkOutputForCompatibleCache(String name, boolean isPersistent,boolean shouldBeFound) {1004String[] lines = RunCommand.lastCommandStderrLines;1005boolean isFound = false;1006if (lines!=null) {1007int i=0;1008boolean inCompatSection = false;1009while (i<lines.length) {1010if (inCompatSection) {1011// Ok, this might be our entry1012if (lines[i].matches(name+".*"+(isPersistent?"(yes|persistent)":"(no|non-persistent)")+".*$")) {1013isFound=true;1014}1015}1016if (lines[i].startsWith("Compatible")) inCompatSection=true;1017if (lines[i].trim().equals("")) inCompatSection=false;1018i++;1019}1020}1021if (shouldBeFound) {1022if (!isFound) {1023fail((isPersistent?"":"Non-")+"Persistent cache '"+name+"' was not found to be compatible");1024}1025} else {1026if (isFound) {1027fail((isPersistent?"":"Non-")+"Persistent cache '"+name+"' was unexpectedly found to be compatible");1028}1029}1030}10311032public static List processOutputForCompatibleCacheList() {1033List compatibleCaches = new ArrayList();1034String[] lines = RunCommand.lastCommandStderrLines;1035if (lines!=null) {1036int i=0;1037boolean inCompatSection = false;1038while (i<lines.length) {1039if (inCompatSection) {1040// Chop from position 0 to the first non-space or tab1041// System.out.println(">>>"+lines[i]+"<<<");1042if (lines[i].length()!=0) { // this will avoid including the final line of compatible section1043int p=0; while (p<lines[i].length() && lines[i].charAt(p)!=' ' && lines[i].charAt(p)!='\t') p++;1044compatibleCaches.add(lines[i].substring(0,p));1045}1046}1047if (lines[i].startsWith("Compatible")) inCompatSection=true;1048if (lines[i].trim().equals("")) {1049inCompatSection=false;1050}1051i++;1052}1053}1054return compatibleCaches;1055}10561057public static void deleteTemporaryDirectory(String path) {1058File f = new File(path);1059if (f.exists()) {1060File[] files = f.listFiles();1061for (int i = 0; i < files.length; i++) {1062if (files[i].isDirectory()) {1063deleteTemporaryDirectory((files[i]).getAbsolutePath());1064} else {1065files[i].delete();1066if (files[i].exists()) {1067fail("Couldn't delete temp file " + files[i].getAbsolutePath());1068}1069}1070}1071f.delete();1072}1073if (f.exists()) {1074fail("Couldn't delete temp dir " + f.getAbsolutePath());1075}1076//System.out.println("Deleted Tmp Folder: " + f.getAbsolutePath());1077}10781079public static String createTemporaryDirectory(String testname) {1080try {1081File f = File.createTempFile("testSC"+testname,"dir");10821083//System.out.println("Created Tmp Folder: "+f.getAbsolutePath());10841085if (!f.delete()) fail("Couldn't create the temp dir");1086if (!f.mkdir()) fail("Couldnt create the temp dir");1087return f.getAbsolutePath();1088} catch (IOException e) {1089fail("Couldnt create temp dir: "+e);1090return null;1091}1092}10931094/**1095* Create some caches that are generation 07 and 011096*/1097protected static void createGenerations01() {1098log("Creating cache generations...");1099createPersistentCache("Foo"); createPersistentCache("Bar");1100createNonPersistentCache("Foo");createNonPersistentCache("Bar");1101renameGenerations("G07","G01"); // rename generation 03 files to generation 021102createPersistentCache("Foo"); createPersistentCache("Bar");1103createNonPersistentCache("Foo");createNonPersistentCache("Bar");1104}1105public static void log(String s) {1106if (debug) System.out.println(s);1107}11081109/**1110* Create some caches that are generation 03 and 021111*/1112protected static void createGenerations02() {1113createPersistentCache("Foo"); createPersistentCache("Bar");1114createNonPersistentCache("Foo");createNonPersistentCache("Bar");1115renameGenerations("G07","G02"); // rename generation 03 files to generation 0111161117createPersistentCache("Foo"); createPersistentCache("Bar");1118createNonPersistentCache("Foo");createNonPersistentCache("Bar");11191120}11211122public static void renameGenerations(String from, String to) {1123renameGeneration("Foo",true,from,to);1124renameGeneration("Bar",true,from,to);1125renameGeneration("Foo",false,from,to);1126renameGeneration("Bar",false,from,to);1127}11281129/**1130* Passed a generation number like 'G07', it will change that to 'to' (eg. G02).1131*/1132public static void renameGeneration(String name, boolean isPersistent,1133String from, String to) {1134log("Changing generation numbers for "+(isPersistent?"":"non-")+"persistent cache '"+name+"' from "+from+" to "+to);1135if (isWindows() || isPersistent) {1136String cachefilename = getCacheFileName(name, isPersistent); // TODO null will need fixing for linux and non-persistent caches11371138String expectedFileLocation = null;1139if (isPersistent) {1140expectedFileLocation = getCacheFileLocationForPersistentCache(name);1141} else {1142expectedFileLocation = getCacheFileLocationForNonPersistentCache(name);1143}11441145// String expectedFileLocation =1146// getConfigParameter("defaultCacheLocation")+File.separator+1147// "javasharedresources"+File.separator+cachefilename;11481149File currentCache = new File(expectedFileLocation);1150if (!currentCache.exists()) {1151fail("Unexpectedly couldn't find cache file: "+expectedFileLocation);1152}11531154if (expectedFileLocation.endsWith(from)) {1155String newLocation = expectedFileLocation.substring(0,expectedFileLocation.length()-from.length())+to;1156if (!currentCache.renameTo(new File(newLocation))) {1157fail("Could not rename from '"+expectedFileLocation+"' to '"+newLocation+"'");1158}1159}1160} else {1161// non-persistent caches on non-windows have two control files1162String locMemory = getCacheFileLocationForNonPersistentCache(name);1163File f = new File(locMemory);1164if (!f.exists()) fail("Unexpectedly couldn't find cache file: "+locMemory);1165if (locMemory.endsWith(from)) {1166String newLocation = locMemory.substring(0,locMemory.length()-from.length())+to;1167if (!f.renameTo(new File(newLocation))) {1168fail("Could not rename from '"+locMemory+"' to '"+newLocation+"'");1169}1170}1171String locSemaphore = getCacheFileLocationForNonPersistentCache(name).replace("memory","semaphore");1172f = new File(locSemaphore);1173if (!f.exists()) fail("Unexpectedly couldn't find cache file: "+locSemaphore);1174if (locSemaphore.endsWith(from)) {1175String newLocation = null;1176if (to.equals("G01") || to.equals("G02")) {1177// semaphore doesnt have generation number on for gen1/21178newLocation = locSemaphore.substring(0,locSemaphore.length()-from.length()-1);1179} else {1180newLocation = locSemaphore.substring(0,locSemaphore.length()-from.length())+to;1181}1182if (!f.renameTo(new File(newLocation))) {1183fail("Could not rename from '"+locSemaphore+"' to '"+newLocation+"'");1184}1185}1186}1187}1188//1189// public void touchFiles(String listForTouching) {1190//1191// if (listForTouching.length()==0) return;1192// StringTokenizer st = new StringTokenizer(listForTouching,",");1193// try { Thread.sleep(1000); } catch (Exception e) {} // allow for filesystem with crap resolution timer1194// while (st.hasMoreTokens()) {1195// String touch = st.nextToken();1196// File f = new File(touch);1197// f.r1198// if (!f.exists()) throw new RuntimeException("Can't find: "+touch);1199// boolean b = f.setLastModified(System.currentTimeMillis());1200// log("Touched: "+f+" : "+(b?"successful":"unsuccessful"));1201// }1202// }12031204public static void corruptCache(String cachename, boolean isPersistent, String howToCorruptIt) {1205String theFile = (isPersistent?getCacheFileLocationForPersistentCache(cachename):1206getCacheFileLocationForNonPersistentCache(cachename));12071208//if (!isPersistent && !isWindows()) {1209// System.out.println("corruptCache is not implemented on this target");1210// return;1211//}12121213if (howToCorruptIt.equals("truncate")) {12141215File f = new File(theFile);1216File fNew = new File(theFile+".tmp");1217// chop it to 1000 bytes1218int i =0;1219byte[] buff = new byte[1000];1220try {1221FileInputStream fis = new FileInputStream(f);1222FileOutputStream fos = new FileOutputStream(fNew);1223while (i<10000) {1224int read = fis.read(buff);1225if (read>0)1226{1227i+=read;1228fos.write(buff,0,read);1229}1230else1231{1232fail("Could not create the fake corrupt file.");1233break;1234}1235}1236fos.flush();1237fos.close();1238fis.close();1239if (!f.delete()) fail("Failed to delete existing cache");1240if (!fNew.renameTo(f)) fail("Could not rename new truncated cache");1241} catch (Exception e) {1242fail("Cannot truncate file "+e);1243}1244} else if (howToCorruptIt.equals("ftpascii")) {1245File f = new File(theFile);1246File fNew = new File(theFile+".tmp");1247// chop it to 10000 bytes1248int i =0;1249byte[] buff = new byte[1000];1250try {1251FileInputStream fis = new FileInputStream(f);1252FileOutputStream fos = new FileOutputStream(fNew);1253int read=1;1254while (true && read>0) {1255read = fis.read(buff);1256i+=read;1257byte b = 0x7f;1258if (read>-1) {1259for (int j=0;j<read;j++) {1260buff[j]=(byte)(buff[j]&b);1261}1262fos.write(buff,0,read);1263}1264}1265fos.flush();fos.close();1266fis.close();1267// System.out.println("Copied "+i+" bytes");1268if (!f.delete()) fail("Failed to delete existing cache");1269if (!fNew.renameTo(f)) fail("Could not rename new ftpascii cache");1270} catch (Exception e) {1271e.printStackTrace();1272fail("Cannot ftpascii file "+e);1273}1274} else if (howToCorruptIt.equals("zero")) {1275File f = new File(theFile);1276File fNew = new File(theFile+".tmp");1277byte[] buff = new byte[1000];1278try {1279FileInputStream fis = new FileInputStream(f);1280FileOutputStream fos = new FileOutputStream(fNew);1281int read=1;1282int blocksToZero = 200;1283int offsetForZero=5000;1284boolean corrupted=false;12851286if (realtimeTestsSelected()){1287offsetForZero=100000;1288}12891290while (read > 0) {1291read = fis.read(buff);1292offsetForZero-=read;1293if (read > -1) {1294if (offsetForZero<=0 && !corrupted) {1295if ((blocksToZero--)<0) {1296corrupted=true;1297}1298for (int j=0;j<read;j++) {1299buff[j]=0;1300}1301}1302fos.write(buff,0,read);1303}1304}1305fos.flush();fos.close();1306fis.close();1307if (!f.delete()) fail("Failed to delete existing cache");1308if (!fNew.renameTo(f)) fail("Could not rename new zerod cache");1309} catch (Exception e) {1310e.printStackTrace();1311fail("Cannot zero file "+e);1312}1313} else if (howToCorruptIt.equals("zeroStringCache")) {1314File f = new File(theFile);1315File fNew = new File(theFile+".tmp");1316byte[] buff = new byte[1000];1317try {1318FileInputStream fis = new FileInputStream(f);1319FileOutputStream fos = new FileOutputStream(fNew);1320int read=1;1321int blocksToZero = 3;1322int offsetForZero=2000;1323boolean corrupted=false;13241325while (read > 0) {1326read = fis.read(buff);1327offsetForZero-=read;1328if (read > -1) {1329if (offsetForZero<=0 && !corrupted) {1330if ((blocksToZero--)<0) {1331corrupted=true;1332}1333for (int j=0;j<read;j++) {1334buff[j]=0;1335}1336}1337fos.write(buff,0,read);1338}1339}1340fos.flush();fos.close();1341fis.close();1342if (!f.delete()) fail("Failed to delete existing cache");1343if (!fNew.renameTo(f)) fail("Could not rename new zeroStringCache cache");1344} catch (Exception e) {1345e.printStackTrace();1346fail("Cannot zeroStringCache file "+e);1347}1348} else if (howToCorruptIt.equals("zeroFirstPage")) {1349File f = new File(theFile);1350File fNew = new File(theFile+".tmp");1351byte[] buff = new byte[1024];1352try {1353FileInputStream fis = new FileInputStream(f);1354FileOutputStream fos = new FileOutputStream(fNew);1355int read=1;1356boolean corrupted=false;13571358while (read > 0) {1359read = fis.read(buff);1360if (read > -1) {1361if (!corrupted) {1362for (int j=0;j<read;j++) {1363buff[j]=0;1364}1365corrupted = true;1366}1367fos.write(buff,0,read);1368}1369}1370fos.flush();fos.close();1371fis.close();1372if (!f.delete()) fail("Failed to delete existing cache");1373if (!fNew.renameTo(f)) fail("Could not rename new zerod cache");1374} catch (Exception e) {1375e.printStackTrace();1376fail("Cannot zero file "+e);1377}1378}1379}13801381protected static boolean copyFile(File from,File to) {1382int i =0;1383byte[] buff = new byte[1000];1384try {1385FileInputStream fis = new FileInputStream(from);1386FileOutputStream fos = new FileOutputStream(to);1387int read=1;1388while (true && read>0) {1389read = fis.read(buff);1390i+=read;1391if (read>-1) fos.write(buff,0,read);1392}1393fos.flush();fos.close();1394fis.close();1395// System.out.println("Copied "+i+" bytes from "+from+" to "+to);1396} catch (Exception e) {1397fail("Cannot copy file '"+from+"' "+e);1398}1399return true;1400}1401public static void moveControlFilesForNonPersistentCache(String name,1402String whereFrom, String whereTo) {1403if (isWindows()) {1404File f = new File(whereFrom+File.separator+getCacheFileName(name,false));1405File fNew = new File(whereTo+File.separator+getCacheFileName(name, false));1406if (!f.renameTo(fNew)) fail("Could not rename the control file");1407} else {1408File f = new File(whereFrom+File.separator+getCacheFileName(name,false));1409File fNew = new File(whereTo+File.separator+getCacheFileName(name, false));1410if (!f.renameTo(fNew)) fail("Could not rename the memory file from "+f.getAbsolutePath()+" to "+fNew.getAbsolutePath());14111412f = new File(whereFrom+File.separator+getCacheFileName(name,false).replace("memory", "semaphore"));1413fNew = new File(whereTo+File.separator+getCacheFileName(name, false).replace("memory", "semaphore"));1414if (!f.renameTo(fNew)) fail("Could not rename the semaphore file from "+f.getAbsolutePath()+" to "+fNew.getAbsolutePath());1415}1416}1417public static Set getSharedMemorySegments() {1418Set shmSegments = new HashSet();1419RunCommand.execute("ipcs");1420String[] lines = RunCommand.lastCommandStdoutLines;1421if (lines!=null) {1422int i=0;1423boolean inSharedMemorySegmentSection = false;1424while (i<lines.length) {1425if (inSharedMemorySegmentSection) {1426if (lines[i].startsWith("0x")) {1427String shm = lines[i].substring(11,21).trim();1428// System.out.println("From line '"+lines[i]+"' we have "+shm);1429shmSegments.add(shm);1430}1431}1432if (lines[i].indexOf("Shared Memory Segments")!=-1) inSharedMemorySegmentSection=true;1433if (lines[i].trim().equals("")) inSharedMemorySegmentSection=false;1434i++;1435}1436}1437return shmSegments;1438}1439public static Set getSharedSemaphores() {1440Set shmSegments = new HashSet();1441RunCommand.execute("ipcs");1442String[] lines = RunCommand.lastCommandStdoutLines;1443if (lines!=null) {1444int i=0;1445boolean inSharedSemaphoresSection = false;1446while (i<lines.length) {1447if (inSharedSemaphoresSection) {1448if (lines[i].startsWith("0x")) {1449String sem = lines[i].substring(11,21).trim();1450// System.out.println("From line '"+lines[i]+"' we have "+sem);1451shmSegments.add(sem);1452}1453}1454if (lines[i].indexOf("Semaphore Arrays")!=-1) inSharedSemaphoresSection=true;1455if (lines[i].trim().equals("")) inSharedSemaphoresSection=false;1456i++;1457}1458}1459return shmSegments;1460}14611462public static boolean removeSemaphoreForCache(String cacheName) {1463StringBuffer removeSemCmd = new StringBuffer("ipcrm -s ");1464String semid = null;1465RunCommand.execute(getCommand(ListAllCaches), false);1466String[] lines = RunCommand.lastCommandStderrLines;1467for (int i = 0; i < lines.length; i++) {1468if (lines[i].startsWith(cacheName)) {1469String token[] = lines[i].split("(\\s)+");1470/* verify cache name */1471if (token[0].trim().equals(cacheName) == false) {1472continue;1473}1474/* verify non-persistent cache */1475if ((token[3].trim().equals("no") == false) && (token[3].trim().equals("non-persistent") == false)) {1476continue;1477}1478/* get semaphore */1479semid = token[7].trim();1480}1481}14821483if (semid != null) {1484removeSemCmd.append(semid);1485RunCommand.execute(removeSemCmd.toString());1486return true;1487} else {1488return false;1489}1490}14911492public static boolean removeSharedMemoryForCache(String cacheName) {1493StringBuffer removeShmCmd = new StringBuffer("ipcrm -m ");1494String shmid = null;1495RunCommand.execute(getCommand(ListAllCaches), false);1496String[] lines = RunCommand.lastCommandStderrLines;1497for (int i = 0; i < lines.length; i++) {1498if (lines[i].startsWith(cacheName)) {1499String token[] = lines[i].split("(\\s)+");1500/* verify cache name */1501if (token[0].trim().equals(cacheName) == false) {1502continue;1503}1504/* verify non-persistent cache */1505if ((token[3].trim().equals("no") == false) && (token[3].trim().equals("non-persistent") == false)) {1506continue;1507}1508/* get shared memory */1509shmid = token[6].trim();1510}15111512}1513if (shmid != null) {1514removeShmCmd.append(shmid);1515RunCommand.execute(removeShmCmd.toString());1516return true;1517} else {1518return false;1519}1520}15211522public static String[] getLastCommandStdout() {1523return RunCommand.lastCommandStdoutLines;1524}15251526public static String[] getLastCommandStderr() {1527return RunCommand.lastCommandStderrLines;1528}15291530public static boolean isDefaultDirTmp() {1531// ibm 11+ has the same -DOPENJ9_BUILD as openj91532return System.getProperty("java.vm.vendor").toLowerCase().contains("ibm") && System.getProperty("java.specification.version").contains("1.8") || isMVS();1533}15341535public static String removeJavaSharedResourcesDir(String dir) {1536if (dir != null && dir.length() > 0) {1537String tempDir = dir;1538if (tempDir.endsWith(java.io.File.separator)) {1539tempDir = tempDir.substring(0, dir.length() - 1);1540}1541if (tempDir.endsWith(java.io.File.separator + "javasharedresources")) {1542int index = tempDir.lastIndexOf(java.io.File.separator);1543return tempDir.substring(0, index);1544}1545return dir;1546}1547fail("Error: should never hit this code, directory " + dir + " is not correct.");1548return "";1549}1550}155115521553