List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:ch.psi.zmq.receiver.FileReceiver.java
public static void main(String[] args) { int port = 8888; String source = "localhost"; Options options = new Options(); options.addOption("h", false, "Help"); @SuppressWarnings("static-access") Option optionP = OptionBuilder.withArgName("port").hasArg() .withDescription("Source port (default: " + port + ")").create("p"); options.addOption(optionP);/*from w w w. jav a 2 s . c o m*/ @SuppressWarnings("static-access") Option optionS = OptionBuilder.withArgName("source").hasArg().isRequired().withDescription( "Source address of the ZMQ stream (default port " + port + " : use -p to set the port if needed)") .create("s"); options.addOption(optionS); @SuppressWarnings("static-access") Option optionD = OptionBuilder.withArgName("path").hasArg().isRequired() .withDescription("tpath for storing files with relative destination paths").create("d"); options.addOption(optionD); GnuParser parser = new GnuParser(); CommandLine line; String path = "."; try { line = parser.parse(options, args); if (line.hasOption(optionP.getOpt())) { port = Integer.parseInt(line.getOptionValue(optionP.getOpt())); } if (line.hasOption("h")) { HelpFormatter f = new HelpFormatter(); f.printHelp("receiver", options); return; } source = line.getOptionValue(optionS.getOpt()); path = line.getOptionValue(optionD.getOpt()); } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter f = new HelpFormatter(); f.printHelp("receiver", options); System.exit(-1); } final FileReceiver r = new FileReceiver(source, port, path); r.receive(); // Control+C Signal.handle(new Signal("INT"), new SignalHandler() { int count = 0; public void handle(Signal sig) { if (count < 1) { count++; r.terminate(); } else { System.exit(-1); } } }); }
From source file:com.ibm.crail.tools.CrailFsck.java
public static void main(String[] args) throws Exception { String type = ""; String filename = "/tmp.dat"; long offset = 0; long length = 1; boolean randomize = false; int storageClass = 0; int locationClass = 0; Option typeOption = Option.builder("t").desc( "type of experiment [getLocations|directoryDump|namenodeDump|blockStatistics|ping|createDirectory]") .hasArg().build();/* ww w .j a v a2 s . co m*/ Option fileOption = Option.builder("f").desc("filename").hasArg().build(); Option offsetOption = Option.builder("y").desc("offset into the file").hasArg().build(); Option lengthOption = Option.builder("l").desc("length of the file [bytes]").hasArg().build(); Option storageOption = Option.builder("c").desc("storageClass for file [1..n]").hasArg().build(); Option locationOption = Option.builder("p").desc("locationClass for file [1..n]").hasArg().build(); Options options = new Options(); options.addOption(typeOption); options.addOption(fileOption); options.addOption(offsetOption); options.addOption(lengthOption); options.addOption(storageOption); options.addOption(locationOption); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(typeOption.getOpt())) { type = line.getOptionValue(typeOption.getOpt()); } if (line.hasOption(fileOption.getOpt())) { filename = line.getOptionValue(fileOption.getOpt()); } if (line.hasOption(offsetOption.getOpt())) { offset = Long.parseLong(line.getOptionValue(offsetOption.getOpt())); } if (line.hasOption(lengthOption.getOpt())) { length = Long.parseLong(line.getOptionValue(lengthOption.getOpt())); } if (line.hasOption(storageOption.getOpt())) { storageClass = Integer.parseInt(line.getOptionValue(storageOption.getOpt())); } if (line.hasOption(locationOption.getOpt())) { locationClass = Integer.parseInt(line.getOptionValue(locationOption.getOpt())); } CrailFsck fsck = new CrailFsck(); if (type.equals("getLocations")) { fsck.getLocations(filename, offset, length); } else if (type.equals("directoryDump")) { fsck.directoryDump(filename, randomize); } else if (type.equals("namenodeDump")) { fsck.namenodeDump(); } else if (type.equals("blockStatistics")) { fsck.blockStatistics(filename); } else if (type.equals("ping")) { fsck.ping(); } else if (type.equals("createDirectory")) { fsck.createDirectory(filename, storageClass, locationClass); } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("crail fsck", options); System.exit(-1); } }
From source file:com.example.dlp.DeIdentification.java
/** * Command line application to de-identify data using the Data Loss Prevention API. * Supported data format: strings/*from w w w.ja va 2s . c o m*/ */ public static void main(String[] args) throws Exception { OptionGroup optionsGroup = new OptionGroup(); optionsGroup.setRequired(true); Option deidentifyMaskingOption = new Option("m", "mask", true, "deid with character masking"); optionsGroup.addOption(deidentifyMaskingOption); Option deidentifyFpeOption = new Option("f", "fpe", true, "deid with FFX FPE"); optionsGroup.addOption(deidentifyFpeOption); Options commandLineOptions = new Options(); commandLineOptions.addOptionGroup(optionsGroup); Option maskingCharacterOption = Option.builder("maskingCharacter").hasArg(true).required(false).build(); commandLineOptions.addOption(maskingCharacterOption); Option numberToMaskOption = Option.builder("numberToMask").hasArg(true).required(false).build(); commandLineOptions.addOption(numberToMaskOption); Option alphabetOption = Option.builder("commonAlphabet").hasArg(true).required(false).build(); commandLineOptions.addOption(alphabetOption); Option wrappedKeyOption = Option.builder("wrappedKey").hasArg(true).required(false).build(); commandLineOptions.addOption(wrappedKeyOption); Option keyNameOption = Option.builder("keyName").hasArg(true).required(false).build(); commandLineOptions.addOption(keyNameOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(commandLineOptions, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(DeIdentification.class.getName(), commandLineOptions); System.exit(1); return; } if (cmd.hasOption("m")) { // deidentification with character masking int numberToMask = Integer.parseInt(cmd.getOptionValue(numberToMaskOption.getOpt(), "0")); char maskingCharacter = cmd.getOptionValue(maskingCharacterOption.getOpt(), "*").charAt(0); String val = cmd.getOptionValue(deidentifyMaskingOption.getOpt()); deIdentifyWithMask(val, maskingCharacter, numberToMask); } else if (cmd.hasOption("f")) { // deidentification with FPE String wrappedKey = cmd.getOptionValue(wrappedKeyOption.getOpt()); String keyName = cmd.getOptionValue(keyNameOption.getOpt()); String val = cmd.getOptionValue(deidentifyFpeOption.getOpt()); FfxCommonNativeAlphabet alphabet = FfxCommonNativeAlphabet.valueOf( cmd.getOptionValue(alphabetOption.getOpt(), FfxCommonNativeAlphabet.ALPHA_NUMERIC.name())); deIdentifyWithFpe(val, alphabet, keyName, wrappedKey); } }
From source file:com.gordcorp.jira2db.App.java
public static void main(String[] args) throws Exception { File log4jFile = new File("log4j.xml"); if (log4jFile.exists()) { DOMConfigurator.configure("log4j.xml"); }//from w ww . j a va 2s .com Option help = new Option("h", "help", false, "print this message"); @SuppressWarnings("static-access") Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT") .hasArg().withArgName("PROJECT").create(); @SuppressWarnings("static-access") Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property").create("D"); @SuppressWarnings("static-access") Option testJira = OptionBuilder.withLongOpt("test-jira") .withDescription("Test the connection to Jira and print the results").create(); @SuppressWarnings("static-access") Option forever = OptionBuilder.withLongOpt("forever") .withDescription("Will continue polling Jira and syncing forever").create(); Options options = new Options(); options.addOption(help); options.addOption(project); options.addOption(property); options.addOption(testJira); options.addOption(forever); CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(help.getOpt())) { printHelp(options); return; } // Overwrite the properties file with command line arguments if (line.hasOption("D")) { String[] values = line.getOptionValues("D"); for (int i = 0; i < values.length; i = i + 2) { String key = values[i]; // If user does not provide a value for this property, use // an empty string String value = ""; if (i + 1 < values.length) { value = values[i + 1]; } log.info("Setting key=" + key + " value=" + value); PropertiesWrapper.set(key, value); } } if (line.hasOption("test-jira")) { testJira(); } else { JiraSynchroniser jira = new JiraSynchroniser(); if (line.hasOption("project")) { jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") })); } if (line.hasOption("forever")) { jira.syncForever(); } else { jira.syncAll(); } } } catch (ParseException exp) { log.error("Parsing failed: " + exp.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:de.onyxbits.raccoon.cli.Router.java
public static void main(String[] args) { Options options = new Options(); Option property = Option.builder("D").argName("property=value").numberOfArgs(2).valueSeparator() .desc(Messages.getString(DESC + "D")).build(); options.addOption(property);/*from w w w . j a v a 2 s .c o m*/ Option help = new Option("h", "help", false, Messages.getString(DESC + "h")); options.addOption(help); Option version = new Option("v", "version", false, Messages.getString(DESC + "v")); options.addOption(version); // GPA: Google Play Apps (we might add different markets later) Option playAppDetails = new Option(null, "gpa-details", true, Messages.getString(DESC + "gpa-details")); playAppDetails.setArgName("package"); options.addOption(playAppDetails); Option playAppBulkDetails = new Option(null, "gpa-bulkdetails", true, Messages.getString(DESC + "gpa-bulkdetails")); playAppBulkDetails.setArgName("file"); options.addOption(playAppBulkDetails); Option playAppBatchDetails = new Option(null, "gpa-batchdetails", true, Messages.getString(DESC + "gpa-batchdetails")); playAppBatchDetails.setArgName("file"); options.addOption(playAppBatchDetails); Option playAppSearch = new Option(null, "gpa-search", true, Messages.getString(DESC + "gpa-search")); playAppSearch.setArgName("query"); options.addOption(playAppSearch); CommandLine commandLine = null; try { commandLine = new DefaultParser().parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); } if (commandLine.hasOption(property.getOpt())) { System.getProperties().putAll(commandLine.getOptionProperties(property.getOpt())); } if (commandLine.hasOption(help.getOpt())) { new HelpFormatter().printHelp("raccoon", Messages.getString("header"), options, Messages.getString("footer"), true); System.exit(0); } if (commandLine.hasOption(version.getOpt())) { System.out.println(GlobalsProvider.getGlobals().get(Version.class)); System.exit(0); } if (commandLine.hasOption(playAppDetails.getLongOpt())) { Play.details(commandLine.getOptionValue(playAppDetails.getLongOpt())); System.exit(0); } if (commandLine.hasOption(playAppBulkDetails.getLongOpt())) { Play.bulkDetails(new File(commandLine.getOptionValue(playAppBulkDetails.getLongOpt()))); System.exit(0); } if (commandLine.hasOption(playAppBatchDetails.getLongOpt())) { Play.details(new File(commandLine.getOptionValue(playAppBatchDetails.getLongOpt()))); System.exit(0); } if (commandLine.hasOption(playAppSearch.getLongOpt())) { Play.search(commandLine.getOptionValue(playAppSearch.getLongOpt())); System.exit(0); } }
From source file:com.example.dlp.RiskAnalysis.java
/** * Command line application to perform risk analysis using the Data Loss Prevention API. * Supported data format: BigQuery tables *//*from w w w . ja v a 2 s .co m*/ public static void main(String[] args) throws Exception { OptionGroup optionsGroup = new OptionGroup(); optionsGroup.setRequired(true); Option numericalAnalysisOption = new Option("n", "numerical"); optionsGroup.addOption(numericalAnalysisOption); Option categoricalAnalysisOption = new Option("c", "categorical"); optionsGroup.addOption(categoricalAnalysisOption); Option kanonymityOption = new Option("k", "kAnonymity"); optionsGroup.addOption(kanonymityOption); Option ldiversityOption = new Option("l", "lDiversity"); optionsGroup.addOption(ldiversityOption); Options commandLineOptions = new Options(); commandLineOptions.addOptionGroup(optionsGroup); Option datasetIdOption = Option.builder("datasetId").hasArg(true).required(false).build(); commandLineOptions.addOption(datasetIdOption); Option tableIdOption = Option.builder("tableId").hasArg(true).required(false).build(); commandLineOptions.addOption(tableIdOption); Option projectIdOption = Option.builder("projectId").hasArg(true).required(false).build(); commandLineOptions.addOption(projectIdOption); Option columnNameOption = Option.builder("columnName").hasArg(true).required(false).build(); commandLineOptions.addOption(columnNameOption); Option sensitiveAttributeOption = Option.builder("sensitiveAttribute").hasArg(true).required(false).build(); commandLineOptions.addOption(sensitiveAttributeOption); Option quasiIdColumnNamesOption = Option.builder("quasiIdColumnNames").hasArg(true).required(false).build(); commandLineOptions.addOption(quasiIdColumnNamesOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(commandLineOptions, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(RiskAnalysis.class.getName(), commandLineOptions); System.exit(1); return; } String datasetId = cmd.getOptionValue(datasetIdOption.getOpt()); String tableId = cmd.getOptionValue(tableIdOption.getOpt()); // use default project id when project id is not specified String projectId = cmd.getOptionValue(projectIdOption.getOpt(), ServiceOptions.getDefaultProjectId()); if (cmd.hasOption("n")) { // numerical stats analysis String columnName = cmd.getOptionValue(columnNameOption.getOpt()); calculateNumericalStats(projectId, datasetId, tableId, columnName); } else if (cmd.hasOption("c")) { // categorical stats analysis String columnName = cmd.getOptionValue(columnNameOption.getOpt()); calculateCategoricalStats(projectId, datasetId, tableId, columnName); } else if (cmd.hasOption("k")) { // k-anonymity analysis List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt())); calculateKAnonymity(projectId, datasetId, tableId, quasiIdColumnNames); } else if (cmd.hasOption("l")) { // l-diversity analysis String sensitiveAttribute = cmd.getOptionValue(sensitiveAttributeOption.getOpt()); List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt())); calculateLDiversity(projectId, datasetId, tableId, sensitiveAttribute, quasiIdColumnNames); } }
From source file:com.enioka.jqm.tools.Main.java
/** * Startup method for the packaged JAR// w w w. j a v a2 s .co m * * @param args * 0 is node name */ @SuppressWarnings("static-access") public static void main(String[] args) { Helpers.setLogFileName("cli"); Option o00 = OptionBuilder.withArgName("nodeName").hasArg().withDescription("name of the JQM node to start") .isRequired().create("startnode"); Option o01 = OptionBuilder.withDescription("display help").withLongOpt("help").create("h"); Option o11 = OptionBuilder.withArgName("applicationname").hasArg() .withDescription("name of the application to launch").isRequired().create("enqueue"); Option o21 = OptionBuilder.withArgName("xmlpath").hasArg() .withDescription("path of the XML configuration file to import").isRequired() .create("importjobdef"); Option o31 = OptionBuilder.withArgName("xmlpath").hasArg() .withDescription("export all queue definitions into an XML file").isRequired() .create("exportallqueues"); OptionBuilder.withArgName("xmlpath").hasArg() .withDescription("export some queue definitions into an XML file").isRequired() .create("exportqueuefile"); OptionBuilder.withArgName("queues").hasArg().withDescription("queues to export").withValueSeparator(',') .isRequired().create("queue"); Option o51 = OptionBuilder.withArgName("xmlpath").hasArg() .withDescription("import all queue definitions from an XML file").isRequired() .create("importqueuefile"); Option o61 = OptionBuilder.withArgName("nodeName").hasArg() .withDescription("creates a JQM node of this name, or updates it if it exists. Implies -u.") .isRequired().create("createnode"); Option o71 = OptionBuilder.withDescription("display JQM engine version").withLongOpt("version").create("v"); Option o81 = OptionBuilder.withDescription("upgrade JQM database").withLongOpt("upgrade").create("u"); Option o91 = OptionBuilder.withArgName("jobInstanceId").hasArg() .withDescription("get job instance status by ID").isRequired().withLongOpt("getstatus").create("g"); Option o101 = OptionBuilder.withArgName("password").hasArg() .withDescription("creates or resets root admin account password").isRequired().withLongOpt("root") .create("r"); Option o111 = OptionBuilder.withArgName("option").hasArg() .withDescription( "ws handling. Possible values are: enable, disable, ssl, nossl, internalpki, externalapi") .isRequired().withLongOpt("gui").create("w"); Option o121 = OptionBuilder.withArgName("id[,logfilepath]").hasArg().withDescription("single launch mode") .isRequired().withLongOpt("gui").create("s"); Option o131 = OptionBuilder.withArgName("resourcefile").hasArg() .withDescription("resource parameter file to use. Default is resources.xml") .withLongOpt("resources").create("p"); Option o141 = OptionBuilder.withArgName("login,password,role1,role2,...").hasArgs(Option.UNLIMITED_VALUES) .withValueSeparator(',') .withDescription("Create or update a JQM account. Roles must exist beforehand.").create("U"); Options options = new Options(); OptionGroup og1 = new OptionGroup(); og1.setRequired(true); og1.addOption(o00); og1.addOption(o01); og1.addOption(o11); og1.addOption(o21); og1.addOption(o31); og1.addOption(o51); og1.addOption(o61); og1.addOption(o71); og1.addOption(o81); og1.addOption(o91); og1.addOption(o101); og1.addOption(o111); og1.addOption(o121); og1.addOption(o141); options.addOptionGroup(og1); OptionGroup og2 = new OptionGroup(); og2.addOption(o131); options.addOptionGroup(og2); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(160); try { // Parse arguments CommandLineParser parser = new BasicParser(); CommandLine line = parser.parse(options, args); // Other db connection? if (line.getOptionValue(o131.getOpt()) != null) { jqmlogger.info("Using resource XML file " + line.getOptionValue(o131.getOpt())); Helpers.resourceFile = line.getOptionValue(o131.getOpt()); } // Set db connection Helpers.registerJndiIfNeeded(); // Enqueue if (line.getOptionValue(o11.getOpt()) != null) { enqueue(line.getOptionValue(o11.getOpt())); } // Get status if (line.getOptionValue(o91.getOpt()) != null) { getStatus(Integer.parseInt(line.getOptionValue(o91.getOpt()))); } // Import XML else if (line.getOptionValue(o21.getOpt()) != null) { importJobDef(line.getOptionValue(o21.getOpt())); } // Start engine else if (line.getOptionValue(o00.getOpt()) != null) { startEngine(line.getOptionValue(o00.getOpt())); } // Export all Queues else if (line.getOptionValue(o31.getOpt()) != null) { exportAllQueues(line.getOptionValue(o31.getOpt())); } // Import queues else if (line.getOptionValue(o51.getOpt()) != null) { importQueues(line.getOptionValue(o51.getOpt())); } // Create node else if (line.getOptionValue(o61.getOpt()) != null) { createEngine(line.getOptionValue(o61.getOpt())); } // Upgrade else if (line.hasOption(o81.getOpt())) { upgrade(); } // Help else if (line.hasOption(o01.getOpt())) { formatter.printHelp("java -jar jqm-engine.jar", options, true); } // Version else if (line.hasOption(o71.getOpt())) { jqmlogger.info("Engine version: " + Helpers.getMavenVersion()); } // Root password else if (line.hasOption(o101.getOpt())) { root(line.getOptionValue(o101.getOpt())); } // Web options else if (line.hasOption(o111.getOpt())) { ws(line.getOptionValue(o111.getOpt())); } // Web options else if (line.hasOption(o121.getOpt())) { single(line.getOptionValue(o121.getOpt())); } // User handling else if (line.hasOption(o141.getOpt())) { user(line.getOptionValues(o141.getOpt())); } } catch (ParseException exp) { jqmlogger.fatal("Could not read command line: " + exp.getMessage()); formatter.printHelp("java -jar jqm-engine.jar", options, true); return; } }
From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java
/** * Entry point for the program.// w ww.ja v a2 s . co m * * @param args * arguments from the command line * @throws IOException */ @SuppressWarnings("static-access") public static void main(String[] args) throws IOException { Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg() .withDescription("Specify configuration directory.").create("configDir"); // tempDir option is used by the YARN client. Option tempDir = OptionBuilder.withArgName("temporary directory (overwrites configured option)").hasArg() .withDescription("Specify temporary directory.").create(ARG_CONF_DIR); configDirOpt.setRequired(true); tempDir.setRequired(false); Options options = new Options(); options.addOption(configDirOpt); options.addOption(tempDir); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("CLI Parsing failed. Reason: " + e.getMessage()); System.exit(FAILURE_RETURN_CODE); } String configDir = line.getOptionValue(configDirOpt.getOpt(), null); String tempDirVal = line.getOptionValue(tempDir.getOpt(), null); // First, try to load global configuration GlobalConfiguration.loadConfiguration(configDir); if (tempDirVal != null // the YARN TM runner has set a value for the temp dir // the configuration does not contain a temp direcory && GlobalConfiguration.getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, null) == null) { Configuration c = GlobalConfiguration.getConfiguration(); c.setString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, tempDirVal); LOG.info("Setting temporary directory to " + tempDirVal); GlobalConfiguration.includeConfiguration(c); } System.err.println("Configuration " + GlobalConfiguration.getConfiguration()); LOG.info("Current user " + UserGroupInformation.getCurrentUser().getShortUserName()); { // log the available JVM memory long maxMemoryMiBytes = Runtime.getRuntime().maxMemory() >>> 20; LOG.info("Starting TaskManager in a JVM with " + maxMemoryMiBytes + " MiBytes maximum heap size."); } // Create a new task manager object try { new TaskManager(); } catch (Exception e) { LOG.fatal("Taskmanager startup failed: " + e.getMessage(), e); System.exit(FAILURE_RETURN_CODE); } // park the main thread to keep the JVM alive (all other threads may be daemon threads) Object mon = new Object(); synchronized (mon) { try { mon.wait(); } catch (InterruptedException ex) { } } }
From source file:com.quanticate.opensource.pdftkbox.PDFtkBox.java
public static void main(String[] args) throws Exception { // For printing help Options optsHelp = new Options(); optsHelp.addOption(Option.builder("help").required().desc("print this message").build()); // Normal-style import/export Options optsNormal = new Options(); OptionGroup normal = new OptionGroup(); Option optExport = Option.builder("export").required().hasArg().desc("export bookmarks from pdf") .argName("source-pdf").build(); normal.addOption(optExport);//from w w w .j av a 2 s .c om Option optImport = Option.builder("import").required().hasArg().desc("import bookmarks into pdf") .argName("source-pdf").build(); normal.addOption(optImport); optsNormal.addOptionGroup(normal); Option optBookmarks = Option.builder("bookmarks").hasArg().desc("bookmarks definition file") .argName("bookmarks").build(); optsNormal.addOption(optBookmarks); Option optOutput = Option.builder("output").hasArg().desc("output to new pdf").argName("pdf").build(); optsNormal.addOption(optOutput); // PDFtk style options Options optsPDFtk = new Options(); OptionGroup pdftk = new OptionGroup(); Option optDumpData = Option.builder("dump_data").required().desc("dump bookmarks from pdf").build(); pdftk.addOption(optDumpData); Option optUpdateInfo = Option.builder("update_info").required().hasArg().desc("update bookmarks in pdf") .argName("bookmarks").build(); pdftk.addOption(optUpdateInfo); optsPDFtk.addOptionGroup(pdftk); optsPDFtk.addOption(optOutput); // What are we doing? CommandLineParser parser = new DefaultParser(); // Did they want help? try { parser.parse(optsHelp, args); // If we get here, they asked for help doPrintHelp(optsHelp, optsNormal, optsPDFtk); return; } catch (ParseException pe) { } // Normal-style import/export? try { CommandLine line = parser.parse(optsNormal, args); // Export if (line.hasOption(optExport.getOpt())) { doExport(line.getOptionValue(optExport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), line.getArgs()); return; } // Import with explicit output filename if (line.hasOption(optImport.getOpt()) && line.hasOption(optOutput.getOpt())) { doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), line.getOptionValue(optOutput.getOpt()), null); return; } // Import with implicit output filename if (line.hasOption(optImport.getOpt()) && line.getArgs().length > 0) { doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), null, line.getArgs()); return; } } catch (ParseException pe) { } // PDFtk-style if (args.length > 1) { // Nobble things for PDFtk-style options and Commons CLI for (int i = 1; i < args.length; i++) { for (Option opt : optsPDFtk.getOptions()) { if (args[i].equals(opt.getOpt())) { args[i] = "-" + args[i]; } } } try { // Input file comes first, then arguments String input = args[0]; String[] pargs = new String[args.length - 1]; System.arraycopy(args, 1, pargs, 0, pargs.length); // Parse what's left and check CommandLine line = parser.parse(optsPDFtk, pargs); if (line.hasOption(optDumpData.getOpt())) { doExport(input, line.getOptionValue(optOutput.getOpt()), line.getArgs()); return; } if (line.hasOption(optUpdateInfo.getOpt())) { doImport(input, line.getOptionValue(optUpdateInfo.getOpt()), line.getOptionValue(optOutput.getOpt()), line.getArgs()); return; } } catch (ParseException pe) { } } // If in doubt, print help doPrintHelp(optsHelp, optsNormal, optsPDFtk); }
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {//from ww w .j a v a 2 s. c om Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }