List of usage examples for java.util Properties getProperty
public String getProperty(String key)
From source file:com.controlj.experiment.bulktrend.trendclient.Main.java
public static void main(String args[]) { Options options = setupCLOptions();/*w w w. java 2 s . c o m*/ CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line parsing failed: " + e.getMessage()); System.exit(-1); } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("trendclient", options); printConfigHelp(); System.exit(0); } // dir option - read config files File baseDir = new File(""); if (line.hasOption(PARAM_DIR)) { baseDir = new File(line.getOptionValue(PARAM_DIR)); } Properties props = getProperties(baseDir); String server = getProperty(props, PROP_SERVER); String parserName = getProperty(props, PROP_PARSER); String handlerName = getProperty(props, PROP_HANDLER); String user = getProperty(props, PROP_USER); String pw = getProperty(props, PROP_PASSWORD); TrendClient tc = new TrendClient(server, getIDs(baseDir), user, pw, handlerName, parserName); String defaultDigitsString = props.getProperty(PROP_DIGITS); if (defaultDigitsString != null) { try { tc.setDefaultDigits(Integer.parseInt(defaultDigitsString)); } catch (NumberFormatException e) { System.err.println("Invalid valid for property " + PROP_DIGITS + ":" + defaultDigitsString); } } //testfile if (line.hasOption(PARAM_TESTFILE)) { String fileName = line.getOptionValue(PARAM_TESTFILE); if (fileName == null) { fileName = "response.dump"; } try { tc.setAlternateInput(new FileInputStream(new File(fileName))); System.out.println("Reading trends from file: " + fileName); } catch (FileNotFoundException e) { System.err.println("Error, " + PARAM_TESTFILE + " '" + fileName + "' not found"); } } else { System.out.println("Reading trends from " + server); System.out.println("Parser=" + parserName); System.out.println("Handler=" + handlerName); } // Start/End Date start = parseDateOption(PARAM_START, line); Date end = parseDateOption(PARAM_END, line); if (start == null) { start = TrendClient.getYesterday().getTime(); } if (end == null) { end = TrendClient.getYesterday().getTime(); } tc.setStart(start); tc.setEnd(end); System.out.println("From " + start + " to " + end); // nozip if (line.hasOption(PARAM_NOZIP)) { tc.setZip(false); } tc.go(); }
From source file:com.yahoo.pulsar.testclient.PerformanceProducer.java
public static void main(String[] args) throws Exception { final Arguments arguments = new Arguments(); JCommander jc = new JCommander(arguments); jc.setProgramName("pulsar-perf-producer"); try {/*from w w w. j a v a 2 s. c om*/ jc.parse(args); } catch (ParameterException e) { System.out.println(e.getMessage()); jc.usage(); System.exit(-1); } if (arguments.help) { jc.usage(); System.exit(-1); } if (arguments.destinations.size() != 1) { System.out.println("Only one topic name is allowed"); jc.usage(); System.exit(-1); } if (arguments.confFile != null) { Properties prop = new Properties(System.getProperties()); prop.load(new FileInputStream(arguments.confFile)); if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("brokerServiceUrl"); } if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("webServiceUrl"); } // fallback to previous-version serviceUrl property to maintain backward-compatibility if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/"); } if (arguments.authPluginClassName == null) { arguments.authPluginClassName = prop.getProperty("authPlugin", null); } if (arguments.authParams == null) { arguments.authParams = prop.getProperty("authParams", null); } } arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime); // Dump config variables ObjectMapper m = new ObjectMapper(); ObjectWriter w = m.writerWithDefaultPrettyPrinter(); log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments)); // Read payload data from file if needed byte payloadData[]; if (arguments.payloadFilename != null) { payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename)); } else { payloadData = new byte[arguments.msgSize]; } // Now processing command line arguments String prefixTopicName = arguments.destinations.get(0); List<Future<Producer>> futures = Lists.newArrayList(); EventLoopGroup eventLoopGroup; if (SystemUtils.IS_OS_LINUX) { eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer")); } else { eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer")); } ClientConfiguration clientConf = new ClientConfiguration(); clientConf.setConnectionsPerBroker(arguments.maxConnections); clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS); if (isNotBlank(arguments.authPluginClassName)) { clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams); } PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup); ProducerConfiguration producerConf = new ProducerConfiguration(); producerConf.setSendTimeout(0, TimeUnit.SECONDS); producerConf.setCompressionType(arguments.compression); // enable round robin message routing if it is a partitioned topic producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition); if (arguments.batchTime > 0) { producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS); producerConf.setBatchingEnabled(true); producerConf.setMaxPendingMessages(arguments.msgRate); } for (int i = 0; i < arguments.numTopics; i++) { String topic = (arguments.numTopics == 1) ? prefixTopicName : String.format("%s-%d", prefixTopicName, i); log.info("Adding {} publishers on destination {}", arguments.numProducers, topic); for (int j = 0; j < arguments.numProducers; j++) { futures.add(client.createProducerAsync(topic, producerConf)); } } final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size()); for (Future<Producer> future : futures) { producers.add(future.get()); } log.info("Created {} producers", producers.size()); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { printAggregatedStats(); } }); Collections.shuffle(producers); AtomicBoolean isDone = new AtomicBoolean(); executor.submit(() -> { try { RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate); long startTime = System.currentTimeMillis(); // Send messages on all topics/producers long totalSent = 0; while (true) { for (Producer producer : producers) { if (arguments.testTime > 0) { if (System.currentTimeMillis() - startTime > arguments.testTime) { log.info("------------------- DONE -----------------------"); printAggregatedStats(); isDone.set(true); Thread.sleep(5000); System.exit(0); } } if (arguments.numMessages > 0) { if (totalSent++ >= arguments.numMessages) { log.info("------------------- DONE -----------------------"); printAggregatedStats(); isDone.set(true); Thread.sleep(5000); System.exit(0); } } rateLimiter.acquire(); final long sendTime = System.nanoTime(); producer.sendAsync(payloadData).thenRun(() -> { messagesSent.increment(); bytesSent.add(payloadData.length); long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime); recorder.recordValue(latencyMicros); cumulativeRecorder.recordValue(latencyMicros); }).exceptionally(ex -> { log.warn("Write error on message", ex); System.exit(-1); return null; }); } } } catch (Throwable t) { log.error("Got error", t); } }); // Print report stats long oldTime = System.nanoTime(); Histogram reportHistogram = null; String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm"; log.info("Dumping latency stats to {}", statsFileName); PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false); HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog); // Some log header bits histogramLogWriter.outputLogFormatVersion(); histogramLogWriter.outputLegend(); while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { break; } if (isDone.get()) { break; } long now = System.nanoTime(); double elapsed = (now - oldTime) / 1e9; double rate = messagesSent.sumThenReset() / elapsed; double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8; reportHistogram = recorder.getIntervalHistogram(reportHistogram); log.info( "Throughput produced: {} msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0)); histogramLogWriter.outputIntervalHistogram(reportHistogram); reportHistogram.reset(); oldTime = now; } client.close(); }
From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java
/** * @param args/* ww w. j a v a2s .c o m*/ */ public static void main(String[] args) throws Exception { logger.info("start time ==== " + System.currentTimeMillis()); try { //load the adb location from the props file Properties props = new Properties(); props.load(new FileInputStream(new File("adb.props"))); //set the adb location WindowUpdate.adbLocation = props.getProperty("adb_location"); adbLocation = props.getProperty("adb_location"); //set root dir ROOT_DIRECTORY = props.getProperty("root_dir"); //completed txt completedFile = new File(ROOT_DIRECTORY + "tested.txt"); //db location for static analysis dbLocation = props.getProperty("db_location"); //location for smart input generation output smartInputLocation = props.getProperty("smart_input_location"); //udp dump location udpDumpLocation = props.getProperty("udp_dump_location"); //logcat dump location logCatLocation = props.getProperty("log_cat_location"); //strace output location straceOutputLocation = props.getProperty("strace_output_location"); //strace dump location straceDumpLocation = props.getProperty("strace_output_location"); //set x and y coords UIEnumerator.screenX = props.getProperty("x"); UIEnumerator.screenY = props.getProperty("y"); DeviceOfflineMonitor.START_EMULATOR = props.getProperty("restart"); //read output of static analysis readFromStaticAnalysisText(); logger.info("Read static analysis output"); readFromSmartInputText(); logger.info("Read smart input generation output"); //populate the queue with apps which are only present in the static analysis @SuppressWarnings("unchecked") final Set<? extends String> sslApps = new HashSet<String>( CollectionUtils.collect(FileUtils.readLines(new File(dbLocation)), new Transformer() { @Override public Object transform(Object input) { //get app file name String temp = StringUtils.substringBefore(input.toString(), " "); return StringUtils.substringAfterLast(temp, "/"); } })); Collection<File> fileList = FileUtils.listFiles(new File(ROOT_DIRECTORY), new String[] { "apk" }, false); CollectionUtils.filter(fileList, new Predicate() { @Override public boolean evaluate(Object object) { return sslApps.contains(StringUtils.substringAfterLast(object.toString(), "/")); } }); apkQueue = new LinkedBlockingDeque<File>(fileList); logger.info("finished listing files from the root directory"); try { //populate the tested apk list completedApps.addAll(FileUtils.readLines(completedFile)); } catch (Exception e) { //pass except logger.info("No tested.txt file found"); //create new file if (completedFile.createNewFile()) { logger.info("tested.txt created in root directory"); } else { logger.info("tested.txt file could not be created"); } } //get the executors for managing the emulators executors = Executors.newCachedThreadPool(); //set the devicemonitor exec DeviceOfflineMonitor.exec = executors; final List<Future<?>> futureList = new ArrayList<Future<?>>(); //start the offline device monitor (emulator management thread) logger.info("Starting Device Offline Monitor Thread"); executors.submit(new DeviceOfflineMonitor()); //get ADB backend object for device change listener AdbBackend adb = new AdbBackend(); //register for device change and wait for events //once event is received, start the MonkeyMe thread MonkeyDeviceChangeListener deviceChangeListener = new MonkeyDeviceChangeListener(executors, futureList); AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener); logger.info("Listening to changes in devices (emulators)"); //wait for the latch to come down //this means that all the apks have been processed cdl.await(); logger.info("Finished testing all apps waiting for threads to join"); //now wait for every thread to finish for (Future<?> future : futureList) { future.get(); } logger.info("All threads terminated"); //stop listening for device update AndroidDebugBridge.removeDeviceChangeListener(deviceChangeListener); //stop the debug bridge AndroidDebugBridge.terminate(); //stop offline device monitor DeviceOfflineMonitor.stop = true; logger.info("adb and listeners terminated"); } finally { logger.info("Executing this finally"); executors.shutdownNow(); } logger.info("THE END!!"); }
From source file:com.simple.sftpfetch.App.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Options options = getOptions();//from ww w . j av a2 s. c o m List<String> requiredProperties = asList("c"); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printUsage(options); System.exit(0); } for (String opt : requiredProperties) { if (!commandLine.hasOption(opt)) { System.err.println("The option: " + opt + " is required."); printUsage(options); System.exit(1); } } Pattern pattern; if (commandLine.hasOption("p")) { pattern = Pattern.compile(commandLine.getOptionValue("p")); } else { pattern = MATCH_EVERYTHING; } String filename = commandLine.getOptionValue("c"); Properties properties = new Properties(); try { InputStream stream = new FileInputStream(new File(filename)); properties.load(stream); } catch (IOException ioe) { System.err.println("Unable to read properties from: " + filename); System.exit(2); } String routingKey = ""; if (commandLine.hasOption("r")) { routingKey = commandLine.getOptionValue("r"); } else if (properties.containsKey("rabbit.routingkey")) { routingKey = properties.getProperty("rabbit.routingkey"); } int daysToFetch; if (commandLine.hasOption("d")) { daysToFetch = Integer.valueOf(commandLine.getOptionValue("d")); } else { daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS)); } FileDecrypter decrypter = null; if (properties.containsKey("decryption.key.path")) { decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path"))); } else { decrypter = new NoopDecrypter(); } SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties)); try { App app = new App(sftpClient, s3FromProperties(properties), new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter, System.out); app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o")); } finally { sftpClient.close(); } System.exit(0); } catch (UnrecognizedOptionException uoe) { System.err.println(uoe.getMessage()); printUsage(options); System.exit(10); } }
From source file:com.ontotext.s4.service.S4ServiceClient.java
public static void main(String... args) { if (args == null || args.length == 0) { printUsageAndTerminate(null);// w w w.ja v a 2s .c om } Parameters params = new Parameters(args); String serviceID = params.getValue("service"); if (serviceID == null) { printUsageAndTerminate("No service name provided"); } ServiceDescriptor service = null; try { service = ServicesCatalog.getItem(serviceID); } catch (UnsupportedOperationException uoe) { printUsageAndTerminate("Unsupported service '" + serviceID + '\''); } SupportedMimeType mimetype = SupportedMimeType.PLAINTEXT; if (params.getValue("dtype") != null) { try { mimetype = SupportedMimeType.valueOf(params.getValue("dtype")); } catch (IllegalArgumentException iae) { printUsageAndTerminate("Unsupported document type (dtype) : " + params.getValue("dtype")); } } String inFile = params.getValue("file"); String url = params.getValue("url"); String outFile = params.getValue("out", "result.json"); if (inFile != null) { if (!new File(inFile).exists()) { printUsageAndTerminate("Input file is not found : " + inFile); } } else { if (url == null) { printUsageAndTerminate("Neither input file, nor remote URL provided"); } } Properties creds = readCredentials(params); if (!creds.containsKey("apikey") || !creds.containsKey("secret")) { printUsageAndTerminate("No credentials details found"); } S4ServiceClient client = new S4ServiceClient(service, creds.getProperty("apikey"), creds.getProperty("secret")); try { InputStream resultData = null; if (service.getName().equals("news-classifier")) { resultData = (inFile != null) ? client.classifyFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype) : client.classifyDocumentFromUrlAsStream(new URL(url), mimetype); } else { resultData = (inFile != null) ? client.annotateFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype, ResponseFormat.JSON) : client.annotateDocumentFromUrlAsStream(new URL(url), mimetype, ResponseFormat.JSON); } FileOutputStream outStream = new FileOutputStream(outFile); IOUtils.copy(resultData, outStream); outStream.close(); resultData.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage()); System.exit(1); } }
From source file:com.google.api.ads.adwords.awreporting.AwReporting.java
/** * Main method./* w w w . j a v a 2 s . co m*/ * * @param args the command line arguments. */ public static void main(String args[]) { // Proxy JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); boolean errors = false; String propertiesPath = null; try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); // Print full help and quit if (cmdLine.hasOption("help")) { printHelpMessage(options); printSamplePropertiesFile(); System.exit(0); } setLogLevel(cmdLine); if (cmdLine.hasOption("file")) { propertiesPath = cmdLine.getOptionValue("file"); } else { LOGGER.error("Missing required option: 'file'"); System.exit(0); } LOGGER.info("Using properties file: " + propertiesPath); Set<Long> accountIdsSet = Sets.newHashSet(); if (cmdLine.hasOption("accountIdsFile")) { String accountsFileName = cmdLine.getOptionValue("accountIdsFile"); addAccountsFromFile(accountIdsSet, accountsFileName); } boolean forceOnFileProcessor = false; if (cmdLine.hasOption("onFileReport")) { if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate") || !cmdLine.hasOption("endDate")) { LOGGER.error("Missing one or more of the required options: " + "'csvReportFile', 'startDate' or 'endDate'"); System.exit(0); } forceOnFileProcessor = true; } Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor); LOGGER.debug("Creating ReportProcessor bean..."); ReportProcessor processor = createReportProcessor(); LOGGER.debug("... success."); String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", ""); if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) { // Generate Reports String dateStart = cmdLine.getOptionValue("startDate"); String dateEnd = cmdLine.getOptionValue("endDate"); if (cmdLine.hasOption("onFileReport")) { String reportTypeName = cmdLine.getOptionValue("onFileReport"); String csvReportFile = cmdLine.getOptionValue("csvReportFile"); File csvFile = new File(csvReportFile); if (!csvFile.exists()) { LOGGER.error("Could not find CSV file: " + csvReportFile); System.exit(0); } ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor; List<File> localFiles = new ArrayList<File>(); localFiles.add(csvFile); LOGGER.info( "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd); onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd, ReportDefinitionDateRangeType.CUSTOM_DATE); } else { LOGGER.info( "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd); processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd, accountIdsSet, properties, null, null); } } else if (cmdLine.hasOption("dateRange")) { ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType .fromValue(cmdLine.getOptionValue("dateRange")); LOGGER.info("Starting report download for dateRange: " + dateRangeType.name()); processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties, null, null); } else { errors = true; LOGGER.error("Configuration incomplete. Missing options for command line."); } } catch (IOException e) { errors = true; if (e.getMessage().contains("Insufficient Permission")) { LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage()); } else { LOGGER.error("File not found: " + e.getMessage()); } } catch (ParseException e) { errors = true; System.err.println("Error parsing the values for the command line options: " + e.getMessage()); } catch (Exception e) { errors = true; LOGGER.error("Unexpected error accessing the API: " + e.getMessage()); e.printStackTrace(); } if (errors) { System.exit(1); } else { System.exit(0); } }
From source file:com.strider.appinv.agent.Scanner.java
public static void main(String[] args) throws ParseException, ScannerException { if (args.length == 0) { log.info("To display usage info please type"); log.info(" java -jar ai.jar com.strider.appinv.agent.Scanner --help"); return;//from w ww. ja v a 2 s . c om } final Options options = createOptions(); final CommandLine line = getCommandLine(options, args); if (line.hasOption("help")) { help(options); return; } if (line.hasOption("debug")) { LogManager.getRootLogger().setLevel(Level.DEBUG); } else { LogManager.getRootLogger().setLevel(Level.INFO); } String scannerPropertyFile = "scanner.properties"; if (line.hasOption("config")) { scannerPropertyFile = line.getOptionValue("config"); } Properties scannerProperties = null; try { scannerProperties = loadProperties(scannerPropertyFile); } catch (IOException ioe) { throw new ScannerException("ERROR: Unable to load " + scannerPropertyFile, ioe); } if (scannerProperties == null) { throw new ScannerException("ERROR: Scanner property file is not defined."); } IScanner scanner = new AppScanner(); Application application = null; if (line.hasOption("scan")) { scanner = new AppScanner(); application = scanner.scan(scannerProperties); } if (line.hasOption("persist") && application != null) { ApplicationUtils.save(application, scannerProperties.getProperty("scan.output.path")); } }
From source file:com.mijecu25.sqlplus.SQLPlus.java
public static void main(String[] args) throws IOException { // Create and load the properties from the application properties file Properties properties = new Properties(); properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE)); SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); // Check if the user is using a valid console (i.e. not from Eclipse) if (System.console() == null) { // The Console object for the JVM could not be found. Alert the user SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running " + SQLPlus.PROGRAM_NAME + "from the command line"); System.out.println(// w w w. j a v a 2 s.com Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. " + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line."); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME)); return; } // UI intro System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME + "! This program has a DSL to add alerts to various SQL DML events."); System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line."); System.out.println(); // Get the version System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); System.out.println(); // Read the license file BufferedReader bufferedReader; bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE)); // Read a line String line = bufferedReader.readLine(); // While the line is not null while (line != null) { System.out.println(line); // Read a new lines line = bufferedReader.readLine(); } // Close the buffer bufferedReader.close(); System.out.println(); // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions // from the user SQLPlus.console = new ConsoleReader(); SQLPlus.console.setHandleUserInterrupt(true); try { // Get credentials from the user SQLPlus.logger.info("Create SQLPlusConnection"); SQLPlus.createSQLPlusConnection(); } catch (NullPointerException | SQLException | IllegalArgumentException e) { // NPE: This exception can occur if the user is running the program where the JVM Console // object cannot be found. // SQLE: TODO should I add here the error code? // This exception can occur when trying to establish a connection // IAE: This exception can occur when trying to establish a connection SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName())); System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); return; } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); return; } System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND); System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application "); try { // Execute the input scanner while (true) { // Get a line from the user until the hit enter (carriage return, line feed/ new line). System.out.print(SQLPlus.PROMPT); try { line = SQLPlus.console.readLine().trim(); } catch (NullPointerException npe) { // TODO test this behavior // If this exception is catch, it is very likely that the user entered the end of line command. // This means that the program should quit. SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that" + "the user entered the end of line command and they want to quit."); SQLPlus.exitSQLPlus(); return; } // If the user did not enter anything if (line.isEmpty()) { // Continue to the next iteration continue; } if (line.equals(".")) { line = "use courses;"; } if (line.equals("-")) { line = "select created_at from classes;"; } if (line.equals("--")) { line = "select name, year from classes;"; } if (line.equals("*")) { line = "select * from classes;"; } if (line.equals("x")) { line = "select name from classes, classes;"; } if (line.equals("e")) { line = "select * feom classes;"; } // Logic to quit if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) { SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME); SQLPlus.exitSQLPlus(); break; } // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each // time jline reads a new line, the variable is empty StringBuilder query = new StringBuilder(); query.append(line); // While the user does not finish the command with the SQLPlus.END_OF_COMMAND while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) { // Print the wait for command prompt and get the next line for the user System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND); query.append(" "); line = StringUtils.stripEnd(SQLPlus.console.readLine(), null); query.append(line); } SQLPlus.logger.info("Raw input from the user: " + query); try { Statement statement; try { // Execute the antlr code to parse the user input SQLPlus.logger.info("Will parse the user input to determine what to execute"); ANTLRStringStream input = new ANTLRStringStream(query.toString()); SQLPlusLex lexer = new SQLPlusLex(input); CommonTokenStream tokens = new CommonTokenStream(lexer); SQLPlusParser parser = new SQLPlusParser(tokens); statement = parser.sqlplus(); } catch (RecognitionException re) { // TODO move this to somehwere else // String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual" // + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase() // + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax"; // SQLPlus.logger.warn(message); // System.out.println(message); statement = new StatementDefault(); } statement.setStatement(query.toString()); SQLPlus.sqlPlusConnection.execute(statement); } catch (UnsupportedOperationException uoe) { // This exception can occur when the user entered a command allowed by the parsers, but not currently // supported by SQLPlus. This can occur because the parser is written in such a way that supports // the addition of features. SQLPlus.logger.warn(Messages.WARNING + uoe); System.out.println( Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported."); } } } catch (IllegalArgumentException iae) { // This exception can occur when a command is executed but it had illegal arguments. Most likely // it is a programmer's error and should be addressed by the developer. SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName())); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); } }
From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java
/** * Main method/*from w w w. jav a2s . c o m*/ * @param args command line arguments */ public static void main(String[] args) { Properties mavenProps = new Properties(); try { mavenProps.load(Dissimilar.class.getClassLoader() .getResourceAsStream("META-INF/maven/uk.bl.dpt.dissimilar/dissimilar/pom.properties")); version = mavenProps.getProperty("version"); } catch (Exception e) { } boolean calcPSNR = true; boolean calcSSIM = true; String heatMapImage = null; CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("m", "heatmap", true, "file to save the ssim heatmap to (png)"); options.addOption("p", "psnr", false, "calculate just psnr"); options.addOption("s", "ssim", false, "calculate just ssim"); options.addOption("h", "help", false, "help text"); CommandLine com = null; try { com = parser.parse(options, args); } catch (ParseException e) { HelpFormatter help = new HelpFormatter(); help.printHelp("Dissimilar v" + version, options); return; } if (com.hasOption("help")) { HelpFormatter help = new HelpFormatter(); help.printHelp("Dissimilar v" + version, options); return; } if (com.hasOption("psnr") & com.hasOption("ssim")) { //do nothing - both on by default } else { if (com.hasOption("psnr")) { calcPSNR = true; calcSSIM = false; } if (com.hasOption("ssim")) { calcPSNR = false; calcSSIM = true; } } if (com.hasOption("heatmap")) { heatMapImage = com.getOptionValue("heatmap"); } File one = new File(com.getArgs()[0]); File two = new File(com.getArgs()[1]); if (one.exists() && two.exists()) { compare(one, two, heatMapImage, calcSSIM, calcPSNR); } }
From source file:com.googlecode.dex2jar.bin_gen.BinGen.java
/** * @param args/*from ww w . j av a 2s .c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { Properties p = new Properties(); p.load(BinGen.class.getResourceAsStream("class.cfg")); String bat = FileUtils.readFileToString( new File("src/main/resources/com/googlecode/dex2jar/bin_gen/bat_template"), "UTF-8"); String sh = FileUtils.readFileToString( new File("src/main/resources/com/googlecode/dex2jar/bin_gen/sh_template"), "UTF-8"); File binDir = new File("src/main/bin"); String setclasspath = FileUtils.readFileToString( new File("src/main/resources/com/googlecode/dex2jar/bin_gen/setclasspath.bat"), "UTF-8"); FileUtils.writeStringToFile(new File(binDir, "setclasspath.bat"), setclasspath, "UTF-8"); for (Object key : p.keySet()) { String name = key.toString(); FileUtils.writeStringToFile(new File(binDir, key.toString() + ".sh"), sh.replaceAll("__@class_name@__", p.getProperty(name)), "UTF-8"); FileUtils.writeStringToFile(new File(binDir, key.toString() + ".bat"), bat.replaceAll("__@class_name@__", p.getProperty(name)), "UTF-8"); } }