public static <T> T findThrowableCauseByClass(Throwable t, Class<T> clazz) { if (clazz == null) { throw new IllegalArgumentException("'clazz' parameter cannot be null."); } if (t == null) { return null; } else if (clazz.isAssignableFrom(t.getClass())) { return (T) t; } else { return findThrowableCauseByClass(t.getCause(), clazz); } }
public static void setField(Class<?> clazz, String fieldName, Object instance, Object value) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); if (Modifier.isFinal(field.getModifiers())) { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); } field.set(instance, value); } catch (Exception e) { if (e instanceof NoSuchFieldException && clazz.getSuperclass() != null) { setField(clazz.getSuperclass(), fieldName, instance, value); } else { log.error("Failed to set " + clazz.getName() + "." + fieldName + " to value", e); } } }
public static File createOrReplaceFile(File parentDir, String actualFileName) throws IOException { File outputFile = new File(parentDir, actualFileName); backupFile(outputFile); if (outputFile.createNewFile()) { log.info("Successfully created report file:" + outputFile.getAbsolutePath()); } else { log.warn("Failed to create the report file!"); } return outputFile; }
public static void loadConfigFile(String filename, Map<String, byte[]> configs) { if (filename != null) { InputStream is = null; try { is = Utils.class.getClassLoader().getResourceAsStream(filename); if (is == null) { //not attached as resource - assume the direct path on filesystem is = new FileInputStream(new File(filename)); } configs.put(filename, Utils.readAsBytes(is)); } catch (Exception e) { log.error("Error while reading configuration file (" + filename + ")", e); } finally { Utils.close(is); } } }
private boolean checkMemoryReleased() { long percentage = -1; long currentFreeMemory = -1; long deadline = TimeService.currentTimeMillis() + memoryReleaseTimeout; for (; ; ) { System.gc(); Runtime runtime = Runtime.getRuntime(); currentFreeMemory = runtime.freeMemory() + runtime.maxMemory() - runtime.totalMemory(); percentage = (currentFreeMemory * 100) / initialFreeMemory; if (percentage > memoryThreshold || TimeService.currentTimeMillis() > deadline) break; log.infof("Available memory: %d kB (%d%% of initial available memory - %d kB)", currentFreeMemory / 1024, percentage, initialFreeMemory / 1024); Utils.sleep(1000); } if (percentage > memoryThreshold) { return true; } log.error("Using more memory than expected!"); return false; }
public static void deleteDirectory(File file) { if (file.isDirectory()) { for (File f : file.listFiles()) { deleteDirectory(f); } } if (file.exists()) { file.delete(); } }
/** * @param stageClass * @param properties Stage's attributes as written in configuration - evaluation takes place on slave. * @param labelName Label that should be used together with stage-defined prefix and suffix to uniquely * identify this stage in the scenario. Can be null. */ public void addStage(Class<? extends Stage> stageClass, Map<String, Definition> properties, String labelName) { org.radargun.config.Stage annotation = stageClass.getAnnotation(org.radargun.config.Stage.class); if (annotation == null) { throw new IllegalArgumentException("Class " + stageClass.getName() + " does not have annotation @Stage!"); } Label label = annotation.label(); String fullLabelName = Utils.concat(label.separator(), label.prefix(), labelName, label.suffix()); if (!fullLabelName.isEmpty()) { if (labels.put(fullLabelName, stages.size()) != null) { throw new IllegalArgumentException("Label '" + label + "' was already defined (hint: two loops without name?)"); } } stages.add(new StageDescription(stageClass, properties)); }
@Deprecated public static void createOutputFile(String fileName, String fileContent) throws IOException { createOutputFile(fileName, fileContent, true); }
public static String prettyPrintTime(long time, TimeUnit unit) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); if (unit.toNanos(time) < 1000) return nf.format(convert(time, unit, TimeUnit.NANOSECONDS)) + " ns"; if (unit.toMicros(time) < 1000) return nf.format(convert(time, unit, TimeUnit.MICROSECONDS)) + " us"; if (unit.toMillis(time) < 1000) return nf.format(convert(time, unit, TimeUnit.MILLISECONDS)) + " ms"; if (unit.toSeconds(time) < 300) return nf.format(convert(time, unit, TimeUnit.SECONDS)) + " seconds"; if (unit.toMinutes(time) < 120) return nf.format(convert(time, unit, TimeUnit.MINUTES)) + " minutes"; return nf.format(convert(time, unit, TimeUnit.HOURS)) + " hours"; }
public static List<String> readFile(String file) { List<String> lines = new ArrayList<String>(); BufferedReader br = null; InputStream resourceStream = Utils.class.getResourceAsStream(file); try { if (resourceStream != null) { br = new BufferedReader(new InputStreamReader(resourceStream)); } else { br = new BufferedReader(new FileReader(file)); } String line; while ((line = br.readLine()) != null) { lines.add(line); } } catch (IOException ex) { log.error("Error is thrown during file reading!", ex); throw new RuntimeException(ex); } finally { close(br, resourceStream); } return lines; }
@Deprecated public static void createOutputFile(String fileName, String fileContent, boolean doBackup) throws IOException { File parentDir = new File("reports"); if (!parentDir.exists() && !parentDir.mkdirs()) { log.error("Directory '" + parentDir.getAbsolutePath() + "' could not be created"); /* * The file will be created in the Sytem tmp directory */ parentDir = new File(System.getProperty("java.io.tmpdir")); } File reportFile = new File(parentDir, fileName); if (!reportFile.exists() || doBackup) { reportFile = Utils.createOrReplaceFile(parentDir, fileName); } if (!reportFile.exists()) { throw new IllegalStateException(reportFile.getAbsolutePath() + " was deleted? Not allowed to delete report file during test run!"); } else { log.info("Report file '" + reportFile.getAbsolutePath() + "' created"); } FileWriter writer = null; try { writer = new FileWriter(reportFile, !doBackup); writer.append(fileContent); } finally { if (writer != null) writer.close(); } }
public void smokeTest() throws Exception { CoreStageRunner stageRunner = new CoreStageRunner(1); Lifecycle lifecycle = stageRunner.getTraitImpl(Lifecycle.class); lifecycle.start(); MonitorStartStage monitorStartStage = new MonitorStartStage(); List<DistStageAck> acks = new ArrayList<>(1); acks.add(stageRunner.executeOnSlave(monitorStartStage, 0)); Assert.assertEquals(stageRunner.processAckOnMaster(monitorStartStage, acks), StageResult.SUCCESS); Utils.sleep(3000); MonitorStopStage monitorStopStage = new MonitorStopStage(); acks = new ArrayList<>(1); acks.add(stageRunner.executeOnSlave(monitorStopStage, 0)); Assert.assertEquals(stageRunner.processAckOnMaster(monitorStopStage, acks), StageResult.SUCCESS); } }
/** * Unzip the zip file located at zipPath to directory targetDirectory. * Note that the extraction removes executable bits from files, so you need to set them afterwards, * for example using the {@link Utils#setPermissions(String, String)} method. */ public static void unzip(String zipPath, String targetDirectory) throws IOException { Path targetPath = FileSystems.getDefault().getPath(targetDirectory); Utils.deleteDirectory(targetPath.toFile()); Files.createDirectories(targetPath); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipPath)); ZipEntry nextEntry; while ((nextEntry = zipInputStream.getNextEntry()) != null) { Path entryOutput = targetPath.resolve(nextEntry.getName()); if (nextEntry.isDirectory()) { Files.createDirectory(entryOutput); } else { Files.copy(zipInputStream, entryOutput); } zipInputStream.closeEntry(); } }
return -1; } else if (result == StageResult.BREAK) { nextLabel = Utils.concat(".", "repeat", repeatNames.peek(), "end"); } else if (result == StageResult.CONTINUE) { nextLabel = Utils.concat(".", "repeat", repeatNames.peek(), "begin"); } else throw new IllegalStateException(); int nextStageId = masterConfig.getScenario().getLabel(nextLabel);
@Test(expectedExceptions = IllegalArgumentException.class) public void testFindThrowableCauseByClassNullArg() { Utils.findThrowableCauseByClass(new TestChildException(), null); }
slaveIds1.add(2); partitions.add(slaveIds1); Utils.setField(SetPartitionsStage.class, "partitions", setPartitionsStage, partitions);
public void testFindThrowableCauseByClass() { Exception root = new TestRootException(); Exception child = new TestChildException(root); Exception result = Utils.findThrowableCauseByClass(child, TestRootException.class); assertTrue(result instanceof TestRootException); child = new TestChildException(); result = Utils.findThrowableCauseByClass(child, TestRootException.class); assertEquals(null, result); }