List of usage examples for org.apache.commons.configuration ConfigurationException printStackTrace
public void printStackTrace()
From source file:ch.epfl.lsir.xin.test.MFTest.java
/** * @param args// ww w .j a va 2s . c o m */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//MF"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//MF.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); logger.flush(); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); logger.flush(); double totalMAE = 0; double totalRMSE = 0; double totalPrecision = 0; double totalRecall = 0; double totalMAP = 0; double totalNDCG = 0; double totalMRR = 0; double totalAUC = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); logger.flush(); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { // if( testRatings.get(i).getValue() < 5 ) // continue; testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a matrix factorization based recommendation model."); logger.flush(); MatrixFactorization algo = new MatrixFactorization(trainRatingMatrix, false, ".//localModels//" + config.getString("NAME")); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); //rating prediction accuracy double RMSE = 0; double MAE = 0; double precision = 0; double recall = 0; double map = 0; double ndcg = 0; double mrr = 0; double auc = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()), itemIDIndexMapping.get(rating.getItemID()), false); if (prediction > algo.getMaxRating()) prediction = algo.getMaxRating(); if (prediction < algo.getMinRating()) prediction = algo.getMinRating(); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: " + MAE + " RMSE: " + RMSE); //ranking accuracy if (algo.getTopN() > 0) { HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>(); for (int i = 0; i < trainRatingMatrix.getRow(); i++) { ArrayList<ResultUnit> rec = algo.getRecommendationList(i); if (rec == null) continue; int total = testRatingMatrix.getUserRatingNumber(i); if (total == 0)//this user is ignored continue; results.put(i, rec); // for( Map.Entry<Integer, Double> entry : testRatingMatrix.getRatingMatrix().get(i).entrySet() ) // { // System.out.print( entry.getKey() + "(" + entry.getValue() + ") , "); // } // System.out.println(); // for( int j = 0 ; j < rec.size() ; j++ ) // { // System.out.print(rec.get(j).getItemIndex() + "(" + rec.get(j).getPrediciton() + // ") , "); // } // System.out.println("**********"); } RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix, trainRatingMatrix); precision = generator.getPrecisionN(); totalPrecision = totalPrecision + precision; recall = generator.getRecallN(); totalRecall = totalRecall + recall; map = generator.getMAPN(); totalMAP = totalMAP + map; ndcg = generator.getNDCGN(); totalNDCG = totalNDCG + ndcg; mrr = generator.getMRRN(); totalMRR = totalMRR + mrr; auc = generator.getAUC(); totalAUC = totalAUC + auc; System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc); logger.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); System.out.println("Precision@N: " + totalPrecision / F); System.out.println("Recall@N: " + totalRecall / F); System.out.println("MAP@N: " + totalMAP / F); System.out.println("MRR@N: " + totalMRR / F); System.out.println("NDCG@N: " + totalNDCG / F); System.out.println("AUC@N: " + totalAUC / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n" + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F); logger.flush(); logger.close(); }
From source file:fm.last.irccat.IRCCat.java
public static void main(String[] args) throws Exception { try {/*from w ww. j a va2 s.c o m*/ if (args.length == 0) { System.out.println("first param should be config file"); System.exit(-1); } XMLConfiguration c = null; try { c = new XMLConfiguration(args[0]); } catch (ConfigurationException cex) { System.err.println("Configuration error, check config file"); cex.printStackTrace(); System.exit(1); } IRCCat bot = new IRCCat(c); // listen for stuff and send it to irc: ServerSocket serverSocket = null; InetAddress inet = null; try { if (bot.getCatIP() != null) inet = InetAddress.getByName(bot.getCatIP()); } catch (UnknownHostException ex) { System.out.println("Could not resolve config cat.ip, fix your config"); ex.printStackTrace(); System.exit(2); } try { serverSocket = new ServerSocket(bot.getCatPort(), 0, inet); } catch (IOException e) { System.err.println("Could not listen on port: " + bot.getCatPort()); System.exit(1); } System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort()); while (true) { try { Socket clientSocket = serverSocket.accept(); // System.out.println("Connection on catport from: " // + clientSocket.getInetAddress().toString()); CatHandler handler = new CatHandler(clientSocket, bot); handler.start(); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ls.zencat.ZenCat.java
public static void main(String[] args) throws Exception { try {/*from w w w.j a va2s .c o m*/ if (args.length == 0) { System.out.println("first param should be config file"); System.exit(-1); } XMLConfiguration c = null; try { c = new XMLConfiguration(args[0]); } catch (ConfigurationException cex) { System.err.println("Configuration error, check config file"); cex.printStackTrace(); System.exit(1); } ZenCat bot = new ZenCat(c); // listen for stuff and send it to irc: ServerSocket serverSocket = null; InetAddress inet = null; try { if (bot.getCatIP() != null) inet = InetAddress.getByName(bot.getCatIP()); } catch (UnknownHostException ex) { System.out.println("Could not resolve config cat.ip, fix your config"); ex.printStackTrace(); System.exit(2); } try { serverSocket = new ServerSocket(bot.getCatPort(), 0, inet); } catch (IOException e) { System.err.println("Could not listen on port: " + bot.getCatPort()); System.exit(1); } System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort()); while (true) { try { Socket clientSocket = serverSocket.accept(); // System.out.println("Connection on catport from: " // + clientSocket.getInetAddress().toString()); CatHandler handler = new CatHandler(clientSocket, bot); handler.start(); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:net.sf.tweety.cli.plugins.CliMain.java
public static void main(String[] args) { // check, if first call parameter is for the helptext if (args.length == 0) { System.out.println("Welcome to the Tweety command line interface."); System.out.println("Obtain help with command --help"); System.exit(0);/*w ww. ja v a 2s. com*/ } else if ((args.length == 1 && args[0].equals("--help"))) { printHelpText(); System.exit(0); } else if (args.length == 1 && !args[0].contains("--help")) { System.out.println("No valid input, call with --help for helptext"); System.exit(0); } // create new plugin manager PluginManager pm = PluginManagerFactory.createPluginManager(); // create plugin manager util PluginManagerUtil pmu = new PluginManagerUtil(pm); // System.out.println(pmu.getPlugins()); // collected parameter ArrayList<ArrayList<String>> collectedparams = new ArrayList<ArrayList<String>>(); // list of available plugins Map<String, String> availablePlugins = new HashMap<String, String>(); // try to configure CLI try { availablePlugins = configCLI(); } catch (ConfigurationException e) { System.out.println("Something went wrong with your Configuration: "); e.printStackTrace(); } catch (FileNotFoundException e) { System.out.println("No such configuration file: "); e.printStackTrace(); } // handle all input parameter for (int i = 0; i < args.length; i++) { // The called plugin if (args[i].equals(ARG__CALLED_PLUGIN) || args[i].equals(ARG__CALLED_PLUGIN_SHORT)) { String calledPlugin = ""; while ((i + 1) < args.length && !args[i + 1].startsWith("-")) { calledPlugin += args[++i]; } plugin = calledPlugin; } // the input files else if (args[i].equals(ARG__INPUT_FILES) || args[i].equals(ARG__INPUT_FILES_SHORT)) { ArrayList<String> inFiles = new ArrayList<String>(); while ((i + 1) < args.length && !args[i + 1].startsWith("-")) { inFiles.add(args[++i]); } String[] files = new String[inFiles.size()]; inFiles.toArray(files); File[] inf = new File[inFiles.size()]; for (int k = 0; k < inf.length; k++) { inf[k] = new File(files[k]).getAbsoluteFile(); } inputFiles = inf; } // output file else if (args[i].equals(ARG__OUTPUT_FILE) || args[i].equals(ARG__OUTPUT_FILE_SHORT)) { // outputFile not used! outputFile = args[++i]; } // collecting given command parameters else if (args[i].startsWith("-")) { ArrayList<String> temp = new ArrayList<String>(); temp.add(args[i]); while ((i + 1) < args.length && !args[i + 1].startsWith("-")) { temp.add(args[++i]); } collectedparams.add(temp); } // else if (args[i].equals(ARG__DEBUG_FLAG) // ||args[i].equals(ARG__DEBUG_FLAG_SHORT)){ // debug = true; // } } // check whether the called plugin is present boolean pluginPresent = false; for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) { if (tp.getCommand().equalsIgnoreCase(plugin)) { pluginPresent = true; System.out.println("Called plugin present"); } } // TODO: move loading into own method // trying to load plugin if not present // old method for loading plugins if (!pluginPresent) { System.out.print("Trying to find plugin..."); if (availablePlugins.containsKey(plugin)) { pm.addPluginsFrom(new File(availablePlugins.get(plugin)).toURI()); System.out.print("success.\n"); } else { System.out.print("no such plugin available.\n"); } } // Test: print all plugins // System.out.println("Plugin loaded due to call parameter: " + // pm.getPlugin(TweetyPlugin.class, new // OptionCapabilities("Tweety Plugin", plugin) )); // System.out.println("Print all plugins: " + pmu.getPlugins()); // System.out.println("Given plugin call parameter: " + plugin); // each plugin MUST implement the capabilites "Tweety Plugin" and the // variable "call parameter" to select called plugin from plugin pool TweetyPlugin tp = pm.getPlugin(TweetyPlugin.class, new OptionCapabilities("Tweety Plugin", plugin)); // for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) { if (tp.getCommand().equalsIgnoreCase(plugin)) { System.out.println("Valid plugin found."); // each input parameter is checked against the called plugin // whether it is valid ArrayList<CommandParameter> ip = new ArrayList<CommandParameter>(); System.out.print("Trying to instantiate parameters..."); try { ip.addAll(instantiateParameters(tp, collectedparams)); System.out.print("done.\n"); } catch (CloneNotSupportedException e) { e.printStackTrace(); } PluginOutput out = new PluginOutput(); System.out.println("Execute Plugin..."); out = tp.execute(inputFiles, ip.toArray(new CommandParameter[ip.size()])); if (outputFile != null) { try { FileWriter fw = new FileWriter(outputFile); fw.write(out.getOutput()); fw.close(); System.out.println("Output written to file: " + outputFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("No output file given, writing to console..."); System.out.println("Output: \n" + out.getOutput()); } } else { System.out.println("Faulty parameters. Please check input."); } }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
/** * @param args/* www . jav a 2 s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { String duration = null; String scenarioFile = null; // ------------------------------------------------------------------- // INITIALIZE LOGGING // ------------------------------------------------------------------- String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // ------------------------------------------------------------------- // PARSE COMMAND LINE PARAMETERS // ------------------------------------------------------------------- CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("s", "scenario", true, "[required] Workload scenario file"); options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation"); options.addOption("r", "runtime", true, "maximum runtime (no events will be started after finishing runtime)"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("g", "gui", false, "Show controlling GUI"); options.addOption("h", "help", false, "Print this help"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("b", "baseline", true, "Output files of previous baseline run"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (!argsLine.hasOption("scenario")) { INIT_LOG.fatal("Missing scenario description file"); System.exit(-1); } else scenarioFile = argsLine.getOptionValue("scenario"); if (argsLine.hasOption("r")) duration = argsLine.getOptionValue("r"); if (argsLine.hasOption("runtime")) duration = argsLine.getOptionValue("runtime"); // ------------------------------------------------------------------- // CREATE TENANT SCHEDULE // ------------------------------------------------------------------- INIT_LOG.info("Create schedule"); Schedule schedule = new Schedule(duration, scenarioFile); HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents(); ArrayList<Integer> tenantList = schedule.getTenantList(); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) { int tenantID = tenantList.get(tenInd); for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) { BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID) .getBenchmarkSettings(tenEvent); // update benchmark Settings benchmarkSettings.setTenantID(tenantID); // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = benchmarkSettings.getBenchmark(); String[] pluginList = plugins.split(","); String configFile = benchmarkSettings.getConfigFile(); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setTenantId(tenantID); wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID)); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID))); wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID)); wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID)); wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID)); wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID)); wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID)); String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"), tenantID); int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString)); wrkld.setTerminals(terminals); int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1")); if (taSize < 0) INIT_LOG.fatal("taSize must not be negative!"); wrkld.setTaSize(taSize); wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false)); wrkld.setIsolationMode(setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID)); wrkld.setScaleFactor(Double .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID))); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or // single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID); rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string), tenantID); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format( "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Tenant " + tenantID + ": Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format( "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)), tenantID)); activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)), tenantID)); if (activeTerminals > terminals) { LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); if (numTxnTypes == 0 && pluginList.length == 1) { // if it is a single workload run, <transactiontypes /> // w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format("Tenant " + tenantID + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID)); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = Integer .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID)); } ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset)); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); if (benchmarkSettings.getBenchmarkSlaFile() != null) wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile()); LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt); bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent)); bench.setTenantID(tenantID); bench.setBenchmarkSettings(benchmarkSettings); benchList.add(bench); } } } // create result collector ResultCollector rCollector = new ResultCollector(tenantList); // execute benchmarks in parallel ArrayList<Thread> benchThreads = new ArrayList<Thread>(); for (BenchmarkModule benchmark : benchList) { BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine); Thread t = new Thread(benchThread); t.start(); benchThreads.add(t); benchmark.getWorkloadConfiguration().setrCollector(rCollector); } // waiting for completion of all benchmarks for (Thread t : benchThreads) { t.join(); } // print statistics int analysisBuckets = -1; if (argsLine.hasOption("analysis-buckets")) analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets")); String output = null; if (argsLine.hasOption("o")) output = argsLine.getOptionValue("o"); String baseline = null; if (argsLine.hasOption("b")) baseline = argsLine.getOptionValue("b"); rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline); // create GUI if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) { try { Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector, output); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.oltpbenchmark.DBWorkload.java
/** * @param args/*from w w w. ja v a 2 s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { // Initialize log4j String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // create the command line parser CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("b", "bench", true, "[required] Benchmark class. Currently supported: " + pluginConfig.getList("/plugin//@name")); options.addOption("c", "config", true, "[required] Workload configuration file"); options.addOption(null, "create", true, "Initialize the database for this benchmark"); options.addOption(null, "clear", true, "Clear all records in the database for this benchmark"); options.addOption(null, "load", true, "Load data using the benchmark's data loader"); options.addOption(null, "execute", true, "Execute the benchmark workload"); options.addOption(null, "runscript", true, "Run an SQL script"); options.addOption(null, "upload", true, "Upload the result"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("h", "help", false, "Print this help"); options.addOption("s", "sample", true, "Sampling window"); options.addOption("ss", false, "Verbose Sampling per Transaction"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("d", "directory", true, "Base directory for the result files, default is current directory"); options.addOption("t", "timestamp", false, "Each result file is prepended with a timestamp for the beginning of the experiment"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption(null, "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (argsLine.hasOption("c") == false) { LOG.error("Missing Configuration file"); printUsage(options); return; } else if (argsLine.hasOption("b") == false) { LOG.fatal("Missing Benchmark Class to load"); printUsage(options); return; } // If an output directory is used, store the information String outputDirectory = ""; if (argsLine.hasOption("d")) { outputDirectory = argsLine.getOptionValue("d"); } String timestampValue = ""; if (argsLine.hasOption("t")) { timestampValue = String.valueOf(TimeUtil.getCurrentTime().getTime()) + "_"; } // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = argsLine.getOptionValue("b"); String[] pluginList = plugins.split(","); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); // Use this list for filtering of the output List<TransactionType> activeTXTypes = new ArrayList<TransactionType>(); String configFile = argsLine.getOptionValue("c"); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setBenchmarkName(plugin); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(xmlConfig.getString("dbtype"))); wrkld.setDBDriver(xmlConfig.getString("driver")); wrkld.setDBConnection(xmlConfig.getString("DBUrl")); wrkld.setDBName(xmlConfig.getString("DBName")); wrkld.setDBUsername(xmlConfig.getString("username")); wrkld.setDBPassword(xmlConfig.getString("password")); int terminals = xmlConfig.getInt("terminals[not(@bench)]", 0); terminals = xmlConfig.getInt("terminals" + pluginTest, terminals); wrkld.setTerminals(terminals); wrkld.setIsolationMode(xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE")); wrkld.setScaleFactor(xmlConfig.getDouble("scalefactor", 1.0)); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = work.getString("rate[not(@bench)]", ""); rate_string = work.getString("rate" + pluginTest, rate_string); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format("Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format("Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = work.getString("@arrival", "regular"); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = work.getInt("active_terminals[not(@bench)]", terminals); activeTerminals = work.getInt("active_terminals" + pluginTest, activeTerminals); if (activeTerminals > terminals) { System.out.println("Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(work.getInt("/time"), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype") .size(); if (numTxnTypes == 0 && pluginList.length == 1) { //if it is a single workload run, <transactiontypes /> w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype") .size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format( "Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]")); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = xmlConfig.getString(key + "/name"); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = xmlConfig.getInt(key + "/id"); } TransactionType tmpType = bench.initTransactionType(txnName, txnId + txnIdOffset); // Keep a reference for filtering activeTXTypes.add(tmpType); // Add a reference for the active TTypes in this benchmark ttypes.add(tmpType); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); LOG.debug("Using the following transaction types: " + tt); benchList.add(bench); } // Export StatementDialects if (isBooleanOptionSet(argsLine, "dialects-export")) { BenchmarkModule bench = benchList.get(0); if (bench.getStatementDialects() != null) { LOG.info("Exporting StatementDialects for " + bench); String xml = bench.getStatementDialects().export(bench.getWorkloadConfiguration().getDBType(), bench.getProcedures().values()); System.out.println(xml); System.exit(0); } throw new RuntimeException("No StatementDialects is available for " + bench); } @Deprecated boolean verbose = argsLine.hasOption("v"); // Create the Benchmark's Database if (isBooleanOptionSet(argsLine, "create")) { for (BenchmarkModule benchmark : benchList) { CREATE_LOG.info("Creating new " + benchmark.getBenchmarkName().toUpperCase() + " database..."); runCreator(benchmark, verbose); CREATE_LOG.info("Finished!"); CREATE_LOG.info(SINGLE_LINE); } } else if (CREATE_LOG.isDebugEnabled()) { CREATE_LOG.debug("Skipping creating benchmark database tables"); CREATE_LOG.info(SINGLE_LINE); } // Clear the Benchmark's Database if (isBooleanOptionSet(argsLine, "clear")) { for (BenchmarkModule benchmark : benchList) { CREATE_LOG.info("Resetting " + benchmark.getBenchmarkName().toUpperCase() + " database..."); benchmark.clearDatabase(); CREATE_LOG.info("Finished!"); CREATE_LOG.info(SINGLE_LINE); } } else if (CREATE_LOG.isDebugEnabled()) { CREATE_LOG.debug("Skipping creating benchmark database tables"); CREATE_LOG.info(SINGLE_LINE); } // Execute Loader if (isBooleanOptionSet(argsLine, "load")) { for (BenchmarkModule benchmark : benchList) { LOAD_LOG.info("Loading data into " + benchmark.getBenchmarkName().toUpperCase() + " database..."); runLoader(benchmark, verbose); LOAD_LOG.info("Finished!"); LOAD_LOG.info(SINGLE_LINE); } } else if (LOAD_LOG.isDebugEnabled()) { LOAD_LOG.debug("Skipping loading benchmark database records"); LOAD_LOG.info(SINGLE_LINE); } // Execute a Script if (argsLine.hasOption("runscript")) { for (BenchmarkModule benchmark : benchList) { String script = argsLine.getOptionValue("runscript"); SCRIPT_LOG.info("Running a SQL script: " + script); runScript(benchmark, script); SCRIPT_LOG.info("Finished!"); SCRIPT_LOG.info(SINGLE_LINE); } } // Execute Workload if (isBooleanOptionSet(argsLine, "execute")) { // Bombs away! Results r = null; try { r = runWorkload(benchList, verbose); } catch (Throwable ex) { LOG.error("Unexpected error when running benchmarks.", ex); System.exit(1); } assert (r != null); PrintStream ps = System.out; PrintStream rs = System.out; ResultUploader ru = new ResultUploader(r, xmlConfig, argsLine); if (argsLine.hasOption("o")) { // Check if directory needs to be created if (outputDirectory.length() > 0) { FileUtil.makeDirIfNotExists(outputDirectory.split("/")); } // Build the complex path String baseFile = timestampValue + argsLine.getOptionValue("o"); // Increment the filename for new results String nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res")); ps = new PrintStream(new File(nextName)); EXEC_LOG.info("Output into file: " + nextName); nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".raw")); rs = new PrintStream(new File(nextName)); EXEC_LOG.info("Output Raw data into file: " + nextName); nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".summary")); PrintStream ss = new PrintStream(new File(nextName)); EXEC_LOG.info("Output summary data into file: " + nextName); ru.writeSummary(ss); ss.close(); nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".db.cnf")); ss = new PrintStream(new File(nextName)); EXEC_LOG.info("Output db config into file: " + nextName); ru.writeDBParameters(ss); ss.close(); nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".ben.cnf")); ss = new PrintStream(new File(nextName)); EXEC_LOG.info("Output benchmark config into file: " + nextName); ru.writeBenchmarkConf(ss); ss.close(); } else if (EXEC_LOG.isDebugEnabled()) { EXEC_LOG.debug("No output file specified"); } if (argsLine.hasOption("s")) { int windowSize = Integer.parseInt(argsLine.getOptionValue("s")); EXEC_LOG.info("Grouped into Buckets of " + windowSize + " seconds"); r.writeCSV(windowSize, ps); if (isBooleanOptionSet(argsLine, "upload")) { ru.uploadResult(); } // Allow more detailed reporting by transaction to make it easier to check if (argsLine.hasOption("ss")) { for (TransactionType t : activeTXTypes) { PrintStream ts = ps; if (ts != System.out) { // Get the actual filename for the output String baseFile = timestampValue + argsLine.getOptionValue("o") + "_" + t.getName(); String prepended = outputDirectory + timestampValue; String nextName = FileUtil .getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res")); ts = new PrintStream(new File(nextName)); r.writeCSV(windowSize, ts, t); ts.close(); } } } } else if (EXEC_LOG.isDebugEnabled()) { EXEC_LOG.warn("No bucket size specified"); } if (argsLine.hasOption("histograms")) { EXEC_LOG.info(SINGLE_LINE); EXEC_LOG.info("Completed Transactions:\n" + r.getTransactionSuccessHistogram() + "\n"); EXEC_LOG.info("Aborted Transactions:\n" + r.getTransactionAbortHistogram() + "\n"); EXEC_LOG.info("Rejected Transactions:\n" + r.getTransactionRetryHistogram()); EXEC_LOG.info("Unexpected Errors:\n" + r.getTransactionErrorHistogram()); if (r.getTransactionAbortMessageHistogram().isEmpty() == false) EXEC_LOG.info( "User Aborts:\n" + StringUtil.formatMaps(r.getTransactionAbortMessageHistogram())); } else if (EXEC_LOG.isDebugEnabled()) { EXEC_LOG.warn("No bucket size specified"); } r.writeAllCSVAbsoluteTiming(rs); ps.close(); rs.close(); } else { EXEC_LOG.info("Skipping benchmark workload execution"); } }
From source file:com.github.rwhogg.git_vcr.App.java
/** * main is the entry point for Git-VCR// w w w . j a va 2s.c o m * @param args Command-line arguments */ public static void main(String[] args) { Options options = parseCommandLine(args); HierarchicalINIConfiguration configuration = null; try { configuration = getConfiguration(); } catch (ConfigurationException e) { Util.error("could not parse configuration file!"); } // verify we are in a git folder and then construct the repo final File currentFolder = new File("."); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository localRepo = null; try { localRepo = builder.findGitDir().build(); } catch (IOException e) { Util.error("not in a Git folder!"); } // deal with submodules assert localRepo != null; if (localRepo.isBare()) { FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder(); Repository parentRepo; try { parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build(); localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName()); } catch (IOException e) { Util.error("could not find parent of submodule!"); } } // if we need to retrieve the patch file, get it now URL patchUrl = options.getPatchUrl(); String patchPath = patchUrl.getFile(); File patchFile = null; HttpUrl httpUrl = HttpUrl.get(patchUrl); if (httpUrl != null) { try { patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff"); Request request = new Request.Builder().url(httpUrl).build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request); Response response = call.execute(); ResponseBody body = response.body(); if (!response.isSuccessful()) { Util.error("could not retrieve diff file from URL " + patchUrl); } String content = body.string(); org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null); } catch (IOException ie) { Util.error("could not retrieve diff file from URL " + patchUrl); } } else { patchFile = new File(patchPath); } // find the patch //noinspection ConstantConditions if (!patchFile.canRead()) { Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!"); } final Git git = new Git(localRepo); // handle the branch String branchName = options.getBranchName(); String theOldCommit = null; try { theOldCommit = localRepo.getBranch(); } catch (IOException e2) { Util.error("could not get reference to current branch!"); } final String oldCommit = theOldCommit; // needed to reference from shutdown hook if (branchName != null) { // switch to the branch try { git.checkout().setName(branchName).call(); } catch (RefAlreadyExistsException e) { // FIXME Auto-generated catch block e.printStackTrace(); } catch (RefNotFoundException e) { Util.error("the branch " + branchName + " was not found!"); } catch (InvalidRefNameException e) { Util.error("the branch name " + branchName + " is invalid!"); } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) { Util.error("there was a checkout conflict!"); } catch (GitAPIException e) { Util.error("there was an unspecified Git API failure!"); } } // ensure there are no changes before we apply the patch try { if (!git.status().call().isClean()) { Util.error("cannot run git-vcr while there are uncommitted changes!"); } } catch (NoWorkTreeException e1) { // won't happen assert false; } catch (GitAPIException e1) { Util.error("call to git status failed!"); } // list all the files changed String patchName = patchFile.getName(); Patch patch = new Patch(); try { patch.parse(new FileInputStream(patchFile)); } catch (FileNotFoundException e) { assert false; } catch (IOException e) { Util.error("could not parse the patch file!"); } ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false); try { oldResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // we're about to change the repo, so register a shutdown hook to clean it up Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cleanupGit(git, oldCommit); } }); // apply the patch try { git.apply().setPatch(new FileInputStream(patchFile)).call(); } catch (PatchFormatException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!"); } catch (PatchApplyException e) { Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!"); } catch (FileNotFoundException e) { assert false; } catch (GitAPIException e) { Util.error(e.getLocalizedMessage()); } ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true); try { newResults.review(); } catch (InstantiationException e1) { Util.error("could not instantiate a review tool class!"); } catch (IllegalAccessException e1) { Util.error("illegal access to a class"); } catch (ClassNotFoundException e1) { Util.error("could not find a review tool class"); } catch (ReviewFailedException e1) { e1.printStackTrace(); Util.error("Review failed!"); } // generate and show the report VelocityReport report = new VelocityReport(patch, oldResults, newResults); File reportFile = null; try { reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html"); org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null); } catch (IOException e) { Util.error("could not generate the results page!"); } try { assert reportFile != null; Desktop.getDesktop().open(reportFile); } catch (IOException e) { Util.error("could not open the results page!"); } }
From source file:eu.forgetit.middleware.ConfigurationManager.java
public static Configuration getConfiguration() { if (configuration == null) { try {/*from ww w. java2 s. com*/ configuration = new PropertiesConfiguration(PROPERTY_FILE); } catch (ConfigurationException e) { e.printStackTrace(); } } return configuration; }
From source file:io.coala.config.ConfigUtil.java
/** * @return/* w w w . j av a 2 s. c om*/ */ public static Configuration getMainConfig() { if (MAIN_CONFIG == null) try { MAIN_CONFIG = new PropertiesConfiguration(PROPERTIES_FILE); } catch (final ConfigurationException e) { e.printStackTrace(); MAIN_CONFIG = new PropertiesConfiguration(); } return MAIN_CONFIG; }
From source file:com.cisco.oss.foundation.http.apache.test.JavaClientSample.java
@BeforeClass public static void init() { try {//from ww w.j a v a 2 s . co m propsConfiguration = new PropertiesConfiguration( TestApacheClient.class.getResource("/config.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } }