List of usage examples for org.apache.commons.cli CommandLine getParsedOptionValue
public Object getParsedOptionValue(String opt) throws ParseException
Option
converted to a particular type. From source file:jetbrains.exodus.console.Console.java
public static void main(String[] args) throws IOException, ParseException { CommandLine line = getCommandLine(args); Long port = (Long) line.getParsedOptionValue("l"); port = port == null ? 2222 : port;/*from www .ja v a 2 s. co m*/ String password = line.getOptionValue('p', null); Map<String, Object> config = new HashMap<>(); config.put("location", line.getOptionValue('x', null)); new RhinoServer(port.intValue(), password, config); }
From source file:au.id.hazelwood.xmltvguidebuilder.runner.Main.java
public static void main(String[] args) throws Exception { SLF4JBridgeHandler.install();/*from w w w . jav a2 s . c o m*/ Options options = new Options(); options.addOption(createOptionWithArg("config", true, "file", File.class, "Config file location")); options.addOption(createOptionWithArg("out", true, "file", File.class, "Output file name")); try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); App app = new App(); app.run((File) line.getParsedOptionValue("config"), (File) line.getParsedOptionValue("out")); } catch (ParseException exp) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Main", options, true); } }
From source file:com.pinterest.secor.main.TestLogMessageProducerMain.java
public static void main(String[] args) { try {//from w w w.j a va 2 s. c o m CommandLine commandLine = parseArgs(args); String topic = commandLine.getOptionValue("topic"); int messages = ((Number) commandLine.getParsedOptionValue("messages")).intValue(); int producers = ((Number) commandLine.getParsedOptionValue("producers")).intValue(); String broker = commandLine.getOptionValue("broker"); String type = commandLine.getOptionValue("type"); Number timeshiftNumber = ((Number) commandLine.getParsedOptionValue("timeshift")); int timeshift = timeshiftNumber == null ? 0 : timeshiftNumber.intValue(); for (int i = 0; i < producers; ++i) { TestLogMessageProducer producer = new TestLogMessageProducer(topic, messages, type, broker, timeshift); producer.start(); } } catch (Throwable t) { LOG.error("Log message producer failed", t); System.exit(1); } }
From source file:com.pinterest.secor.main.ZookeeperClientMain.java
public static void main(String[] args) { try {/*w w w . j a va2 s. c o m*/ CommandLine commandLine = parseArgs(args); String command = commandLine.getOptionValue("command"); if (!command.equals("delete_committed_offsets")) { throw new IllegalArgumentException("command has to be one of \"delete_committed_offsets\""); } SecorConfig config = SecorConfig.load(); ZookeeperConnector zookeeperConnector = new ZookeeperConnector(config); String topic = commandLine.getOptionValue("topic"); if (commandLine.hasOption("partition")) { int partition = ((Number) commandLine.getParsedOptionValue("partition")).intValue(); TopicPartition topicPartition = new TopicPartition(topic, partition); zookeeperConnector.deleteCommittedOffsetPartitionCount(topicPartition); } else { zookeeperConnector.deleteCommittedOffsetTopicCount(topic); } } catch (Throwable t) { LOG.error("Zookeeper client failed", t); System.exit(1); } }
From source file:com.pinterest.secor.main.LogFileVerifierMain.java
public static void main(String[] args) { try {//from w ww . ja v a 2 s. c o m CommandLine commandLine = parseArgs(args); SecorConfig config = SecorConfig.load(); FileUtil.configure(config); LogFileVerifier verifier = new LogFileVerifier(config, commandLine.getOptionValue("topic")); long startOffset = -2; long endOffset = Long.MAX_VALUE; if (commandLine.hasOption("start_offset")) { startOffset = Long.parseLong(commandLine.getOptionValue("start_offset")); if (commandLine.hasOption("end_offset")) { endOffset = Long.parseLong(commandLine.getOptionValue("end_offset")); } } int numMessages = -1; if (commandLine.hasOption("messages")) { numMessages = ((Number) commandLine.getParsedOptionValue("messages")).intValue(); } verifier.verifyCounts(startOffset, endOffset, numMessages); if (commandLine.hasOption("sequence_offsets")) { verifier.verifySequences(startOffset, endOffset); } System.out.println("verification succeeded"); } catch (Throwable t) { LOG.error("Log file verifier failed", t); System.exit(1); } }
From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java
public static void main(String[] args) throws GenerationException, IOException { ResourceSetImpl resourceSet = new ResourceSetImpl(); { // initializing the registry resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX, new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME, NeoEMFResourceFactory.eINSTANCE); }// ww w .j av a 2s .c om Options options = new Options(); configureOptions(options); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS); LOGGER.info("Start loading the package"); Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class); EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null); Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy")); metamodelResource.getContents().add(_package); LOGGER.info("Finish loading the package"); int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE; if (commandLine.hasOption(SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(SIZE); size = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } float variation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION, number.floatValue())); } variation = number.floatValue(); } float propVariation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(PROP_VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", PROP_VARIATION, number.floatValue())); } propVariation = number.floatValue(); } long seed = System.currentTimeMillis(); if (commandLine.hasOption(SEED)) { seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); } Range<Integer> range = Range.between(Math.round(size * (1 - variation)), Math.round(size * (1 + variation))); GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed); GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config); if (commandLine.hasOption(OUTPUT_PATH)) { String outDir = commandLine.getOptionValue(OUTPUT_PATH); //java.net.URI intermediateURI = java.net.URI.create(outDir); modelGen.setSamplesPath(outDir); } int numberOfModels = 1; if (commandLine.hasOption(N_MODELS)) { numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); } int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE); valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(DEGREE); referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } config.setValuesRange(Math.round(valuesSize * (1 - propVariation)), Math.round(valuesSize * (1 + propVariation))); config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); long start = System.currentTimeMillis(); modelGen.runGeneration(resourceSet, numberOfModels, size, variation); long end = System.currentTimeMillis(); LOGGER.info( MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000))); if (commandLine.hasOption(DIAGNOSE)) { for (Resource resource : resourceSet.getResources()) { LOGGER.info( MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI())); BasicDiagnostic diagnosticChain = diagnoseResource(resource); if (!isFailed(diagnosticChain)) { LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''", resource.getURI())); } else { LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''", diagnosticChain.getChildren().size(), resource.getURI())); for (Diagnostic diagnostic : diagnosticChain.getChildren()) { LOGGER.fine(diagnostic.getMessage()); } } } LOGGER.info("Validation finished"); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80)); } catch (Throwable t) { LOGGER.warning("Unable to get console information"); } ; formatter.printHelp("java -jar <this-file.jar>", options, true); System.exit(ERROR); } catch (ClassNotFoundException t) { System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(stringWriter.toString()); } catch (Throwable t) { System.err.println("ERROR: " + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(t); LOGGER.severe(stringWriter.toString()); System.exit(ERROR); } }
From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java
public static void main(String[] args) throws GenerationException, IOException { ResourceSetImpl resourceSet = new ResourceSetImpl(); { // initializing the registry resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX, new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME, NeoEMFResourceFactory.eINSTANCE); }/*from w ww. j a v a 2 s . c o m*/ Options options = new Options(); configureOptions(options); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); // String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS); // // LOGGER.info("Start loading the package"); // Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class); // EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null); // // Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy")); // metamodelResource.getContents().add(_package); // LOGGER.info("Finish loading the package"); int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE; if (commandLine.hasOption(SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(SIZE); size = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } float variation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION, number.floatValue())); } variation = number.floatValue(); } float propVariation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(PROP_VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", PROP_VARIATION, number.floatValue())); } propVariation = number.floatValue(); } long seed = System.currentTimeMillis(); if (commandLine.hasOption(SEED)) { seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); } Range<Integer> range = Range.between(Math.round(size * (1 - variation)), Math.round(size * (1 + variation))); ISpecimenConfiguration config = new DagMetamodelConfig(range, seed); IGenerator generator = new DagGenerator(config, config.getSeed()); GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator); if (commandLine.hasOption(OUTPUT_PATH)) { String outDir = commandLine.getOptionValue(OUTPUT_PATH); //java.net.URI intermediateURI = java.net.URI.create(outDir); modelGen.setSamplesPath(outDir); } int numberOfModels = 1; if (commandLine.hasOption(N_MODELS)) { numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); } int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE); valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE; if (commandLine.hasOption(DEGREE)) { Number number = (Number) commandLine.getParsedOptionValue(DEGREE); referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } config.setValuesRange(Math.round(valuesSize * (1 - propVariation)), Math.round(valuesSize * (1 + propVariation))); config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); long start = System.currentTimeMillis(); modelGen.runGeneration(resourceSet, numberOfModels, size, variation); long end = System.currentTimeMillis(); LOGGER.info( MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000))); // for (Resource rsc : resourceSet.getResources()) { // if (rsc.getContents().get(0) instanceof DAG) { // // } // // } if (commandLine.hasOption(DIAGNOSE)) { for (Resource resource : resourceSet.getResources()) { LOGGER.info( MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI())); BasicDiagnostic diagnosticChain = diagnoseResource(resource); if (!isFailed(diagnosticChain)) { LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''", resource.getURI())); } else { LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''", diagnosticChain.getChildren().size(), resource.getURI())); for (Diagnostic diagnostic : diagnosticChain.getChildren()) { LOGGER.fine(diagnostic.getMessage()); } } } LOGGER.info("Validation finished"); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80)); } catch (Throwable t) { LOGGER.warning("Unable to get console information"); } ; formatter.printHelp("java -jar <this-file.jar>", options, true); System.exit(ERROR); } catch (Throwable t) { System.err.println("ERROR: " + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(t); LOGGER.severe(stringWriter.toString()); System.exit(ERROR); } }
From source file:fr.inria.atlanmod.instantiator.SpecimenGenerator.java
public static void main(String[] args) throws GenerationException, IOException { Options options = new Options(); configureOptions(options);/*from ww w . j av a2s. com*/ CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); String metamodel = commandLine.getOptionValue(METAMODEL); DefaultModelGenerator modelGen = new DefaultModelGenerator(URI.createFileURI(metamodel)); if (commandLine.hasOption(ADDITIONAL_METAMODEL)) { for (String additionalMetamodel : commandLine.getOptionValues(ADDITIONAL_METAMODEL)) { URI additionalMetamodelUri = URI.createFileURI(additionalMetamodel); Resource resource = new XMIResourceImpl(additionalMetamodelUri); resource.load(Collections.emptyMap()); registerPackages(resource); } } if (commandLine.hasOption(OUTPUT_DIR)) { String outDir = commandLine.getOptionValue(OUTPUT_DIR); modelGen.setSamplesPath(Paths.get(outDir)); } else { modelGen.setSamplesPath(Paths.get(".")); } if (commandLine.hasOption(N_MODELS)) { int models = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); modelGen.setSetSize(new int[] { models }); } else { modelGen.setSetSize(new int[] { 1 }); } if (commandLine.hasOption(SIZE)) { long size = ((Number) commandLine.getParsedOptionValue(SIZE)).longValue(); modelGen.setModelsSize(new long[] { size }); } else { modelGen.setModelsSize(new long[] { 1000 }); } if (commandLine.hasOption(SEED)) { long seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); modelGen.setSeed(seed); } else { modelGen.setSeed(System.currentTimeMillis()); } modelGen.runGeneration(); } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(TerminalFactory.get().getWidth(), 80)); } catch (Throwable t) { // Nothing to do... } ; formatter.printHelp("java -jar <this-file.jar>", options, true); } }
From source file:lanchon.dexpatcher.Parser.java
public static Configuration parseCommandLine(String[] args) throws ParseException { Configuration config = new Configuration(); Options options = getOptions();/* w w w . ja v a 2 s .c o m*/ CommandLine cl = new PosixParser().parse(options, args); if (cl.hasOption("help")) { printUsage(); return null; } if (cl.hasOption("version")) { System.out.println(Main.getVersion()); return null; } @SuppressWarnings("unchecked") List<String> files = cl.getArgList(); if (files.isEmpty()) throw new ParseException("Missing argument: <source-dex-apk-or-dir>"); config.sourceFile = files.remove(0); config.patchFiles = files; config.patchedFile = cl.getOptionValue("output"); Number apiLevel = (Number) cl.getParsedOptionValue("api-level"); if (apiLevel != null) config.apiLevel = apiLevel.intValue(); config.multiDex = cl.hasOption("multi-dex"); if (cl.hasOption("multi-dex-threaded")) { config.multiDex = true; config.multiDexJobs = 0; } Number multiDexJobs = (Number) cl.getParsedOptionValue("multi-dex-jobs"); if (multiDexJobs != null) { config.multiDex = true; config.multiDexJobs = multiDexJobs.intValue(); } Number maxDexPoolSize = (Number) cl.getParsedOptionValue("max-dex-pool-size"); if (maxDexPoolSize != null) config.maxDexPoolSize = maxDexPoolSize.intValue(); config.annotationPackage = cl.getOptionValue("annotations", Context.DEFAULT_ANNOTATION_PACKAGE); config.dexTagSupported = cl.hasOption("compat-dextag"); config.logLevel = WARN; if (cl.hasOption("quiet")) config.logLevel = ERROR; if (cl.hasOption("verbose")) config.logLevel = INFO; if (cl.hasOption("debug")) config.logLevel = DEBUG; if (cl.hasOption("path")) config.sourceCodeRoot = ""; config.sourceCodeRoot = cl.getOptionValue("path-root", config.sourceCodeRoot); config.timingStats = cl.hasOption("stats"); config.dryRun = cl.hasOption("dry-run"); return config; }
From source file:com.google.cloud.iot.examples.HttpExampleOptions.java
/** Construct an HttpExampleOptions class from command line flags. */ public static HttpExampleOptions fromFlags(String[] args) { Options options = new Options(); // Required arguments options.addOption(Option.builder().type(String.class).longOpt("project_id").hasArg() .desc("GCP cloud project name.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("registry_id").hasArg() .desc("Cloud IoT Core registry id.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("device_id").hasArg() .desc("Cloud IoT Core device id.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("private_key_file").hasArg() .desc("Path to private key file.").required().build()); options.addOption(Option.builder().type(String.class).longOpt("algorithm").hasArg() .desc("Encryption algorithm to use to generate the JWT. Either 'RS256' or 'ES256'.").required() .build());/*from w w w . ja v a 2 s.co m*/ // Optional arguments. options.addOption(Option.builder().type(String.class).longOpt("cloud_region").hasArg() .desc("GCP cloud region.").build()); options.addOption(Option.builder().type(Number.class).longOpt("num_messages").hasArg() .desc("Number of messages to publish.").build()); options.addOption(Option.builder().type(Number.class).longOpt("token_exp_minutes").hasArg() .desc("Minutes to JWT token refresh (token expiration time).").build()); options.addOption(Option.builder().type(String.class).longOpt("http_bridge_address").hasArg() .desc("HTTP bridge address.").build()); options.addOption(Option.builder().type(String.class).longOpt("api_version").hasArg() .desc("The version to use of the API.").build()); options.addOption(Option.builder().type(String.class).longOpt("message_type").hasArg() .desc("Indicates whether message is a telemetry event or a device state message").build()); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); HttpExampleOptions res = new HttpExampleOptions(); res.projectId = commandLine.getOptionValue("project_id"); res.registryId = commandLine.getOptionValue("registry_id"); res.deviceId = commandLine.getOptionValue("device_id"); res.privateKeyFile = commandLine.getOptionValue("private_key_file"); res.algorithm = commandLine.getOptionValue("algorithm"); if (commandLine.hasOption("cloud_region")) { res.cloudRegion = commandLine.getOptionValue("cloud_region"); } if (commandLine.hasOption("num_messages")) { res.numMessages = ((Number) commandLine.getParsedOptionValue("num_messages")).intValue(); } if (commandLine.hasOption("token_exp_minutes")) { res.tokenExpMins = ((Number) commandLine.getParsedOptionValue("token_exp_minutes")).intValue(); } if (commandLine.hasOption("http_bridge_address")) { res.httpBridgeAddress = commandLine.getOptionValue("http_bridge_address"); } if (commandLine.hasOption("api_version")) { res.apiVersion = commandLine.getOptionValue("api_version"); } if (commandLine.hasOption("message_type")) { res.messageType = commandLine.getOptionValue("message_type"); } return res; } catch (ParseException e) { System.err.println(e.getMessage()); return null; } }