List of usage examples for org.apache.commons.cli ParseException getMessage
public String getMessage()
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args//from www . ja va2s. c o m */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }
From source file:com.github.braully.graph.UtilResultCompare.java
public static void main(String... args) throws Exception { Options options = new Options(); Option input = new Option("i", "input", true, "input file path"); input.setRequired(false);// w ww . ja v a2s. c o m options.addOption(input); Option output = new Option("o", "output", true, "output file"); output.setRequired(false); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("UtilResult", options); System.exit(1); return; } String inputFilePath = cmd.getOptionValue("input"); if (inputFilePath == null) { inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-quartic-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-mft-parcial-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-highlyirregular-ht.txt"; // inputFilePath = "/home/strike/Documentos/grafos-processados/mtf/resultado-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-hypo-parcial-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-eul-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-almhypo-ht.txt"; // inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-Almost_hypohamiltonian_graphs_cubic-parcial-ht.txt"; } if (inputFilePath != null) { if (inputFilePath.toLowerCase().endsWith(".txt")) { processFileTxt(inputFilePath); } else if (inputFilePath.toLowerCase().endsWith(".json")) { processFileJson(inputFilePath); } } }
From source file:br.com.riselabs.cotonet.Main.java
/** * @param args/*from w w w . ja v a2 s . c o m*/ * @throws EmptyContentException * @throws IOException * @throws NullPointerException * @throws InvalidNumberOfTagsException */ public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(Option.builder("c").longOpt("chunkBased").desc( "c - build a conflict chunk-based network with the developers that in fact conflits with each other." + " Additionally to the c argument the user should provide a path. This path should have" + " a file containig the repository's URL of the target systems.") .hasArg().build()); options.addOption(Option.builder("cf").longOpt("chunkBasedFullGraph") .desc("cf - like c, build a conflict chunk-based network adding all developers involved in " + "identified chunk conflicts. Additionally to the cf argument the user should provide a path. " + "This path should have a file containig the repository's URL of the target systems.") .hasArg().build()); options.addOption(Option.builder("f").longOpt("fileBase").desc( " f - build a conflict file-based network. In other others all developers that contribute to some" + " conflict at file level should be part of this network. This network is based on network provides " + "by cf, adding edges between developers of different chunks. Additionally to the f argument the" + " user should provide a path. This path should have afile containig the repository's URL of " + "the target systems.") .hasArg().build()); /* * options.addOption( Option.builder("rw").longOpt("rewrite-aux"). * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_WITHOUT_ " + * "the recreation of the merge scenarios based tags.").hasArg(false). * build()); * * options.addOption( Option.builder("rwt").longOpt("rewrite-tagfile"). * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_INCLUDING_ " * + "the recreation of the merge scenarios based tags.").hasArg(false). * build()); */ options.addOption("h", "help", false, "Print this help page"); File reposListFile = null; Boolean skipCloneAndNetworks = false; try { CommandLine cmd = parser.parse(options, args); // user is looking for help if (cmd.hasOption("h")) { new HelpFormatter().printHelp("java ", options); System.exit(0); } /* "c", "cf", and "f" are the three available options * "c" builds the chunk-based network with developers that contribute to the conflict * "cf" builds the chunk-based network with developers that contribute to the conflict and developers * that are part of the chunk, but don't contribute to the conflict * "f" builds the file-based network with developers that contribute to the chunk into a target file */ else if (cmd.hasOption("c") || cmd.hasOption("cf") || cmd.hasOption("f")) { String urlsFilePath = null; NetworkType type; if (cmd.hasOption("c")) { urlsFilePath = cmd.getOptionValue("c"); type = NetworkType.CHUNK_BASED; } else if (cmd.hasOption("cf")) { urlsFilePath = cmd.getOptionValue("cf"); type = NetworkType.CHUNK_BASED_FULL; } else { urlsFilePath = cmd.getOptionValue("f"); type = NetworkType.FILE_BASED; } System.out.println(urlsFilePath); reposListFile = new File(urlsFilePath); // Ends execution if file not found. if (!reposListFile.exists()) { System.out.println("COTONET ended without retrive any repository.\n\n" + "The file containig the repository's URL of the target systems was not found. " + "Check wether the file \"" + urlsFilePath + "\" exists."); System.exit(1); } skipCloneAndNetworks = (cmd.hasOption("rw") || cmd.hasOption("rwt")) ? true : false; MainThread m = new MainThread(type, reposListFile, skipCloneAndNetworks); m.start(); m.join(); Logger.log("COTONET finished. Files rewritten."); } else { System.out.println("COTONET ended without retrive any repository.\n\n" + "You should use 'h' if you are looking for help. Otherwise," + " the 'l' or 'fc' option is mandatory."); System.exit(1); } } catch (ParseException e) { new HelpFormatter().printHelp("java ", options); } catch (Exception e) { Logger.log(e.getMessage()); } }
From source file:com.act.lcms.db.io.LoadPlateCompositionIntoDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder("t").argName("type") .desc("The type of plate composition in this file, valid options are: " + StringUtils.join(Arrays.asList(Plate.CONTENT_TYPE.values()), ", ")) .hasArg().longOpt("plate-type").required().build()); opts.addOption(Option.builder("i").argName("path").desc("The plate composition file to read").hasArg() .longOpt("input-file").required().build()); // DB connection options. opts.addOption(Option.builder().argName("database url") .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build()); opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg() .longOpt("db-user").build()); opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg() .longOpt("db-pass").build()); opts.addOption(Option.builder("H").argName("database host") .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host") .build());// www . ja va2 s. co m opts.addOption(Option.builder("P").argName("database port") .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port") .build()); opts.addOption(Option.builder("N").argName("database name") .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg() .longOpt("db-name").build()); // Everybody needs a little help from their friends. opts.addOption( Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build()); CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HelpFormatter fmt = new HelpFormatter(); fmt.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } if (cl.hasOption("help")) { new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); return; } File inputFile = new File(cl.getOptionValue("input-file")); if (!inputFile.exists()) { System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file")); new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } PlateCompositionParser parser = new PlateCompositionParser(); parser.processFile(inputFile); Plate.CONTENT_TYPE contentType = null; try { contentType = Plate.CONTENT_TYPE.valueOf(cl.getOptionValue("plate-type")); } catch (IllegalArgumentException e) { System.err.format("Unrecognized plate type '%s'\n", cl.getOptionValue("plate-type")); new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } DB db; if (cl.hasOption("db-url")) { db = new DB().connectToDB(cl.getOptionValue("db-url")); } else { Integer port = null; if (cl.getOptionValue("P") != null) { port = Integer.parseInt(cl.getOptionValue("P")); } db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"), cl.getOptionValue("p")); } try { db.getConn().setAutoCommit(false); Plate p = Plate.getOrInsertFromPlateComposition(db, parser, contentType); switch (contentType) { case LCMS: List<LCMSWell> LCMSWells = LCMSWell.getInstance().insertFromPlateComposition(db, parser, p); for (LCMSWell LCMSWell : LCMSWells) { System.out.format("%d: %d x %d %s %s\n", LCMSWell.getId(), LCMSWell.getPlateColumn(), LCMSWell.getPlateRow(), LCMSWell.getMsid(), LCMSWell.getComposition()); } break; case STANDARD: List<StandardWell> standardWells = StandardWell.getInstance().insertFromPlateComposition(db, parser, p); for (StandardWell standardWell : standardWells) { System.out.format("%d: %d x %d %s\n", standardWell.getId(), standardWell.getPlateColumn(), standardWell.getPlateRow(), standardWell.getChemical()); } break; case DELIVERED_STRAIN: List<DeliveredStrainWell> deliveredStrainWells = DeliveredStrainWell.getInstance() .insertFromPlateComposition(db, parser, p); for (DeliveredStrainWell deliveredStrainWell : deliveredStrainWells) { System.out.format("%d: %d x %d (%s) %s %s \n", deliveredStrainWell.getId(), deliveredStrainWell.getPlateColumn(), deliveredStrainWell.getPlateRow(), deliveredStrainWell.getWell(), deliveredStrainWell.getMsid(), deliveredStrainWell.getComposition()); } break; case INDUCTION: List<InductionWell> inductionWells = InductionWell.getInstance().insertFromPlateComposition(db, parser, p); for (InductionWell inductionWell : inductionWells) { System.out.format("%d: %d x %d %s %s %s %d\n", inductionWell.getId(), inductionWell.getPlateColumn(), inductionWell.getPlateRow(), inductionWell.getMsid(), inductionWell.getComposition(), inductionWell.getChemical(), inductionWell.getGrowth()); } break; case PREGROWTH: List<PregrowthWell> pregrowthWells = PregrowthWell.getInstance().insertFromPlateComposition(db, parser, p); for (PregrowthWell pregrowthWell : pregrowthWells) { System.out.format("%d: %d x %d (%s @ %s) %s %s %d\n", pregrowthWell.getId(), pregrowthWell.getPlateColumn(), pregrowthWell.getPlateRow(), pregrowthWell.getSourcePlate(), pregrowthWell.getSourceWell(), pregrowthWell.getMsid(), pregrowthWell.getComposition(), pregrowthWell.getGrowth()); } break; case FEEDING_LCMS: List<FeedingLCMSWell> feedingLCMSWells = FeedingLCMSWell.getInstance() .insertFromPlateComposition(db, parser, p); for (FeedingLCMSWell feedingLCMSWell : feedingLCMSWells) { System.out.format("%d: %d x %d (%s @ %s) %s %s %f\n", feedingLCMSWell.getId(), feedingLCMSWell.getPlateColumn(), feedingLCMSWell.getPlateRow(), feedingLCMSWell.getMsid(), feedingLCMSWell.getComposition(), feedingLCMSWell.getExtract(), feedingLCMSWell.getChemical(), feedingLCMSWell.getConcentration()); } break; default: System.err.format("Unrecognized/unimplemented data type '%s'\n", contentType); break; } // If we didn't encounter an exception, commit the transaction. db.getConn().commit(); } catch (Exception e) { System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n", e.getMessage()); db.getConn().rollback(); throw (e); } finally { db.getConn().close(); } }
From source file:eu.fbk.utils.wikipedia.WikipediaPlainTextExtractor.java
public static void main(String args[]) throws IOException { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "configuration/log-config.txt"; }//from w ww. j a v a 2s . c om PropertyConfigurator.configure(logConfig); Options options = new Options(); try { Option wikipediaDumpOpt = OptionBuilder.withArgName("file").hasArg() .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump") .create("d"); Option outputDirOpt = OptionBuilder.withArgName("dir").hasArg() .withDescription("output directory in which to store output files").isRequired() .withLongOpt("output-dir").create("o"); Option numThreadOpt = OptionBuilder.withArgName("int").hasArg() .withDescription("number of threads (default " + Defaults.DEFAULT_THREADS_NUMBER + ")") .withLongOpt("num-threads").create("t"); Option numPageOpt = OptionBuilder.withArgName("int").hasArg() .withDescription("number of pages to process (default all)").withLongOpt("num-pages") .create("p"); Option notificationPointOpt = OptionBuilder.withArgName("int").hasArg() .withDescription("receive notification every n pages (default " + Defaults.DEFAULT_NOTIFICATION_POINT + ")") .withLongOpt("notification-point").create("b"); options.addOption(null, "text-only", false, "skipt title in file"); options.addOption("h", "help", false, "print this message"); options.addOption("v", "version", false, "output version information and exit"); options.addOption(wikipediaDumpOpt); options.addOption(outputDirOpt); options.addOption(numThreadOpt); options.addOption(numPageOpt); options.addOption(notificationPointOpt); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args); logger.debug(line); if (line.hasOption("help") || line.hasOption("version")) { throw new ParseException(""); } int numThreads = Defaults.DEFAULT_THREADS_NUMBER; boolean textOnly = line.hasOption("text-only"); if (line.hasOption("num-threads")) { numThreads = Integer.parseInt(line.getOptionValue("num-threads")); } int numPages = Defaults.DEFAULT_NUM_PAGES; if (line.hasOption("num-pages")) { numPages = Integer.parseInt(line.getOptionValue("num-pages")); } int notificationPoint = Defaults.DEFAULT_NOTIFICATION_POINT; if (line.hasOption("notification-point")) { notificationPoint = Integer.parseInt(line.getOptionValue("notification-point")); } ExtractorParameters extractorParameters = new ExtractorParameters(line.getOptionValue("wikipedia-dump"), line.getOptionValue("output-dir")); WikipediaPlainTextExtractor wikipediaPageParser = new WikipediaPlainTextExtractor(numThreads, numPages, extractorParameters.getLocale()); wikipediaPageParser.setNotificationPoint(notificationPoint); // wikipediaPageParser.setSkipTitle(textOnly); wikipediaPageParser.start(extractorParameters); logger.info("extraction ended " + new Date()); } catch (ParseException e) { // oops, something went wrong System.out.println("Parsing failed: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(400, "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.xmldump.WikipediaTextExtractor", "\n", options, "\n", true); } }
From source file:com.mvdb.etl.actions.InitCustomerData.java
public static void main(String[] args) { ActionUtils.assertEnvironmentSetupOk(); ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing."); ActionUtils.assertFileExists("~/.mvdb/status.InitDB.complete", "200initdb.sh not executed yet. Exiting"); ActionUtils.assertFileDoesNotExist("~/.mvdb/status.InitCustomerData.complete", "InitCustomerData already done. Start with 100init.sh if required. Exiting"); ActionUtils.setUpInitFileProperty(); ActionUtils.createMarkerFile("~/.mvdb/status.InitCustomerData.start"); Date startDate = null;//from w ww . j a v a 2 s . c om Date endDate = null; String customerName = null; int batchCountF = 0; int batchSizeF = 0; final CommandLineParser cmdLinePosixParser = new PosixParser(); final Options posixOptions = constructPosixOptions(); CommandLine commandLine; try { commandLine = cmdLinePosixParser.parse(posixOptions, args); if (commandLine.hasOption("customer")) { customerName = commandLine.getOptionValue("customer"); } if (commandLine.hasOption("batchSize")) { String batchSizeStr = commandLine.getOptionValue("batchSize"); batchSizeF = Integer.parseInt(batchSizeStr); } if (commandLine.hasOption("batchCount")) { String batchCountStr = commandLine.getOptionValue("batchCount"); batchCountF = Integer.parseInt(batchCountStr); } if (commandLine.hasOption("startDate")) { String startDateStr = commandLine.getOptionValue("startDate"); startDate = ActionUtils.getDate(startDateStr); } if (commandLine.hasOption("endDate")) { String endDateStr = commandLine.getOptionValue("endDate"); endDate = ActionUtils.getDate(endDateStr); } } catch (ParseException parseException) // checked exception { System.err.println( "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage()); } if (startDate == null) { System.err.println( "startDate has not been specified with the correct format YYYYMMddHHmmss. Aborting..."); System.exit(1); } if (endDate == null) { System.err .println("endDate has not been specified with the correct format YYYYMMddHHmmss. Aborting..."); System.exit(1); } if (endDate.after(startDate) == false) { System.err.println("endDate must be after startDate. Aborting..."); System.exit(1); } // if you have time, // it's better to create an unit test rather than testing like this :) ApplicationContext context = Top.getContext(); final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO"); final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO"); initData(orderDAO, batchCountF, batchSizeF, startDate, endDate); initConfiguration(configurationDAO, customerName, endDate); int total = orderDAO.findTotalOrders(); System.out.println("Total : " + total); long max = orderDAO.findMaxId(); System.out.println("maxid : " + max); ActionUtils.createMarkerFile("~/.mvdb/status.InitCustomerData.complete"); }
From source file:net.mybox.mybox.Server.java
/** * Handle the command line args and instantiate the Server * @param args//from ww w . jav a 2 s .c o m */ public static void main(String args[]) { Options options = new Options(); options.addOption("c", "config", true, "configuration file"); // options.addOption("d", "database", true, "accounts database file"); // TODO: handle in config? options.addOption("a", "apphome", true, "application home directory"); options.addOption("h", "help", false, "show help screen"); options.addOption("V", "version", false, "print the Mybox version"); CommandLineParser line = new GnuParser(); CommandLine cmd = null; try { cmd = line.parse(options, args); } catch (ParseException exp) { System.err.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Server.class.getName(), options); return; } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Server.class.getName(), options); return; } if (cmd.hasOption("V")) { Client.printMessage("version " + Common.appVersion); return; } if (cmd.hasOption("a")) { String appHomeDir = cmd.getOptionValue("a"); try { Common.updatePaths(appHomeDir); } catch (FileNotFoundException e) { printErrorExit(e.getMessage()); } updatePaths(); } String configFile = defaultConfigFile; // String accountsDBfile = defaultAccountsDbFile; if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } File fileCheck = new File(configFile); if (!fileCheck.isFile()) Server.printErrorExit("Config not found: " + configFile + "\nPlease run ServerSetup"); // if (cmd.hasOption("d")){ // accountsDBfile = cmd.getOptionValue("d"); // } // // fileCheck = new File(accountsDBfile); // if (!fileCheck.isFile()) // Server.printErrorExit("Error: account database not found " + accountsDBfile); Server server = new Server(configFile); }
From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The root URL of the application to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, URL_OPTION_LONG); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The file to be used to populate the answers, can point to the file system or the class path", true, FILE_OPTION_LONG);// ww w. j a v a2 s .c om Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true, "The directory containing the html answer files, can point to the file system or the class path", true, DIR_OPTION_LONG); Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API", true, USER_OPTION_LONG); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password for the manage API", true, PASSWORD_OPTION_LONG); final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption); CommandLine cmd; try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null); return; } final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL); final String file = cmd.getOptionValue(FILE_OPTION); final String dir = cmd.getOptionValue(DIR_OPTION); final String user = cmd.getOptionValue(USER_OPTION); final String password = cmd.getOptionValue(PASSWORD_OPTION); System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT) .getFormattedMessage()); try { AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password); // we only want to populate if there is nothing in the database already // start with the assumption that we do want to populate and stop if we find answers in there already boolean doPopulate = true; String answersResult = getAnswers(client); if (answersResult != null && !answersResult.isEmpty()) { Gson gson = new Gson(); Type type = new TypeToken<List<ManagedAnswer>>() { }.getType(); List<ManagedAnswer> answers = gson.fromJson(answersResult, type); if (answers != null && answers.size() > 0) { System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size()) .getFormattedMessage()); doPopulate = false; } } if (doPopulate) { System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2 .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage()); boolean success = populate(client, file, dir); if (!success) { throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage() .getFormattedMessage()); } } else { System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage() .getFormattedMessage()); } System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage()); } catch (IOException e) { System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage()) .getFormattedMessage()); e.printStackTrace(System.err); } }
From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java
/** * Password Manager entry point//from w ww .jav a 2 s . c om * * @param argv * @throws Exception */ public static void main(String argv[]) throws Exception { keystoreManager = new KeystoreManagerCtrl(); // --- Options --- CommandLine line = null; try { CommandLineParser parser = new GnuParser(); // --- Parse the command line arguments --- // --- Help line = parser.parse(keystoreManager.helpOptions, argv, true); if (line.hasOption(_HELP)) { DisplayHelpAndExit(EXIT_CODE.EXIT_OK); } // --- Program command line options line = parser.parse(keystoreManager.options, argv); // --- Compulsory arguments : Get options --- if (line.hasOption(_KEYSTORE_LOCATION)) keystoreManager.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION); if (line.hasOption(_KEY_ALIAS)) keystoreManager.keyAlias = line.getOptionValue(_KEY_ALIAS); if (line.hasOption(_KEY_TYPE)) { String keyType = line.getOptionValue(_KEY_TYPE); // This will throw an exception if the type is not recognised KEYSTORE_TYPE certificateTYpe = KEYSTORE_TYPE.fromString(keyType); keystoreManager.keyType = certificateTYpe; } if (line.hasOption(_KEYSTORE_PASSWORD)) keystoreManager.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD); if (line.hasOption(_KEY_PASSWORD)) keystoreManager.keyPassword = line.getOptionValue(_KEY_PASSWORD); } catch (ParseException exp) { logger.error(exp.getMessage()); DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR); } catch (Exception e) { // Workaround for Junit test if (e.toString().contains("CheckExitCalled")) { throw e; } else // Normal behaviour { logger.error(e.getMessage()); Exit(EXIT_CODE.EXIT_ERROR); } } // --- Perform commands --- // ######### Check password ########## if (line.hasOption(_CHECK)) { try { if (keystoreManager.keystorePassword == null || keystoreManager.keyPassword == null) { // --- Get passwords from stdin if not given on command line List<String> listPrompts = Arrays.asList("Keystore password:", MessageFormat.format("Password for key {0}:", keystoreManager.keyAlias)); List<String> listUserInput = keystoreManager.getUserInputFromStdin(listPrompts); if (listUserInput.size() == listPrompts.size()) { keystoreManager.keystorePassword = listUserInput.get(0); keystoreManager.keyPassword = listUserInput.get(1); } else { throw new NoSuchElementException(); } } try { // --- Check that all keys in keystore use the keystore // password logger.info(MessageFormat.format("Using keystore:{0}", keystoreManager.keystoreLocation)); SecurityHelper.checkKeyStorePasswords(keystoreManager.keystoreLocation, keystoreManager.keyType, keystoreManager.keystorePassword, keystoreManager.keyAlias, keystoreManager.keyPassword); logger.info(MessageFormat.format("OK : Identical password for Keystore and key={0}", keystoreManager.keyAlias)); } catch (UnrecoverableKeyException uke) { logger.error(MessageFormat.format("At least 1 key has a wrong password.{0}", uke.getMessage())); Exit(EXIT_CODE.EXIT_ERROR); } catch (Exception e) { logger.error(MessageFormat.format("{0}", e.getMessage())); Exit(EXIT_CODE.EXIT_ERROR); } } catch (NoSuchElementException nse) { logger.error(nse.getMessage()); Exit(EXIT_CODE.EXIT_ERROR); } catch (Exception e) { logger.error(MessageFormat.format("Error while running the program: {0}", e.getMessage())); Exit(EXIT_CODE.EXIT_ERROR); } } Exit(EXIT_CODE.EXIT_OK); }
From source file:Inmemantlr.java
public static void main(String[] args) { LOGGER.info("Inmemantlr tool"); HelpFormatter hformatter = new HelpFormatter(); Options options = new Options(); // Binary arguments options.addOption("h", "print this message"); Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files") .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build(); Option infiles = Option.builder().longOpt("infiles").hasArgs() .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class) .valueSeparator(',').build(); Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs() .desc("comma-separated list of utility files to be added for " + "compilation").required(false) .argName("utilfiles").type(String.class).valueSeparator(',').build(); Option odir = Option.builder().longOpt("outdir") .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true) .argName("outdir").type(String.class).build(); options.addOption(infiles);//from w w w.ja v a2 s . c o m options.addOption(grmr); options.addOption(utilfiles); options.addOption(odir); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption('h')) { hformatter.printHelp("java -jar inmemantlr.jar", options); System.exit(0); } } catch (ParseException e) { hformatter.printHelp("java -jar inmemantlr.jar", options); LOGGER.error(e.getMessage()); System.exit(-1); } // input files Set<File> ins = getFilesForOption(cmd, "infiles"); // grammar files Set<File> gs = getFilesForOption(cmd, "grmrfiles"); // utility files Set<File> uf = getFilesForOption(cmd, "utilfiles"); // output dir Set<File> od = getFilesForOption(cmd, "outdir"); if (od.size() > 1) { LOGGER.error("output directories must be less than or equal to 1"); System.exit(-1); } if (ins.size() <= 0) { LOGGER.error("no input files were specified"); System.exit(-1); } if (gs.size() <= 0) { LOGGER.error("no grammar files were specified"); System.exit(-1); } LOGGER.info("create generic parser"); GenericParser gp = null; try { gp = new GenericParser(gs.toArray(new File[gs.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } if (!uf.isEmpty()) { try { gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } LOGGER.info("create and add parse tree listener"); DefaultTreeListener dt = new DefaultTreeListener(); gp.setListener(dt); LOGGER.info("compile generic parser"); try { gp.compile(); } catch (CompilationException e) { LOGGER.error("cannot compile generic parser: {}", e.getMessage()); System.exit(-1); } String fpfx = ""; for (File of : od) { if (!of.exists() || !of.isDirectory()) { LOGGER.error("output directory does not exist or is not a " + "directory"); System.exit(-1); } fpfx = of.getAbsolutePath(); } Ast ast; for (File f : ins) { try { gp.parse(f); } catch (IllegalWorkflowException | FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } ast = dt.getAst(); if (!fpfx.isEmpty()) { String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot"; LOGGER.info("write file {}", of); try { FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8"); } catch (IOException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } else { LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot()); } } System.exit(0); }