List of usage examples for java.lang RuntimeException RuntimeException
public RuntimeException(Throwable cause)
From source file:com.oltpbenchmark.DBWorkload.java
/** * @param args//from w ww . jav a2 s . c om * @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.browseengine.bobo.index.MakeBobo.java
/** * @param args//from ww w . j ava 2s.c o m */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Option help = new Option("help", false, "print this message"); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("data source - required"); Option src = OptionBuilder.create("source"); src.setRequired(true); OptionBuilder.withArgName("path"); OptionBuilder.hasArg(); OptionBuilder.withDescription("index to create - required"); Option index = OptionBuilder.create("index"); index.setRequired(true); OptionBuilder.withArgName("file"); OptionBuilder.hasArg(); OptionBuilder.withDescription("field configuration - optional"); Option conf = OptionBuilder.create("conf"); OptionBuilder.withArgName("class"); OptionBuilder.hasArg(); OptionBuilder.withDescription("class name of the data digester - default: xml digester"); Option digesterOpt = OptionBuilder.create("digester"); OptionBuilder.withArgName("name"); OptionBuilder.hasArg(); OptionBuilder.withDescription("character set name - default: UTF-8"); Option charset = OptionBuilder.create("charset"); OptionBuilder.withArgName("maxdocs"); OptionBuilder.hasArg(); OptionBuilder.withDescription("maximum number of documents - default: 100"); Option maxdocs = OptionBuilder.create("maxdocs"); Options options = new Options(); options.addOption(help); options.addOption(conf); options.addOption(index); options.addOption(src); options.addOption(charset); options.addOption(digesterOpt); options.addOption(maxdocs); // create the parser CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String output = line.getOptionValue("index"); File data = new File(line.getOptionValue("source")); Class digesterClass; if (line.hasOption("digester")) digesterClass = Class.forName(line.getOptionValue("digester")); else throw new RuntimeException("digester not specified"); Charset chset; if (line.hasOption("charset")) { chset = Charset.forName(line.getOptionValue("charset")); } else { chset = Charset.forName("UTF-8"); } int maxDocs; try { maxDocs = Integer.parseInt(line.getOptionValue("maxdocs")); } catch (Exception e) { maxDocs = 100; } FileDigester digester; try { Constructor constructor = digesterClass.getConstructor(new Class[] { File.class }); digester = (FileDigester) constructor.newInstance(new Object[] { data }); digester.setCharset(chset); digester.setMaxDocs(maxDocs); } catch (Exception e) { throw new RuntimeException("Invalid digester class.", e); } BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output))); indexer.index(); } catch (ParseException exp) { exp.printStackTrace(); usage(options); } catch (ClassNotFoundException e) { System.out.println("Invalid digester class."); usage(options); } }
From source file:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java
/** * @param args//w w w .ja va2s . c om */ @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER"); File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); // File dryrunDir = new File(projectDir, "dryrun"); File licenceFile = new File(licenceHeaderURL.toURI()); List<String> licenceLines = readLines(licenceFile); // for (int i = 0; i < licenceLines.size(); i++) { // String licenceLine = licenceLines.get(i); // licenceLines.set(i, " * " + licenceLine); // } // licenceLines.add(0, "/**"); // licenceLines.add(" */"); List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir, new String[] { "java" }, true); for (File javaFile : javaFiles) { if (isValidPackage(javaFile)) { List<String> javaFileLines = readLines(javaFile); if (!javaFileLines.isEmpty()) { boolean modified = false; String firstLineTrim = javaFileLines.get(0).trim(); if (firstLineTrim.startsWith("package")) { modified = true; javaFileLines.addAll(0, licenceLines); } else if (firstLineTrim.startsWith("/**")) { int indexOfEndCommentLine = -1; loop2: for (int i = 0; i < javaFileLines.size(); i++) { String javaFileLine = javaFileLines.get(i); if (javaFileLine.indexOf("*/") != -1) { indexOfEndCommentLine = i; break loop2; } } if (indexOfEndCommentLine != -1) { modified = true; int i = 0; loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) { it.next(); if (i <= indexOfEndCommentLine) { it.remove(); } else { break loop3; } i++; } javaFileLines.addAll(0, licenceLines); } else { throw new RuntimeException( "Missing end comment for file " + javaFile.getAbsolutePath()); } } if (modified) { // String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length()); // File outputFile = new File(dryrunDir, outputFilePath); // outputFile.getParentFile().mkdirs(); // System.out.println(outputFile.getPath()); // FileOutputStream fos = new FileOutputStream(outputFile); System.out.println(javaFile.getPath()); FileOutputStream fos = new FileOutputStream(javaFile); IOUtils.writeLines(javaFileLines, "\n", fos); IOUtils.closeQuietly(fos); } } } } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageReaderMongoServiceTestClient client = new StorageReaderMongoServiceTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_READER_SERVICE_URL = "http://192.168.84.34:8080/storage-reader"; String QUERY_SIMPLE_SENSORID = "1000692"; String QUERY_SIMPLE_STARTTIME = "1387565891068"; String QUERY_SIMPLE_ENDTIME = "1387565996633"; String QUERY_SIMPLE_PROPERTYKEY = "value"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;// w ww. j a v a 2 s . co m // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.DEFAULT: " + body); // The result is an array of simple events serialized as JSON using Apache Thrift. // The simple events can be deserialized into Java objects using Apache Thrift. ObjectMapper mapper = new ObjectMapper(); JsonNode nodeArray = mapper.readTree(body); for (JsonNode node : nodeArray) { byte[] bytes = node.toString().getBytes(); TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); SimpleEvent event = new SimpleEvent(); deserializer.deserialize(event, bytes); System.out.println(event.toString()); } } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/average"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Get status code status = response.getStatusLine().getStatusCode(); if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.AVERAGE: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/maximum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query13 = new HttpGet(requestUrl.toString()); query13.setHeader("Content-type", "application/json"); response = client.execute(query13); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MAXIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/minimum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query14 = new HttpGet(requestUrl.toString()); query14.setHeader("Content-type", "application/json"); response = client.execute(query14); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MINIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.griddynamics.jagger.JaggerLauncher.java
public static void main(String[] args) throws Exception { Thread memoryMonitorThread = new Thread("memory-monitor") { @Override/*from ww w .j a v a2s.c o m*/ public void run() { for (;;) { try { log.info("Memory info: totalMemory={}, freeMemory={}", Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory()); Thread.sleep(60000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }; memoryMonitorThread.setDaemon(true); memoryMonitorThread.start(); String pid = ManagementFactory.getRuntimeMXBean().getName(); System.out.println(String.format("PID:%s", pid)); Properties props = System.getProperties(); for (Map.Entry<Object, Object> prop : props.entrySet()) { log.info("{}: '{}'", prop.getKey(), prop.getValue()); } log.info(""); URL directory = new URL("file:" + System.getProperty("user.dir") + "/"); loadBootProperties(directory, args[0], environmentProperties); log.debug("Bootstrap properties:"); for (String propName : environmentProperties.stringPropertyNames()) { log.debug(" {}={}", propName, environmentProperties.getProperty(propName)); } String[] roles = environmentProperties.getProperty(ROLES).split(","); Set<String> rolesSet = Sets.newHashSet(roles); if (rolesSet.contains(Role.COORDINATION_SERVER.toString())) { launchCoordinationServer(directory); } if (rolesSet.contains(Role.HTTP_COORDINATION_SERVER.toString())) { launchCometdCoordinationServer(directory); } if (rolesSet.contains(Role.RDB_SERVER.toString())) { launchRdbServer(directory); } if (rolesSet.contains(Role.MASTER.toString())) { launchMaster(directory); } if (rolesSet.contains(Role.KERNEL.toString())) { launchKernel(directory); } if (rolesSet.contains(Role.REPORTER.toString())) { launchReporter(directory); } LaunchManager launchManager = builder.build(); int result = launchManager.launch(); System.exit(result); }
From source file:com.example.fangyichen.demomaps.IpInfoDbClient.java
public static void main(String[] args) throws IOException { if (args.length < 2 || args.length > 3) { System.out.println("Usage: org.ipinfodb.IpInfoDbClient MODE API_KEY [IP_ADDRESS]\n" + "MODE can be either 'ip-country' or 'ip-city'.\n" + "If you don't have an API_KEY yet, you can get one for free by registering at http://www.ipinfodb.com/register.php."); return;/*w w w. j ava 2 s .com*/ } String mode = args[0]; String apiKey = args[1]; String url = "http://api.ipinfodb.com/v3/" + mode + "/?format=json&key=" + apiKey; if (args.length > 2) { String ip = args[2]; url += "&ip=" + ip; } try { HttpGet request = new HttpGet(url); HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("IpInfoDb response is " + response.getStatusLine()); } String responseBody = EntityUtils.toString(response.getEntity()); IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class); if ("OK".equals(ipCityResponse.getStatusCode())) { System.out.println(ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName()); } else { System.out.println("API status message is '" + ipCityResponse.getStatusMessage() + "'"); } } finally { HTTP_CLIENT.getConnectionManager().shutdown(); } }
From source file:com.cloudera.csd.tools.codahale.CodahaleMetricsServletMetricConventionsGenerator.java
public static void main(String[] args) throws Exception { if (args.length > 1) { throw new RuntimeException("Unexpected arguments!"); }//from w w w . ja v a 2 s. co m String fixture = JsonUtil.valueAsString(makeConventions(), true); if (args.length == 0) { System.out.println(fixture); } else { FileUtils.write(new File(args[0]), fixture); } }
From source file:com.arpnetworking.metrics.mad.Main.java
/** * Entry point for Metrics Aggregator Daemon (MAD). * * @param args the command line arguments *//* w ww . ja v a 2s . c om*/ public static void main(final String[] args) { // Global initialization Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { System.err.println("Unhandled exception! exception: " + throwable.toString()); throwable.printStackTrace(System.err); }); Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error() .setMessage("Unhandled exception!").setThrowable(throwable).log()); LOGGER.info().setMessage("Launching mad").log(); Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD); System.setProperty("org.vertx.logger-delegate-factory-class-name", "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory"); // Run the tsd aggregator if (args.length != 1) { throw new RuntimeException("No configuration file specified"); } LOGGER.debug().setMessage("Loading configuration").addData("file", args[0]).log(); Optional<DynamicConfiguration> configuration = Optional.empty(); Optional<Configurator<Main, AggregatorConfiguration>> configurator = Optional.empty(); try { final File configurationFile = new File(args[0]); configurator = Optional.of(new Configurator<>(Main::new, AggregatorConfiguration.class)); configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(OBJECT_MAPPER) .addSourceBuilder(getFileSourceBuilder(configurationFile)) .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()) .addListener(configurator.get()).build()); configuration.get().launch(); // Wait for application shutdown SHUTDOWN_SEMAPHORE.acquire(); } catch (final InterruptedException e) { throw Throwables.propagate(e); } finally { if (configurator.isPresent()) { configurator.get().shutdown(); } if (configuration.isPresent()) { configuration.get().shutdown(); } // Notify the shutdown that we're done SHUTDOWN_SEMAPHORE.release(); } }
From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java
/** * /*from ww w .j a v a 2s .c o m*/ * ???server * * @param args */ public static void main(String[] args) throws Exception { // if (args.length != 1) { // LOGGER.error("can not get enough parameters for starting file server"); // printUsage(); // System.exit(-1); // } FileInputStream fis = null; String classLocation = FileServer.class.getProtectionDomain().getCodeSource().getLocation().toString(); final File configFile = new File(classLocation + "/../conf/fileserver.conf"); Properties properties = new Properties(); try { if (configFile.exists()) { fis = new FileInputStream(configFile); } else if (StringUtils.isNotEmpty(args[0])) { fis = new FileInputStream(args[0]); } else { printUsage(); throw new RuntimeException("can't find correct file server configuration file!"); } properties.load(fis); } finally { if (fis != null) { fis.close(); } } int port = -1; try { port = Integer.valueOf(properties.getProperty(PORT_NUM_KEY)); } catch (NumberFormatException e) { LOGGER.error("parameter is not correct, [port = {}]", args[0]); System.exit(-1); } String location = properties.getProperty(ROOT_DIR_KEY); if (StringUtils.isEmpty(location)) { LOGGER.error("the location can not be empty"); System.exit(-1); } File f = new File(location); if (!f.exists() && !f.mkdirs()) { LOGGER.error("invalidation location [{}] please verify the input", args[1]); System.exit(-1); } startServer(location, port); }
From source file:org.ipinfodb.IpInfoDbClient.java
public static void main(String[] args) throws IOException { if (args.length < 3 || args.length > 4) { System.out.println("Usage: org.ipinfodb.IpInfoDbClient MODE API_KEY [IP_ADDRESS]\n" + "MODE can be either 'ip-country' or 'ip-city'.\n" + "If you don't have an API_KEY yet, you can get one for free by registering at http://www.ipinfodb.com/register.php."); return;/*from w w w .j av a 2 s .co m*/ } //Code for Reading the multiple ip addresses from a given txt file. File inputLogFilePath = new File(args[1]); FileReader fr = new FileReader(inputLogFilePath); BufferedReader br = new BufferedReader(fr); String logLine; /*File outputFile=new File("C:/Users/Intelligrape/Desktop/New_Sample_29042014.txt"); // if file doesnt exists, then create it if (!outputFile.exists()) { outputFile.createNewFile(); } FileWriter fw = new FileWriter(outputFile,true); BufferedWriter bw = new BufferedWriter(fw); bw.write("S.no, IPAddress, Country, Region, City, Zipcode"); bw.newLine();*/ try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver found"); } catch (ClassNotFoundException e) { System.out.println("Driver not found: " + e); } String url_db = "jdbc:mysql://mysqldb.c7zitrf2gguq.us-east-1.rds.amazonaws.com/matse?user=shagun&password=shagun001"; Connection con = null; int insertCounter = 0; int count = 1; while ((logLine = br.readLine()) != null) { String mode = args[2]; String apiKey = args[3]; String url = "http://api.ipinfodb.com/v3/" + mode + "/?format=json&key=" + apiKey; String[] split = logLine.split(","); String ip = split[3]; url += "&ip=" + ip; try { HttpGet request = new HttpGet(url); HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("IpInfoDb response is " + response.getStatusLine()); } String responseBody = EntityUtils.toString(response.getEntity()); IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class); if ("OK".equals(ipCityResponse.getStatusCode())) { //System.out.print(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode+ ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone); //bw.write(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode + ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone); try { con = DriverManager.getConnection(url_db); //System.out.println("Connected successfully"); Statement stmt = con.createStatement(); //System.out.println(logLine); //System.out.println(split.length); int result = stmt.executeUpdate("INSERT INTO LOGDATA1 VALUES('" + split[0] + "','" + split[1].trim() + "','" + split[2] + "','" + split[3] + "','" + split[4] + "','" + ipCityResponse.statusCode + "','" + ipCityResponse.countryCode + "','" + ipCityResponse.countryName + "','" + ipCityResponse.regionName + "','" + ipCityResponse.cityName + "','" + ipCityResponse.zipCode + "','" + ipCityResponse.latitude + "','" + ipCityResponse.longitude + "','" + ipCityResponse.timeZone + "')"); ++insertCounter; con.close(); System.out.println(insertCounter); } catch (SQLException e) { System.out.println("something wrong in the connection string: " + e); } } else { System.out.print("API status message is '" + ipCityResponse.getStatusMessage() + "'"); } } finally { //HTTP_CLIENT.getConnectionManager().shutdown(); } ++count; } HTTP_CLIENT.getConnectionManager().shutdown(); }