List of usage examples for org.apache.commons.cli PosixParser PosixParser
PosixParser
From source file:com.flaptor.indextank.storage.IndexesLogServer.java
public static void main(String[] args) throws IOException, InterruptedException { // create the parser CommandLineParser parser = new PosixParser(); int readerPort, managerPort; try {//from w ww . j a v a 2s . c o m // parse the command line arguments CommandLine line = parser.parse(getOptions(), args); if (line.hasOption("help")) { printHelp(getOptions(), null); System.exit(1); return; } String val = null; val = line.getOptionValue("reader_port", null); if (null != val) { readerPort = Integer.valueOf(val); } else { printHelp(getOptions(), "Must specify a server port"); System.exit(1); return; } val = null; val = line.getOptionValue("manager_port", null); if (null != val) { managerPort = Integer.valueOf(val); } else { printHelp(getOptions(), "Must specify a server port"); System.exit(1); return; } } catch (ParseException exp) { printHelp(getOptions(), exp.getMessage()); System.exit(1); return; } new IndexesLogServer(readerPort, managerPort).start(); }
From source file:com.hurence.logisland.util.avro.eventgenerator.DataGenerator.java
public static void main(String[] args) throws IOException, UnknownTypeException { // load and verify the options CommandLineParser parser = new PosixParser(); Options opts = loadOptions();/*from w w w. jav a 2 s . c o m*/ CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (org.apache.commons.cli.ParseException parseEx) { logger.error("Invalid option"); printHelp(opts); return; } // check for necessary options String fileLoc = cmd.getOptionValue("schemaLocation"); if (fileLoc == null) { logger.error("schemaLocation not specified"); printHelp(opts); } //getField string length and check if min is greater than 0 // Generate the record File schemaFile = new File(fileLoc); DataGenerator dataGenerator = new DataGenerator(schemaFile); GenericRecord record = dataGenerator.generateRandomRecord(); if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) { String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME); OutputStream outs = System.out; if (!outname.equals("-")) { outs = new FileOutputStream(outname); } printAvroJson(record, outs); if (!outname.equals("-")) { outs.close(); } } else { DataGenerator.prettyPrint(record); } }
From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java
public static void main(String[] theArgs) { Options options = new Options(); Option option = new Option("R", true, "Text to substiture in the message"); option.setArgs(2);// ww w . ja v a 2 s. c om option.setArgName("text=substitution"); option.setValueSeparator('='); option.setRequired(true); options.addOption(option); option = new Option("p", true, "Number of passes"); option.setValueSeparator('='); option.setRequired(false); options.addOption(option); CommandLine commandLine; int passes; try { commandLine = new PosixParser().parse(options, theArgs); passes = Integer.parseInt(commandLine.getOptionValue("p", "1")); } catch (ParseException e) { HelpFormatter hf = new HelpFormatter(); hf.printHelp( "java -cp hunit-[version]-jar-with-dependencies.jar ca.uhn.hunit.example.MllpHl7v2MessageSwapper {-Rtext=substitution}... [options]", options); return; } Properties substitutions = commandLine.getOptionProperties("R"); new MllpHl7v2MessageSwapper(true, substitutions, passes).run(); }
From source file:edu.nyu.vida.data_polygamy.scalar_function_computation.Aggregation.java
/** * @param args//from w w w. j a v a 2 s . c o m */ @SuppressWarnings({ "deprecation" }) public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { Options options = new Options(); Option forceOption = new Option("f", "force", false, "force the computation of the aggregate functions " + "even if files already exist"); forceOption.setRequired(false); options.addOption(forceOption); Option gOption = new Option("g", "group", true, "set group of datasets for which the aggregate functions" + " will be computed, followed by their temporal and spatial attribute indices"); gOption.setRequired(true); gOption.setArgName("GROUP"); gOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(gOption); Option machineOption = new Option("m", "machine", true, "machine identifier"); machineOption.setRequired(true); machineOption.setArgName("MACHINE"); machineOption.setArgs(1); options.addOption(machineOption); Option nodesOption = new Option("n", "nodes", true, "number of nodes"); nodesOption.setRequired(true); nodesOption.setArgName("NODES"); nodesOption.setArgs(1); options.addOption(nodesOption); Option s3Option = new Option("s3", "s3", false, "data on Amazon S3"); s3Option.setRequired(false); options.addOption(s3Option); Option awsAccessKeyIdOption = new Option("aws_id", "aws-id", true, "aws access key id; " + "this is required if the execution is on aws"); awsAccessKeyIdOption.setRequired(false); awsAccessKeyIdOption.setArgName("AWS-ACCESS-KEY-ID"); awsAccessKeyIdOption.setArgs(1); options.addOption(awsAccessKeyIdOption); Option awsSecretAccessKeyOption = new Option("aws_key", "aws-id", true, "aws secrect access key; " + "this is required if the execution is on aws"); awsSecretAccessKeyOption.setRequired(false); awsSecretAccessKeyOption.setArgName("AWS-SECRET-ACCESS-KEY"); awsSecretAccessKeyOption.setArgs(1); options.addOption(awsSecretAccessKeyOption); Option bucketOption = new Option("b", "s3-bucket", true, "bucket on s3; " + "this is required if the execution is on aws"); bucketOption.setRequired(false); bucketOption.setArgName("S3-BUCKET"); bucketOption.setArgs(1); options.addOption(bucketOption); Option helpOption = new Option("h", "help", false, "display this message"); helpOption.setRequired(false); options.addOption(helpOption); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { formatter.printHelp("hadoop jar data-polygamy.jar " + "edu.nyu.vida.data_polygamy.scalar_function_computation.Aggregation", options, true); System.exit(0); } if (cmd.hasOption("h")) { formatter.printHelp("hadoop jar data-polygamy.jar " + "edu.nyu.vida.data_polygamy.scalar_function_computation.Aggregation", options, true); System.exit(0); } boolean s3 = cmd.hasOption("s3"); String s3bucket = ""; String awsAccessKeyId = ""; String awsSecretAccessKey = ""; if (s3) { if ((!cmd.hasOption("aws_id")) || (!cmd.hasOption("aws_key")) || (!cmd.hasOption("b"))) { System.out.println( "Arguments 'aws_id', 'aws_key', and 'b'" + " are mandatory if execution is on AWS."); formatter.printHelp( "hadoop jar data-polygamy.jar " + "edu.nyu.vida.data_polygamy.scalar_function_computation.Aggregation", options, true); System.exit(0); } s3bucket = cmd.getOptionValue("b"); awsAccessKeyId = cmd.getOptionValue("aws_id"); awsSecretAccessKey = cmd.getOptionValue("aws_key"); } boolean snappyCompression = false; boolean bzip2Compression = false; String machine = cmd.getOptionValue("m"); int nbNodes = Integer.parseInt(cmd.getOptionValue("n")); Configuration s3conf = new Configuration(); if (s3) { s3conf.set("fs.s3.awsAccessKeyId", awsAccessKeyId); s3conf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey); s3conf.set("bucket", s3bucket); } String datasetNames = ""; String datasetIds = ""; String preProcessingDatasets = ""; ArrayList<String> shortDataset = new ArrayList<String>(); ArrayList<String> shortDatasetAggregation = new ArrayList<String>(); HashMap<String, String> datasetTempAtt = new HashMap<String, String>(); HashMap<String, String> datasetSpatialAtt = new HashMap<String, String>(); HashMap<String, String> preProcessingDataset = new HashMap<String, String>(); HashMap<String, String> datasetId = new HashMap<String, String>(); boolean removeExistingFiles = cmd.hasOption("f"); String[] datasetArgs = cmd.getOptionValues("g"); for (int i = 0; i < datasetArgs.length; i += 3) { String dataset = datasetArgs[i]; // getting pre-processing String tempPreProcessing = FrameworkUtils.searchPreProcessing(dataset, s3conf, s3); if (tempPreProcessing == null) { System.out.println("No pre-processing available for " + dataset); continue; } preProcessingDataset.put(dataset, tempPreProcessing); shortDataset.add(dataset); datasetTempAtt.put(dataset, ((datasetArgs[i + 1] == "null") ? null : datasetArgs[i + 1])); datasetSpatialAtt.put(dataset, ((datasetArgs[i + 2] == "null") ? null : datasetArgs[i + 2])); datasetId.put(dataset, null); } if (shortDataset.size() == 0) { System.out.println("No datasets to process."); System.exit(0); } // getting dataset id Path path = null; FileSystem fs = null; if (s3) { path = new Path(s3bucket + FrameworkUtils.datasetsIndexDir); fs = FileSystem.get(path.toUri(), s3conf); } else { fs = FileSystem.get(new Configuration()); path = new Path(fs.getHomeDirectory() + "/" + FrameworkUtils.datasetsIndexDir); } BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path))); String line = br.readLine(); while (line != null) { String[] dt = line.split("\t"); if (datasetId.containsKey(dt[0])) { datasetId.put(dt[0], dt[1]); datasetNames += dt[0] + ","; datasetIds += dt[1] + ","; } line = br.readLine(); } br.close(); if (s3) fs.close(); datasetNames = datasetNames.substring(0, datasetNames.length() - 1); datasetIds = datasetIds.substring(0, datasetIds.length() - 1); Iterator<String> it = shortDataset.iterator(); while (it.hasNext()) { String dataset = it.next(); if (datasetId.get(dataset) == null) { System.out.println("No dataset id for " + dataset); System.exit(0); } } FrameworkUtils.createDir(s3bucket + FrameworkUtils.aggregatesDir, s3conf, s3); // getting smallest resolution HashMap<String, String> tempResMap = new HashMap<String, String>(); HashMap<String, String> spatialResMap = new HashMap<String, String>(); HashMap<String, String> datasetTemporalStrMap = new HashMap<String, String>(); HashMap<String, String> datasetSpatialStrMap = new HashMap<String, String>(); HashSet<String> input = new HashSet<String>(); for (String dataset : shortDataset) { String[] datasetArray = preProcessingDataset.get(dataset).split("-"); String datasetTemporalStr = datasetArray[datasetArray.length - 2]; int datasetTemporal = utils.temporalResolution(datasetTemporalStr); String datasetSpatialStr = datasetArray[datasetArray.length - 1]; int datasetSpatial = utils.spatialResolution(datasetSpatialStr); // finding all possible resolutions String[] temporalResolutions = FrameworkUtils.getAggTempResolutions(datasetTemporal); String[] spatialResolutions = FrameworkUtils.getAggSpatialResolutions(datasetSpatial); String temporalResolution = ""; String spatialResolution = ""; String tempRes = ""; String spatialRes = ""; boolean dataAdded = false; for (int i = 0; i < temporalResolutions.length; i++) { for (int j = 0; j < spatialResolutions.length; j++) { temporalResolution = temporalResolutions[i]; spatialResolution = spatialResolutions[j]; String aggregatesOutputFileName = s3bucket + FrameworkUtils.aggregatesDir + "/" + dataset + "/"; if (removeExistingFiles) { FrameworkUtils.removeFile(aggregatesOutputFileName, s3conf, s3); } if (!FrameworkUtils.fileExists(aggregatesOutputFileName, s3conf, s3)) { dataAdded = true; tempRes += temporalResolution + "-"; spatialRes += spatialResolution + "-"; } } } if (dataAdded) { input.add(s3bucket + FrameworkUtils.preProcessingDir + "/" + preProcessingDataset.get(dataset)); shortDatasetAggregation.add(dataset); tempResMap.put(dataset, tempRes.substring(0, tempRes.length() - 1)); spatialResMap.put(dataset, spatialRes.substring(0, spatialRes.length() - 1)); datasetTemporalStrMap.put(dataset, datasetTemporalStr); datasetSpatialStrMap.put(dataset, datasetSpatialStr); } } if (input.isEmpty()) { System.out.println("All the input datasets have aggregates."); System.out.println("Use -f in the beginning of the command line to force the computation."); System.exit(0); } it = input.iterator(); while (it.hasNext()) { preProcessingDatasets += it.next() + ","; } Job aggJob = null; String aggregatesOutputDir = s3bucket + FrameworkUtils.aggregatesDir + "/tmp/"; String jobName = "aggregates"; FrameworkUtils.removeFile(aggregatesOutputDir, s3conf, s3); Configuration aggConf = new Configuration(); Machine machineConf = new Machine(machine, nbNodes); aggConf.set("dataset-name", datasetNames); aggConf.set("dataset-id", datasetIds); for (int i = 0; i < shortDatasetAggregation.size(); i++) { String dataset = shortDatasetAggregation.get(i); String id = datasetId.get(dataset); aggConf.set("dataset-" + id + "-temporal-resolutions", tempResMap.get(dataset)); aggConf.set("dataset-" + id + "-spatial-resolutions", spatialResMap.get(dataset)); aggConf.set("dataset-" + id + "-temporal-att", datasetTempAtt.get(dataset)); aggConf.set("dataset-" + id + "-spatial-att", datasetSpatialAtt.get(dataset)); aggConf.set("dataset-" + id + "-temporal", datasetTemporalStrMap.get(dataset)); aggConf.set("dataset-" + id + "-spatial", datasetSpatialStrMap.get(dataset)); if (s3) aggConf.set("dataset-" + id, s3bucket + FrameworkUtils.preProcessingDir + "/" + preProcessingDataset.get(dataset)); else aggConf.set("dataset-" + id, FileSystem.get(new Configuration()).getHomeDirectory() + "/" + FrameworkUtils.preProcessingDir + "/" + preProcessingDataset.get(dataset)); } aggConf.set("mapreduce.tasktracker.map.tasks.maximum", String.valueOf(machineConf.getMaximumTasks())); aggConf.set("mapreduce.tasktracker.reduce.tasks.maximum", String.valueOf(machineConf.getMaximumTasks())); aggConf.set("mapreduce.jobtracker.maxtasks.perjob", "-1"); aggConf.set("mapreduce.reduce.shuffle.parallelcopies", "20"); aggConf.set("mapreduce.input.fileinputformat.split.minsize", "0"); aggConf.set("mapreduce.task.io.sort.mb", "200"); aggConf.set("mapreduce.task.io.sort.factor", "100"); machineConf.setMachineConfiguration(aggConf); if (s3) { machineConf.setMachineConfiguration(aggConf); aggConf.set("fs.s3.awsAccessKeyId", awsAccessKeyId); aggConf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey); } if (snappyCompression) { aggConf.set("mapreduce.map.output.compress", "true"); aggConf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec"); //aggConf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec"); } if (bzip2Compression) { aggConf.set("mapreduce.map.output.compress", "true"); aggConf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec"); //aggConf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec"); } aggJob = new Job(aggConf); aggJob.setJobName(jobName); aggJob.setMapOutputKeyClass(SpatioTemporalWritable.class); aggJob.setMapOutputValueClass(AggregationArrayWritable.class); aggJob.setOutputKeyClass(SpatioTemporalWritable.class); aggJob.setOutputValueClass(FloatArrayWritable.class); //aggJob.setOutputKeyClass(Text.class); //aggJob.setOutputValueClass(Text.class); aggJob.setMapperClass(AggregationMapper.class); aggJob.setCombinerClass(AggregationCombiner.class); aggJob.setReducerClass(AggregationReducer.class); aggJob.setNumReduceTasks(machineConf.getNumberReduces()); aggJob.setInputFormatClass(SequenceFileInputFormat.class); //aggJob.setOutputFormatClass(SequenceFileOutputFormat.class); LazyOutputFormat.setOutputFormatClass(aggJob, SequenceFileOutputFormat.class); //LazyOutputFormat.setOutputFormatClass(aggJob, TextOutputFormat.class); SequenceFileOutputFormat.setCompressOutput(aggJob, true); SequenceFileOutputFormat.setOutputCompressionType(aggJob, CompressionType.BLOCK); FileInputFormat.setInputDirRecursive(aggJob, true); FileInputFormat.setInputPaths(aggJob, preProcessingDatasets.substring(0, preProcessingDatasets.length() - 1)); FileOutputFormat.setOutputPath(aggJob, new Path(aggregatesOutputDir)); aggJob.setJarByClass(Aggregation.class); long start = System.currentTimeMillis(); aggJob.submit(); aggJob.waitForCompletion(true); System.out.println(jobName + "\t" + (System.currentTimeMillis() - start)); // moving files to right place for (String dataset : shortDatasetAggregation) { String from = s3bucket + FrameworkUtils.aggregatesDir + "/tmp/" + dataset + "/"; String to = s3bucket + FrameworkUtils.aggregatesDir + "/" + dataset + "/"; FrameworkUtils.renameFile(from, to, s3conf, s3); } }
From source file:com.hs.mail.deliver.Deliver.java
public static void main(String[] args) { CommandLine cli = null;/* w ww .j ava 2 s. c om*/ try { cli = new PosixParser().parse(OPTS, args); } catch (ParseException e) { usage(); System.exit(EX_USAGE); } // Configuration file path String config = cli.getOptionValue("c", DEFAULT_CONFIG_LOCATION); // Message file path File file = new File(cli.getOptionValue("p")); // Envelope sender address String from = cli.getOptionValue("f"); // Destination mailboxes String[] rcpts = cli.getOptionValues("r"); if (!file.exists()) { // Message file must exist logger.error("File not exist: " + file.getAbsolutePath()); System.exit(EX_TEMPFAIL); } if (from == null || rcpts == null) { // If sender or recipients address was not specified, get the // addresses from the message header. InputStream is = null; try { is = new FileInputStream(file); MessageHeader header = new MessageHeader(is); if (from == null && header.getFrom() != null) { from = header.getFrom().getAddress(); } if (rcpts == null) { rcpts = getRecipients(header); } } catch (IOException ex) { logger.error(ex.getMessage(), ex); System.exit(EX_TEMPFAIL); } finally { IOUtils.closeQuietly(is); } } if (from == null || ArrayUtils.isEmpty(rcpts)) { usage(); System.exit(EX_USAGE); } Deliver deliver = new Deliver(); deliver.init(config); // Spool the incoming message deliver.deliver(from, rcpts, file); System.exit(EX_OK); }
From source file:io.werval.cli.DamnSmallDevShell.java
public static void main(String[] args) { Options options = declareOptions();// www .ja va 2s .c o m CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); // Handle --help if (cmd.hasOption("help")) { PrintWriter out = new PrintWriter(System.out); printHelp(options, out); out.flush(); System.exit(0); } // Handle --version if (cmd.hasOption("version")) { System.out.print(String.format( "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n" + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n" + "OS name: %s, version: %s, arch: %s\n", VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home"), Locale.getDefault().toString(), System.getProperty("file.encoding"), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))); System.out.flush(); System.exit(0); } // Debug final boolean debug = cmd.hasOption('d'); // Temporary directory final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp")); if (debug) { System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'."); } // Handle commands @SuppressWarnings("unchecked") List<String> commands = cmd.getArgList(); if (commands.isEmpty()) { commands = Collections.singletonList("start"); } if (debug) { System.out.println("Commands to be executed: " + commands); } Iterator<String> commandsIterator = commands.iterator(); while (commandsIterator.hasNext()) { String command = commandsIterator.next(); switch (command) { case "new": System.out.println(LOGO); newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd); break; case "clean": cleanCommand(debug, tmpDir); break; case "devshell": System.out.println(LOGO); devshellCommand(debug, tmpDir, cmd); break; case "start": System.out.println(LOGO); startCommand(debug, tmpDir, cmd); break; case "secret": secretCommand(); break; default: PrintWriter out = new PrintWriter(System.err); System.err.println("Unknown command: '" + command + "'"); printHelp(options, out); out.flush(); System.exit(1); break; } } } catch (IllegalArgumentException | ParseException | IOException ex) { PrintWriter out = new PrintWriter(System.err); printHelp(options, out); out.flush(); System.exit(1); } catch (WervalException ex) { ex.printStackTrace(System.err); System.err.flush(); System.exit(1); } }
From source file:com.salaboy.rolo.hardware.test.HardwareTestCommandServer.java
public static void main(String[] args) throws Exception { Weld weld = new Weld(); WeldContainer container = weld.initialize(); HardwareTestCommandServer roloCommandServer = container.instance().select(HardwareTestCommandServer.class) .get();/*from w w w .j a va 2 s . c o m*/ // 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 { 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 !"); readDistanceSensors = false; readLightSensors = false; readTouchSensors = false; } }); }
From source file:eu.scape_project.archiventory.Archiventory.java
/** * Main entry point./*from www . j ava 2 s . c om*/ * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // Command line interface config = new CliConfig(); CommandLineParser cmdParser = new PosixParser(); GenericOptionsParser gop = new GenericOptionsParser(conf, args); CommandLine cmd = cmdParser.parse(Options.OPTIONS, gop.getRemainingArgs()); if ((args.length == 0) || (cmd.hasOption(Options.HELP_OPT))) { Options.exit("Usage", 0); } else { Options.initOptions(cmd, config); } // Trying to load spring configuration from local file system (same // directory where the application is executed). If the spring // configuration is not given as a parameter, it is loaded as a // resource from the class path. if (config.getSpringConfig() != null && (new File(config.getSpringConfig()).exists())) { ctx = new FileSystemXmlApplicationContext("file://" + config.getSpringConfig()); } else { ctx = new ClassPathXmlApplicationContext(SPRING_CONFIG_RESOURCE_PATH); } if (config.isMapReduceJob()) { startHadoopJob(conf); } else { startApplication(); } }
From source file:com.flaptor.indextank.storage.LogWriterServer.java
public static void main(String[] args) throws IOException, InterruptedException { // create the parser CommandLineParser parser = new PosixParser(); int port;/*from ww w . j a v a2s . co m*/ LogWriterServer server; try { // parse the command line arguments CommandLine line = parser.parse(getOptions(), args); if (line.hasOption("help")) { printHelp(getOptions(), null); System.exit(1); return; } String val = null; val = line.getOptionValue("port", null); if (null != val) { port = Integer.valueOf(val); } else { printHelp(getOptions(), "Must specify a server port"); System.exit(1); return; } String path = null; path = line.getOptionValue("path", null); if (null != path) { server = new LogWriterServer(new File(path), port); } else { server = new LogWriterServer(port); } } catch (ParseException exp) { printHelp(getOptions(), exp.getMessage()); System.exit(1); return; } server.start(); }
From source file:com.tvh.gmaildrafter.Drafter.java
/** * @param args the command line arguments *//*from w w w. j a v a 2 s . c om*/ public static void main(String[] args) { Options options = getCMDLineOptions(); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelpMessage(options); System.exit(0); } String emailBody = null; String emailSubject = null; if (cmd.hasOption("body")) { String bodyFile = cmd.getOptionValue("body"); File body = new File(bodyFile); emailBody = FileUtils.readFileToString(body); if (cmd.hasOption("deletebody")) { body.delete(); } } else if (cmd.hasOption("stdin")) { emailBody = Util.readEntireStdin(); } if (cmd.hasOption("subject")) emailSubject = cmd.getOptionValue("subject"); else if (cmd.hasOption("subjectfile")) { String subjectFile = cmd.getOptionValue("subjectfile"); File subject = new File(subjectFile); emailSubject = FileUtils.readFileToString(subject); if (cmd.hasOption("deletesubjectfile")) subject.delete(); } String username = null; if (cmd.hasOption("username")) username = cmd.getOptionValue("username"); String password = null; if (cmd.hasOption("password")) password = cmd.getOptionValue("password"); String[] bcc = cmd.getOptionValues("bcc"); String[] cc = cmd.getOptionValues("cc"); Boolean sendImmediately = cmd.hasOption("immediate"); String[] attachments = cmd.getOptionValues("attachments"); String[] attachmentnames = cmd.getOptionValues("attachmentnames"); String[] destinations = cmd.getOptionValues("to"); Credentials credentials = Authenticater.getValidCredentials(username, password); if (credentials != null) { boolean success = false; while (!success) { try { composeMail(credentials, emailSubject, emailBody, attachments, attachmentnames, destinations, cc, bcc, sendImmediately); success = true; } catch (AuthenticationFailedException e) { JOptionPane.showMessageDialog(null, "Invalid login, please try again!"); credentials = Authenticater.getValidCredentials(username, null); success = false; } } } } catch (ParseException ex) { javax.swing.JOptionPane.showMessageDialog(null, ex.getMessage()); printHelpMessage(options); System.exit(7); } catch (IOException ex) { System.out.println("IO Exception " + ex.getLocalizedMessage()); printHelpMessage(options); System.exit(2); } catch (LoginException ex) { System.out.println(ex.getMessage()); System.exit(3); } System.exit(0); }