List of usage examples for org.apache.commons.cli CommandLine getOptionValue
public String getOptionValue(char opt)
From source file:SuperPeer.java
/** * The good stuff./*www . j a va2s. c o m*/ */ public static void main(String[] argv) { int mbits = 5; ArgumentHandler cli = new ArgumentHandler("SuperPeer [-h]", "Run a DHT SuperPeer and attached to the specified superpeer.", "Bala Subrahmanyam Kambala, Daniel William DaCosta - GPLv3 (http://www.gnu.org/copyleft/gpl.html)"); cli.addOption("h", "help", false, "Print this usage information."); cli.addOption("m", "mbits", true, "The maximum number of unique keys in terms of 2^m (Default is " + Integer.toString(mbits) + ")."); CommandLine commandLine = cli.parse(argv); if (commandLine.hasOption('h')) { cli.usage(""); System.exit(0); } if (commandLine.hasOption('m')) { //XXX:uncaught exception! mbits = Integer.parseInt((commandLine.getOptionValue('m'))); } try { Naming.rebind("SuperPeer", new SuperPeer(mbits)); } catch (Exception e) { System.out.println("SuperPeer failed: " + e); } }
From source file:net.ladenthin.snowman.imager.run.CLI.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { try {/*from w w w . jav a 2 s . c o m*/ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(cmdHelpS, cmdHelp, false, cmdHelpD); options.addOption(cmdVersionS, cmdVersion, false, cmdVersionD); options.addOption(OptionBuilder.withDescription(cmdConfigurationD).withLongOpt(cmdConfiguration) .hasArg().withArgName(cmdConfigurationA).create(cmdConfigurationS)); // parse the command line arguments CommandLine line = parser.parse(options, args); final String cmdLineSyntax = "java -jar " + Imager.jarFilename; // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); final String configurationPath; if (line.hasOption(cmdConfiguration)) { configurationPath = line.getOptionValue(cmdConfiguration); } else { System.out.println("Need configuration value."); formatter.printHelp(cmdLineSyntax, options); return; } // check parameter if (args.length == 0 || line.hasOption(cmdHelp)) { formatter.printHelp(cmdLineSyntax, options); return; } if (line.hasOption(cmdVersion)) { System.out.println(Imager.version); return; } Imager imager = new Imager(configurationPath); imager.waitForAllThreads(); imager.restartAndExit(); } catch (IllegalArgumentException | ParseException | IOException | InstantiationException | InterruptedException e) { LOGGER.error("Critical exception.", e); System.exit(-1); } }
From source file:android.example.hlsmerge.crypto.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {/*from ww w. j a v a2s . c om*/ String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl, null); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:com.mvdb.etl.actions.ExtractDBChanges.java
public static void main(String[] args) throws JSONException { ActionUtils.setUpInitFileProperty(); // boolean success = ActionUtils.markActionChainBroken("Just Testing"); // System.exit(success ? 0 : 1); ActionUtils.assertActionChainNotBroken(); ActionUtils.assertEnvironmentSetupOk(); ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing."); ActionUtils.assertFileExists("~/.mvdb/status.InitCustomerData.complete", "300init-customer-data.sh not executed yet. Exiting"); //This check is not required as data can be modified any number of times //ActionUtils.assertFileDoesNotExist("~/.mvdb/status.ModifyCustomerData.complete", "ModifyCustomerData already done. Start with 100init.sh if required. Exiting"); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.start", true); //String schemaDescription = "{ 'root' : [{'table' : 'orders', 'keyColumn' : 'order_id', 'updateTimeColumn' : 'update_time'}]}"; String customerName = null;//from w ww . j a va2 s . co m final CommandLineParser cmdLinePosixParser = new PosixParser(); final Options posixOptions = constructPosixOptions(); CommandLine commandLine; try { commandLine = cmdLinePosixParser.parse(posixOptions, args); if (commandLine.hasOption("customer")) { customerName = commandLine.getOptionValue("customer"); } } catch (ParseException parseException) // checked exception { System.err.println( "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage()); } if (customerName == null) { System.err.println("Could not find customerName. Aborting..."); System.exit(1); } ApplicationContext context = Top.getContext(); final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO"); final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO"); final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO"); File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName); try { FileUtils.writeStringToFile(new File("/tmp/etl.extractdbchanges.directory.txt"), snapshotDirectory.getName(), false); } catch (IOException e) { e.printStackTrace(); System.exit(1); return; } long currentTime = new Date().getTime(); Configuration lastRefreshTimeConf = configurationDAO.find(customerName, "last-refresh-time"); Configuration schemaDescriptionConf = configurationDAO.find(customerName, "schema-description"); long lastRefreshTime = Long.parseLong(lastRefreshTimeConf.getValue()); OrderJsonFileConsumer orderJsonFileConsumer = new OrderJsonFileConsumer(snapshotDirectory); Map<String, ColumnMetadata> metadataMap = orderDAO.findMetadata(); //write file schema-orders.dat in snapshotDirectory genericDAO.fetchMetadata("orders", snapshotDirectory); //writes files: header-orders.dat, data-orders.dat in snapshotDirectory JSONObject json = new JSONObject(schemaDescriptionConf.getValue()); JSONArray rootArray = json.getJSONArray("root"); int length = rootArray.length(); for (int i = 0; i < length; i++) { JSONObject jsonObject = rootArray.getJSONObject(i); String table = jsonObject.getString("table"); String keyColumnName = jsonObject.getString("keyColumn"); String updateTimeColumnName = jsonObject.getString("updateTimeColumn"); System.out.println("table:" + table + ", keyColumn: " + keyColumnName + ", updateTimeColumn: " + updateTimeColumnName); genericDAO.fetchAll2(snapshotDirectory, new Timestamp(lastRefreshTime), table, keyColumnName, updateTimeColumnName); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. try { String sourceDirectoryAbsolutePath = snapshotDirectory.getAbsolutePath(); File sourceRelativeDirectoryPath = getRelativeSnapShotDirectory(configurationDAO, sourceDirectoryAbsolutePath); String hdfsRoot = ActionUtils.getConfigurationValue(ConfigurationKeys.GLOBAL_CUSTOMER, ConfigurationKeys.GLOBAL_HDFS_ROOT); String targetDirectoryFullPath = hdfsRoot + "/data" + sourceRelativeDirectoryPath; ActionUtils.copyLocalDirectoryToHdfsDirectory(sourceDirectoryAbsolutePath, targetDirectoryFullPath); String dirName = snapshotDirectory.getName(); ActionUtils.setConfigurationValue(customerName, ConfigurationKeys.LAST_COPY_TO_HDFS_DIRNAME, dirName); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects Extracted from database. But copy of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to hdfs <" + "" + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. String targetZip = null; try { File targetZipDirectory = new File(snapshotDirectory.getParent(), "archives"); if (!targetZipDirectory.exists()) { boolean success = targetZipDirectory.mkdirs(); if (success == false) { logger.error("Objects copied to hdfs. But able to create archive directory <" + targetZipDirectory.getAbsolutePath() + ">. Fix the problem and redo extract."); System.exit(1); } } targetZip = new File(targetZipDirectory, snapshotDirectory.getName() + ".zip").getAbsolutePath(); ActionUtils.zipFullDirectory(snapshotDirectory.getAbsolutePath(), targetZip); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects copied to hdfs. But zipping of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to <" + targetZip + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //orderDAO.findAll(new Timestamp(lastRefreshTime), orderJsonFileConsumer); Configuration updateRefreshTimeConf = new Configuration(customerName, "last-refresh-time", String.valueOf(currentTime)); configurationDAO.update(updateRefreshTimeConf, String.valueOf(lastRefreshTimeConf.getValue())); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.complete", true); }
From source file:net.chrislongo.hls.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {//from ww w .j a v a 2s .co m String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:com.google.endpoints.examples.bookstore.BookstoreServer.java
public static void main(String[] args) throws Exception { Options options = createOptions();//from w ww . j a v a2s . c o m CommandLineParser parser = new DefaultParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Invalid command line: " + e.getMessage()); printUsage(options); return; } int port = DEFAULT_PORT; if (line.hasOption("port")) { String portOption = line.getOptionValue("port"); try { port = Integer.parseInt(portOption); } catch (java.lang.NumberFormatException e) { System.err.println("Invalid port number: " + portOption); printUsage(options); return; } } final BookstoreData data = initializeBookstoreData(); final BookstoreServer server = new BookstoreServer(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { System.out.println("Shutting down"); server.stop(); } catch (Exception e) { e.printStackTrace(); } } }); server.start(port, data); System.out.format("Bookstore service listening on %d\n", port); server.blockUntilShutdown(); }
From source file:it.iit.genomics.cru.genomics.misc.apps.Vcf2tabApp.java
public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); Option helpOpt = new Option("help", "print this message."); options.addOption(helpOpt);/*from w ww . jav a 2 s . c om*/ Option option1 = new Option("f", "filename", true, "VCF file to load"); option1.setRequired(true); options.addOption(option1); option1 = new Option("o", "outputfile", true, "outputfilene"); option1.setRequired(true); options.addOption(option1); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { // parse the command line arguments cmd = parser.parse(options, args, true); } catch (ParseException exp) { displayUsage("vcf2tab", options); System.exit(1); } if (cmd.hasOption("help")) { displayUsage("vcf2tab", options); System.exit(0); } String filename = cmd.getOptionValue("f"); String outputfilename = cmd.getOptionValue("o"); Vcf2tab loader = new Vcf2tab(); loader.file2tab(filename, outputfilename); //(args[0]); }
From source file:com.salaboy.rolo.hardware.test.HardwareSerialTestCommandServer.java
public static void main(String[] args) throws Exception { Weld weld = new Weld(); WeldContainer container = weld.initialize(); HardwareSerialTestCommandServer roloCommandServer = container.instance() .select(HardwareSerialTestCommandServer.class).get(); // create Options object Options options = new Options(); // add t option options.addOption("t", true, "sensors latency"); options.addOption("ip", true, "host"); options.addOption("port", true, "port"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String sensorLatency = cmd.getOptionValue("t"); if (sensorLatency == null) { System.out.println(" The Default Latency will be used: " + defaultLatency); } else {/* w w w . j av a 2s . c om*/ System.out.println(" The Latency will be set to: " + sensorLatency); defaultLatency = new Long(sensorLatency); } String ip = cmd.getOptionValue("ip"); if (ip == null) { System.out.println(" The Default IP will be used: 127.0.0.1"); roloCommandServer.setHost("127.0.0.1"); } else { System.out.println(" The IP will be set to: " + ip); roloCommandServer.setHost(ip); } String port = cmd.getOptionValue("port"); if (port == null) { System.out.println(" The Default Port will be used: 5445"); roloCommandServer.setPort(5445); } else { System.out.println(" The Port will be set to: " + port); roloCommandServer.setPort(Integer.parseInt(port)); } System.out.println("Starting Rolo ..."); Thread thread = new Thread(roloCommandServer); thread.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutdown Hook is running !"); } }); }
From source file:de.dominicscheurer.passwords.Main.java
/** * @param args/*from ww w. j av a 2s. c o m*/ * Command line arguments (see code or output of program when * started with no arguments). */ @SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); Option seedPwdOpt = OptionBuilder.withArgName("Seed Password").isRequired().hasArg() .withDescription("Password used as a seed").withLongOpt("seed-password").create("s"); Option serviceIdOpt = OptionBuilder.withArgName("Service Identifier").isRequired().hasArg() .withDescription("The service that the password is created for, e.g. facebook.com") .withLongOpt("service-identifier").create("i"); Option pwdLengthOpt = OptionBuilder.withArgName("Password Length").withType(Integer.class).hasArg() .withDescription("Length of the password in characters").withLongOpt("pwd-length").create("l"); Option specialChars = OptionBuilder.withArgName("With special chars (TRUE|false)").withType(Boolean.class) .hasArg().withDescription("Set to true if special chars !-_?=@/+* are desired, else false") .withLongOpt("special-chars").create("c"); Option suppressPwdOutpOpt = OptionBuilder .withDescription("Suppress password output (copy to clipboard only)").withLongOpt("hide-password") .hasArg(false).create("x"); Option helpOpt = OptionBuilder.withDescription("Prints this help message").withLongOpt("help").create("h"); options.addOption(seedPwdOpt); options.addOption(serviceIdOpt); options.addOption(pwdLengthOpt); options.addOption(specialChars); options.addOption(suppressPwdOutpOpt); options.addOption(helpOpt); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { SafePwdGen.printHelp(options); System.exit(0); } int pwdLength = STD_PWD_LENGTH; if (cmd.hasOption("l")) { pwdLength = new Integer(cmd.getOptionValue("l")); } boolean useSpecialChars = true; if (cmd.hasOption("c")) { useSpecialChars = new Boolean(cmd.getOptionValue("c")); } if (pwdLength > MAX_PWD_LENGTH_64 && !useSpecialChars) { System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_64); } if (pwdLength > MAX_PWD_LENGTH_71 && useSpecialChars) { System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_71); } boolean suppressPwdOutput = cmd.hasOption('x'); String pwd = SafePwdGen.createPwd(cmd.getOptionValue("s"), cmd.getOptionValue("i"), pwdLength, useSpecialChars); if (!suppressPwdOutput) { System.out.print(GENERATED_PASSWORD); System.out.println(pwd); } System.out.println(CLIPBOARD_COPIED_MSG); SystemClipboardInterface.copy(pwd); System.in.read(); } catch (ParseException e) { System.out.println(e.getLocalizedMessage()); SafePwdGen.printHelp(options); } catch (UnsupportedEncodingException e) { System.out.println(e.getLocalizedMessage()); } catch (NoSuchAlgorithmException e) { System.out.println(e.getLocalizedMessage()); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } }
From source file:com.novadart.silencedetect.SilenceDetect.java
public static void main(String[] args) { // create the parser CommandLineParser parser = new BasicParser(); try {// ww w. j a v a 2 s.c om // parse the command line arguments CommandLine line = parser.parse(OPTIONS, args); if (line.hasOption("h")) { printHelp(); } else { String decibels = "-10"; if (line.hasOption("b")) { decibels = "-" + line.getOptionValue("b"); } else { throw new RuntimeException(); } String videoFile = null; if (line.hasOption("i")) { videoFile = line.getOptionValue("i"); Boolean debug = line.hasOption("d"); if (line.hasOption("t")) { System.out.println(printAudioTracksList(videoFile, debug)); } else if (line.hasOption("s")) { int trackNumber = Integer.parseInt(line.getOptionValue("s")); System.out.println(printAudioTrackSilenceDuration(videoFile, trackNumber, decibels, debug)); } else { printHelp(); } } else if (line.hasOption("-j")) { // choose file final JFileChooser fc = new JFileChooser(); fc.setVisible(true); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { videoFile = fc.getSelectedFile().getAbsolutePath(); } else { return; } JTextArea tracks = new JTextArea(); tracks.setText(printAudioTracksList(videoFile, true)); JSpinner trackNumber = new JSpinner(); trackNumber.setValue(1); final JComponent[] inputs = new JComponent[] { new JLabel("Audio Tracks"), tracks, new JLabel("Track to analyze"), trackNumber }; JOptionPane.showMessageDialog(null, inputs, "Select Audio Track", JOptionPane.PLAIN_MESSAGE); JTextArea results = new JTextArea(); results.setText(printAudioTrackSilenceDuration(videoFile, (int) trackNumber.getValue(), decibels, false)); final JComponent[] resultsInputs = new JComponent[] { new JLabel("Results"), results }; JOptionPane.showMessageDialog(null, resultsInputs, "RESULTS!", JOptionPane.PLAIN_MESSAGE); } else { printHelp(); return; } } } catch (ParseException | IOException | InterruptedException exp) { // oops, something went wrong System.out.println("There was a problem :(\nReason: " + exp.getMessage()); } }