List of usage examples for org.apache.commons.cli CommandLine getOptionValue
public String getOptionValue(char opt)
From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java
public static void main(String[] args) throws MalformedURLException, IOException { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); String domainName = cmd.getOptionValue("domain"); String serviceName = cmd.getOptionValue("service"); String privateKeyPath = cmd.getOptionValue("pkey"); String keyId = cmd.getOptionValue("keyid"); String url = cmd.getOptionValue("url"); // we need to generate our principal credentials (ntoken). In // addition to the domain and service names, we need the // the service's private key and the key identifier - the // service with the corresponding public key must already be // registered in ZMS PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath)); ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName, privateKey, keyId);/*from w w w. j av a2 s .c o m*/ Principal principal = identityProvider.getIdentity(domainName, serviceName); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // set our Athenz credentials. The authority in the principal provides // the header name that we must use for credentials while the principal // itself provides the credentials (ntoken). con.setRequestProperty(principal.getAuthority().getHeader(), principal.getCredentials()); // now process our request int responseCode = con.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_FORBIDDEN: System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: System.out.println("Successful response: "); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } break; default: System.out.println("Request failed - response status code: " + responseCode); } }
From source file:com.alibaba.rocketmq.example.operation.Producer.java
public static void main(String[] args) throws MQClientException, InterruptedException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String tags = commandLine.getOptionValue('a'); String keys = commandLine.getOptionValue('k'); String msgCount = commandLine.getOptionValue('c'); DefaultMQProducer producer = new DefaultMQProducer(group); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.start();/*from w w w .ja v a 2 s . c o m*/ for (int i = 0; i < Integer.parseInt(msgCount); i++) { try { Message msg = new Message(// topic, // topic tags, // tag keys, // key ("Hello RocketMQ " + i).getBytes());// body SendResult sendResult = producer.send(msg); System.out.printf("%-8d %s\n", i, sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } }
From source file:com.ict.dtube.example.operation.Producer.java
public static void main(String[] args) throws MQClientException, InterruptedException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String tags = commandLine.getOptionValue('a'); String keys = commandLine.getOptionValue('k'); String msgCount = commandLine.getOptionValue('c'); DtubeProducer producer = new DtubeProducer(group); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.start();//ww w . j ava2s . c om for (int i = 0; i < Integer.parseInt(msgCount); i++) { try { Message msg = new Message(// topic, // topic tags, // tag keys, // key ("Hello Dtube " + i).getBytes());// body SendResult sendResult = producer.send(msg); System.out.printf("%-8d %s\n", i, sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } }
From source file:com.incapture.rapgen.persistence.GenPersistence.java
public static void main(String[] args) { Options options = new Options(); options.addOption("o", true, "Output root folder for kernel files"); options.addOption("g", true, "The type of grammar to generate, current options are 'SDK' or 'API'"); options.addOption("mainApiFile", true, "FileName specifying the api"); CommandLineParser cparser = new PosixParser(); try {/*from w ww.ja v a 2 s. co m*/ CommandLine cmd = cparser.parse(options, args); String mainApiFile = cmd.getOptionValue("mainApiFile"); String outputFolder = cmd.getOptionValue('o'); GenType genType = GenType.valueOf(cmd.getOptionValue('g')); StringTemplateGroup templateLib = loadTemplates(genType); List<StorableAttributes> storableAttributes = parseApiFiles(cmd, mainApiFile, templateLib, genType); StorableSerDeserRepo mappersRepo = StorableMappersLoader.loadSerDeserHelpers(); log.info(String.format("Got %s storable mapper(s)", mappersRepo.getAll().size())); Generator generator = new Generator(templateLib); Map<String, StringTemplate> pathToTemplate = generator.generatePersistenceFiles(storableAttributes, mappersRepo); log.info(String.format("Writing persistence files in [%s]", outputFolder)); OutputWriter.writeTemplates(outputFolder, pathToTemplate); } catch (ParseException e) { System.err.println("Error parsing command line - " + e.getMessage()); System.out.println("Usage: " + options.toString()); } catch (IOException | RecognitionException e) { System.err.println("Error running GenApi: " + ExceptionToString.format(e)); } }
From source file:com.mebigfatguy.roomstore.RoomStore.java
public static void main(String[] args) { Options options = createOptions();// www . j av a2 s. c o m try { CommandLineParser parser = new GnuParser(); CommandLine cmdLine = parser.parse(options, args); String nickname = cmdLine.getOptionValue(NICK_NAME); String server = cmdLine.getOptionValue(IRCSERVER); String[] channels = cmdLine.getOptionValues(CHANNELS); String[] endPoints = cmdLine.getOptionValues(ENDPOINTS); String rf = cmdLine.getOptionValue(RF); if ((endPoints == null) || (endPoints.length == 0)) { endPoints = new String[] { "127.0.0.1" }; } int replicationFactor; try { replicationFactor = Integer.parseInt(rf); } catch (Exception e) { replicationFactor = 1; } final IRCConnector connector = new IRCConnector(nickname, server, channels); Cluster cluster = new Cluster.Builder().addContactPoints(endPoints).build(); final Session session = cluster.connect(); CassandraWriter writer = new CassandraWriter(session, replicationFactor); connector.setWriter(writer); connector.startRecording(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { connector.stopRecording(); session.close(); } })); } catch (ParseException pe) { System.out.println("Parse Error on command line options:"); System.out.println(commandLineRepresentation(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("roomstore", options); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.adobe.aem.demomachine.Checksums.java
public static void main(String[] args) { String rootFolder = null;/*from ww w .jav a2 s. co m*/ // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { rootFolder = cmd.getOptionValue("f"); } } catch (Exception e) { System.exit(-1); } Properties md5properties = new Properties(); List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths); for (String[] path : listPaths) { if (path.length == 5) { logger.debug(path[1]); File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : "")); if (pathFolder.exists()) { String md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false); logger.debug("MD5 is: " + md5); md5properties.setProperty("demo.path." + path[0], path[1]); md5properties.setProperty("demo.md5." + path[0], md5); } else { logger.error("Folder cannot be found"); } } } File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties"); try { @SuppressWarnings("serial") Properties tmpProperties = new Properties() { @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<Object>(super.keySet())); } }; tmpProperties.putAll(md5properties); tmpProperties.store(new FileOutputStream(md5), null); } catch (Exception e) { logger.error(e.getMessage()); } System.out.println("MD5 checkums generated"); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input model"); inputOpt.setArgs(1);//from w w w. java 2 s . c om inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI uri = URI.createFileURI(commandLine.getOptionValue(IN)); Class<?> inClazz = XmiTraverser.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); resource.load(loadOpts); LOG.log(Level.INFO, "Start counting"); int count = 0; long begin = System.currentTimeMillis(); for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator .next(), count++) ; long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End counting"); LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count)); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); resource.unload(); } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:com.alibaba.rocketmq.example.operation.Consumer.java
public static void main(String[] args) throws InterruptedException, MQClientException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String subscription = commandLine.getOptionValue('s'); final String returnFailedHalf = commandLine.getOptionValue('f'); DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group); consumer.setInstanceName(Long.toString(System.currentTimeMillis())); consumer.subscribe(topic, subscription); consumer.registerMessageListener(new MessageListenerConcurrently() { AtomicLong consumeTimes = new AtomicLong(0); @Override/* w w w .j a v a 2 s . c om*/ public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { long currentTimes = this.consumeTimes.incrementAndGet(); System.out.printf("%-8d %s\n", currentTimes, msgs); if (Boolean.parseBoolean(returnFailedHalf)) { if ((currentTimes % 2) == 0) { return ConsumeConcurrentlyStatus.RECONSUME_LATER; } } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.println("Consumer Started."); } }
From source file:com.ict.dtube.example.operation.Consumer.java
public static void main(String[] args) throws InterruptedException, MQClientException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String subscription = commandLine.getOptionValue('s'); final String returnFailedHalf = commandLine.getOptionValue('f'); DtubePushConsumer consumer = new DtubePushConsumer(group); consumer.setInstanceName(Long.toString(System.currentTimeMillis())); consumer.subscribe(topic, subscription); consumer.registerMessageListener(new MessageListenerConcurrently() { AtomicLong consumeTimes = new AtomicLong(0); @Override/*from ww w . j ava2s .c o m*/ public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { long currentTimes = this.consumeTimes.incrementAndGet(); System.out.printf("%-8d %s\n", currentTimes, msgs); if (Boolean.parseBoolean(returnFailedHalf)) { if ((currentTimes % 2) == 0) { return ConsumeConcurrentlyStatus.RECONSUME_LATER; } } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.println("Consumer Started."); } }
From source file:com.kylinolap.query.QueryCli.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OPTION_METADATA);/*from w w w .j a va2 s . com*/ options.addOption(OPTION_SQL); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); KylinConfig config = KylinConfig .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt())); String sql = commandLine.getOptionValue(OPTION_SQL.getOpt()); Class.forName("net.hydromatic.optiq.jdbc.Driver"); File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath()); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); int n = 0; ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { n++; for (int i = 1; i <= meta.getColumnCount(); i++) { System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i)); } } } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }