List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:cz.cuni.mff.ufal.dspace.app.MoveItems.java
/** * main method to run the MoveItems action * /*from w ww . j av a 2 s. c o m*/ * @param argv * the command line arguments given * @throws SQLException */ public static void main(String[] argv) throws SQLException { // Create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("l", "list", false, "list collections"); options.addOption("s", "source", true, "source collection ID"); options.addOption("t", "target", true, "target collection ID"); options.addOption("i", "inherit", false, "inherit target collection privileges (default false)"); options.addOption("h", "help", false, "help"); // Parse the command line arguments CommandLine line; try { line = parser.parse(options, argv); } catch (ParseException pe) { System.err.println("Error parsing command line arguments: " + pe.getMessage()); System.exit(1); return; } if (line.hasOption('h') || line.getOptions().length == 0) { printHelp(options, 0); } // Create a context Context context; try { context = new Context(); context.turnOffAuthorisationSystem(); } catch (Exception e) { System.err.println("Unable to create a new DSpace Context: " + e.getMessage()); System.exit(1); return; } if (line.hasOption('l')) { listCollections(context); System.exit(0); } // Check a filename is given if (!line.hasOption('s')) { System.err.println("Required parameter -s missing!"); printHelp(options, 1); } Boolean inherit; // Check a filename is given if (line.hasOption('i')) { inherit = true; } else { inherit = false; } String sourceCollectionIdParam = line.getOptionValue('s'); Integer sourceCollectionId = null; if (sourceCollectionIdParam.matches("\\d+")) { sourceCollectionId = Integer.valueOf(sourceCollectionIdParam); } else { System.err.println("Invalid argument for parameter -s: " + sourceCollectionIdParam); printHelp(options, 1); } // Check source collection ID is given if (!line.hasOption('t')) { System.err.println("Required parameter -t missing!"); printHelp(options, 1); } String targetCollectionIdParam = line.getOptionValue('t'); Integer targetCollectionId = null; if (targetCollectionIdParam.matches("\\d+")) { targetCollectionId = Integer.valueOf(targetCollectionIdParam); } else { System.err.println("Invalid argument for parameter -t: " + targetCollectionIdParam); printHelp(options, 1); } // Check target collection ID is given if (targetCollectionIdParam.equals(sourceCollectionIdParam)) { System.err.println("Source collection id and target collection id must differ"); printHelp(options, 1); } try { moveItems(context, sourceCollectionId, targetCollectionId, inherit); // Finish off and tidy up context.restoreAuthSystemState(); context.complete(); } catch (Exception e) { context.abort(); System.err.println("Error committing changes to database: " + e.getMessage()); System.err.println("Aborting most recent changes."); System.exit(1); } }
From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java
public static void main(String args[]) { // Example Command line args //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000 int numberEvents = 10000; // Number of Events String gisServer = "w12ags104a.jennings.home"; // GIS Server int inputTcpPort = 5565; // TCP Input Port String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0"; String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("g", true, "GIS Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("m", true, "Map Service Layer URL"); opts.addOption("f", true, "File with GeoEvents to Send"); opts.addOption("r", true, "Rates to test Start,End,Step"); opts.addOption("h", false, "Help"); try {// w w w . j a va 2 s .com CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (org.apache.commons.cli.ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new org.apache.commons.cli.ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("g")) { gisServer = cmd.getOptionValue("g"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { inputTcpPort = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("m")) { msLayerUrl = cmd.getOptionValue("m"); } if (cmd.hasOption("f")) { EventsInputFile = cmd.getOptionValue("f"); } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new org.apache.commons.cli.ParseException( "Rate must be three comma seperated values or a single value"); } } catch (org.apache.commons.cli.ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg); } // Assuming the ES port is 9220 RunTcpInBdsOutTest t = new RunTcpInBdsOutTest(); DecimalFormat df = new DecimalFormat("##0"); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); Thread.sleep(3 * 1000); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.ovea.tajin.server.ContainerRunner.java
public static void main(String... args) throws Exception { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help") || !line.hasOption(Properties.CONTAINER.getName())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ContainerRunner.class.getSimpleName(), options); return;//from ww w . j a va 2s . c o m } // Set default values // And override by system properties. This way, we can start ContainerRunner with specific options such as -DjettyConf=.. -DjettyEnv=... ContainerConfiguration settings = ContainerConfiguration.from(System.getProperties()); // Then parse command line for (Option option : line.getOptions()) { settings.set(Properties.from(option.getOpt()), line.getOptionValue(option.getOpt())); } Container container = settings.buildContainer(line.getOptionValue(Properties.CONTAINER.getName())); container.start(); }
From source file:net.aepik.alasca.plugin.schemaconverter.SCTool.java
/** * Launch this tool./*from w w w.j a va 2 s .c o m*/ */ public static void main(String[] args) { String inFile = null; String inSyntax = null; String outFile = null; String outSyntax = null; boolean clear = false; boolean list = false; // // Parsing options. // CommandLineParser parser = new GnuParser(); try { CommandLine cmdOptions = parser.parse(options, args); inFile = cmdOptions.getOptionValue("i"); inSyntax = cmdOptions.getOptionValue("I"); outFile = cmdOptions.getOptionValue("o"); outSyntax = cmdOptions.getOptionValue("O"); if (cmdOptions.hasOption("c")) { clear = true; } if (cmdOptions.hasOption("l")) { list = true; } if (cmdOptions.getOptions().length == 0) { displayHelp(); System.exit(2); } } catch (MissingArgumentException e) { System.out.println("Missing arguments\n"); displayHelp(); System.exit(2); } catch (ParseException e) { System.out.println("Wrong arguments\n"); displayHelp(); System.exit(2); } // // Print query options. // if (list) { displayAvailableSyntaxes(); System.exit(0); } // // Launch schema. // String dictionnary = findDictionnary(inSyntax, outSyntax); if (dictionnary == null) { System.out.println("Can't find valid translation dictionnary"); System.exit(1); } SchemaSyntax inSchemaSyntax = createSchemaSyntax(inSyntax); if (inSchemaSyntax == null) { System.out.println("Unknow input syntax (" + inSyntax + ")"); System.exit(1); } SchemaSyntax outSchemaSyntax = createSchemaSyntax(outSyntax); if (outSchemaSyntax == null) { System.out.println("Unknow output syntax (" + outSyntax + ")"); System.exit(1); } Schema inSchema = createSchema(inSchemaSyntax, inFile); if (inSchema == null) { System.out.println("Failed to read input schema file (" + inFile + ")"); System.exit(1); } // // Convert schema. // Schema outSchema = convertSchema(inSchema, dictionnary, outSyntax); if (outSchema == null) { System.out.println("Failed to convert input schema"); System.exit(1); } if (clear) { outSchema.setProperties(new Properties()); } // // Write schema. // SchemaFileWriter schemaWriter = outSchemaSyntax.createSchemaWriter(); SchemaFile schemaFile = new SchemaFile(outFile, null, schemaWriter); schemaFile.setSchema(outSchema); if (!schemaFile.write()) { System.out.println("Failed to write output schema file"); System.exit(1); } System.exit(0); }
From source file:HLA.java
public static void main(String[] args) throws IOException { if (!isVersionOrHigher()) { System.err.println("JRE of 1.8+ is required to run Kourami. Exiting."); System.exit(1);//from w ww . j a v a 2 s. c om } CommandLineParser parser = new DefaultParser(); Options options = HLA.createOption(); Options helponlyOpts = HLA.createHelpOption(); String[] bams = null; CommandLine line = null; boolean exitRun = false; try { CommandLine helpcheck = new DefaultParser().parse(helponlyOpts, args, true); if (helpcheck.getOptions().length > 0) HLA.help(options); else { line = parser.parse(options, args); if (line.hasOption("h"))//help")) HLA.help(options); else { if (line.hasOption("a")) HLA.TYPEADDITIONAL = true; HLA.OUTPREFIX = line.getOptionValue("o");//outfilePrefix"); String tmploc = line.getOptionValue("d");//msaDirectory"); HLA.MSAFILELOC = tmploc; if (tmploc.endsWith(File.separator)) HLA.MSAFILELOC = tmploc.substring(0, tmploc.length() - 1); if (!new File(HLA.MSAFILELOC).exists() || !new File(HLA.MSAFILELOC).isDirectory()) { System.err.println("Given msaDirectory: " + HLA.MSAFILELOC + "\t does NOT exist or is NOT a directory."); exitRun = true; } else if (!new File(HLA.MSAFILELOC + File.separator + "hla_nom_g.txt").exists()) { System.err.println("hla_nom_g.txt NOT FOUND in " + HLA.MSAFILELOC); System.err .println("Please download hla_nom_g.txt from the same IMGT Release as msa files."); exitRun = true; } } bams = line.getArgs(); if (bams.length < 1 || (bams.length == 1 && bams[bams.length - 1].equals("DEBUG1228"))) throw new ParseException("At least 1 bam file is required. See Usage:"); else { if (bams.length > 1 && bams[bams.length - 1].equals("DEBUG1228")) { String[] tmpbams = new String[bams.length - 1]; for (int i = 0; i < bams.length - 1; i++) tmpbams[i] = bams[i]; bams = tmpbams; HLA.DEBUG = true; } for (String b : bams) if (!new File(b).exists()) { System.err .println("Input bam : " + b + " DOES NOT exist. Please check the bam exists."); exitRun = true; } } } if (exitRun) throw new ParseException("Exitting . . ."); } catch (ParseException e) { System.err.println(e.getMessage()); //System.err.println("Failed to parse command line args. Check usage."); HLA.help(options); } String[] list = { "A", "B", "C", "DQA1", "DQB1", "DRB1" }; String[] extList = { "A", "B", "C", "DQA1", "DQB1", "DRB1", "DOA", "DMA", "DMB", "DPA1", "DPB1", "DRA", "DRB3", "DRB5", "F", "G", "H", "J", "L" }; //,"DPA1", "DPB1", "DRA", "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"}; //,"DPA1", "DPB1", "DRA", "DRB3", "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"}; if (HLA.TYPEADDITIONAL) list = extList; File[] bamfiles = new File[bams.length]; for (int i = 0; i < bams.length; i++) bamfiles[i] = new File(bams[i]); //check if <HLA.OUTPREFIX>.result is writable //if not exit. BufferedWriter resultWriter = null; try { resultWriter = new BufferedWriter(new FileWriter(HLA.OUTPREFIX + ".result")); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("\n\n>>> CANNOT open output file: " + HLA.OUTPREFIX + ".result <<<\n\n"); HLA.help(options); } HLA.log = new LogHandler(); for (int i = 0; i < args.length; i++) HLA.log.append(" " + args[i]); HLA.log.appendln(); try { System.err.println("----------------REF GRAPH CONSTRUCTION--------------"); HLA.log.appendln("----------------REF GRAPH CONSTRUCTION--------------"); HLA hla = new HLA(list, HLA.MSAFILELOC + File.separator + "hla_nom_g.txt"); //1. bubble counting before loading reads. //System.err.println("----------------BUBBLE COUNTING: REF GRAPH--------------"); //HLA.log.appendln("----------------BUBBLE COUNTING: REF GRAPH--------------"); //hla.countStems(); System.err.println("---------------- READ LOADING --------------"); HLA.log.appendln("---------------- READ LOADING --------------"); hla.loadReads(bamfiles); System.err.println("---------------- GRAPH CLEANING --------------"); HLA.log.appendln("---------------- GRAPH CLEANING --------------"); hla.flattenInsertionNodes(list); hla.removeUnused(list); hla.removeStems(list); /*updating error prob*/ hla.updateErrorProb(); hla.log.flush(); StringBuffer resultBuffer = new StringBuffer(); HLA.DEBUG3 = HLA.DEBUG; hla.countBubblesAndMerge(list, resultBuffer); hla.writeResults(resultBuffer, resultWriter); } catch (Exception e) { e.printStackTrace(); HLA.log.outToFile(); System.exit(-1); } /*printingWeights*/ //hla.printWeights(); HLA.log.outToFile(); HLA.log.appendln("NEW_NODE_ADDED:\t" + HLA.NEW_NODE_ADDED); HLA.log.appendln("HOPPPING:\t" + HLA.HOPPING); HLA.log.appendln("INSERTION_NODE_ADDED:\t" + HLA.INSERTION_NODE_ADDED); HLA.log.appendln("INSERTION_WITH_NO_NEW_NODE:\t" + HLA.INSERTION_WITH_NO_NEW_NODE); HLA.log.appendln("INSERTION_COUNTS:\t" + HLA.INSERTION); }
From source file:emperior.Main.java
public static void main(String[] args) throws Exception { mainFrame = new MainFrame(); operatingSystem = System.getProperty("os.name"); CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information"); options.addOption("t", "test", true, "Name of the Bat-File which is executed for Compilation and Unit-Testing"); options.addOption("r", "run", true, "Name of the Bat-File which is executed for Compilation and running the project"); options.addOption("f", "folder", true, "Name of the Folder in which the exercises for the Experiment are stored"); CommandLine commandLine = parser.parse(options, args); // read from command line if (commandLine.getOptions().length > 0) { readCommandLine(commandLine, options); }// w ww.j av a2 s .com // read from property file else { readPropertyFile(); } initLogging(); checkBatFile(); addLineToLogFile("[Start] Emperior"); if (resuming) Main.addLineToLogFile("[ResumeTask] Resume task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); else { Main.addLineToLogFile("[StartTask] Start new task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); startedWith = Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask); updateStartedWithTask(Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); } mainFrame.init(); mainFrame.setSize(800, 600); mainFrame.setVisible(true); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Main.addLineToLogFile("[PauseTask] Stop task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); addLineToLogFile("[Close] Emperior"); updateResumeTask(tasktypes.get(activeType) + "_" + tasks.get(activeTask)); System.exit(0); } }); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //makeContiniousCopys(); }
From source file:com.github.chrbayer84.keybits.KeyBits.java
/** * @param args/*from ww w.ja va2 s .c om*/ */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }
From source file:com.cws.esolutions.security.main.PasswordUtility.java
public static void main(final String[] args) { final String methodName = PasswordUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/*w ww.j a v a 2s. c o m*/ DEBUGGER.debug("Value: {}", methodName); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(PasswordUtility.CNAME, options, true); System.exit(1); } BufferedReader bReader = null; BufferedWriter bWriter = null; try { // load service config first !! SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG, false); if (DEBUG) { DEBUGGER.debug("Options options: {}", options); for (String arg : args) { DEBUGGER.debug("Value: {}", arg); } } CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo(); final SystemConfig systemConfig = secConfigData.getSystemConfig(); if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig); DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig); } if (commandLine.hasOption("encrypt")) { if ((StringUtils.isBlank(repoConfig.getPasswordFile())) || (StringUtils.isBlank(repoConfig.getSaltFile()))) { System.err.println("The password/salt files are not configured. Entries will not be stored!"); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } final String entryName = commandLine.getOptionValue("entry"); final String username = commandLine.getOptionValue("username"); final String password = commandLine.getOptionValue("password"); final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); DEBUGGER.debug("String password: {}", password); DEBUGGER.debug("String salt: {}", salt); } final String encodedSalt = PasswordUtils.base64Encode(salt); final String encodedUserName = PasswordUtils.base64Encode(username); final String encryptedPassword = PasswordUtils.encryptText(password, salt, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword); if (DEBUG) { DEBUGGER.debug("String encodedSalt: {}", encodedSalt); DEBUGGER.debug("String encodedUserName: {}", encodedUserName); DEBUGGER.debug("String encodedPassword: {}", encodedPassword); } if (commandLine.hasOption("store")) { try { new File(passwordFile.getParent()).mkdirs(); new File(saltFile.getParent()).mkdirs(); boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile(); if (DEBUG) { DEBUGGER.debug("saltFileExists: {}", saltFileExists); } // write the salt out first if (!(saltFileExists)) { throw new IOException("Unable to create salt file"); } boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile(); if (!(passwordFileExists)) { throw new IOException("Unable to create password file"); } if (commandLine.hasOption("replace")) { File[] files = new File[] { saltFile, passwordFile }; if (DEBUG) { DEBUGGER.debug("File[] files: {}", (Object) files); } for (File file : files) { if (DEBUG) { DEBUGGER.debug("File: {}", file); } String currentLine = null; File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile"); if (DEBUG) { DEBUGGER.debug("File tmpFile: {}", tmpFile); } bReader = new BufferedReader(new FileReader(file)); bWriter = new BufferedWriter(new FileWriter(tmpFile)); while ((currentLine = bReader.readLine()) != null) { if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) { bWriter.write(currentLine + System.getProperty("line.separator")); bWriter.flush(); } } bWriter.close(); FileUtils.deleteQuietly(file); FileUtils.copyFile(tmpFile, file); FileUtils.deleteQuietly(tmpFile); } } FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt + System.getProperty("line.separator"), true); FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + "," + encodedPassword + System.getProperty("line.separator"), true); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } System.out.println("Entry Name " + entryName + " stored."); } if (commandLine.hasOption("decrypt")) { String saltEntryName = null; String saltEntryValue = null; String decryptedPassword = null; String passwordEntryName = null; if ((StringUtils.isEmpty(commandLine.getOptionValue("entry")) && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) { throw new ParseException("No entry or username was provided to decrypt."); } if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) { throw new ParseException("no entry provided to decrypt"); } String entryName = commandLine.getOptionValue("entry"); String username = commandLine.getOptionValue("username"); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) { throw new IOException( "Unable to read configured password/salt file. Please check configuration and/or permissions."); } for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) { saltEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String saltEntryName: {}", saltEntryName); } if (StringUtils.equals(saltEntryName, entryName)) { saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]); break; } } if (StringUtils.isEmpty(saltEntryValue)) { throw new SecurityException("No entries were found that matched the provided information"); } for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) { passwordEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName); } if (StringUtils.equals(passwordEntryName, saltEntryName)) { String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]); decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); break; } } if (StringUtils.isEmpty(decryptedPassword)) { throw new SecurityException("No entries were found that matched the provided information"); } System.out.println(decryptedPassword); } else if (commandLine.hasOption("encode")) { System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0))); } else if (commandLine.hasOption("decode")) { System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0))); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); System.err.println("An error occurred during processing: " + iox.getMessage()); System.exit(1); } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); System.exit(1); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); System.exit(1); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.exit(1); } finally { try { if (bReader != null) { bReader.close(); } if (bWriter != null) { bReader.close(); } } catch (IOException iox) { } } System.exit(0); }
From source file:com.cyberway.issue.io.arc.ARCReader.java
/** * Command-line interface to ARCReader./*from www .j a va 2 s. c o m*/ * * Here is the command-line interface: * <pre> * usage: java com.cyberway.issue.io.arc.ARCReader [--offset=#] ARCFILE * -h,--help Prints this message and exits. * -o,--offset Outputs record at this offset into arc file.</pre> * * <p>See in <code>$HERITRIX_HOME/bin/arcreader</code> for a script that'll * take care of classpaths and the calling of ARCReader. * * <p>Outputs using a pseudo-CDX format as described here: * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX * Legent</a> and here * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>. * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'. * Hash is hard-coded straight SHA-1 hash of content. * * @param args Command-line arguments. * @throws ParseException Failed parse of the command line. * @throws IOException * @throws java.text.ParseException */ public static void main(String[] args) throws ParseException, IOException, java.text.ParseException { Options options = getOptions(); options.addOption(new Option("p", "parse", false, "Parse headers.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. long offset = -1; boolean digest = false; boolean strict = false; boolean parse = false; String format = CDX; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'o': offset = Long.parseLong(cmdlineOptions[i].getValue()); break; case 's': strict = true; break; case 'p': parse = true; break; case 'd': digest = getTrueOrFalse(cmdlineOptions[i].getValue()); break; case 'f': format = cmdlineOptions[i].getValue().toLowerCase(); boolean match = false; // List of supported formats. final String[] supportedFormats = { CDX, DUMP, GZIP_DUMP, HEADER, NOHEAD, CDX_FILE }; for (int ii = 0; ii < supportedFormats.length; ii++) { if (supportedFormats[ii].equals(format)) { match = true; break; } } if (!match) { usage(formatter, options, 1); } break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } if (offset >= 0) { if (cmdlineArgs.size() != 1) { System.out.println("Error: Pass one arcfile only."); usage(formatter, options, 1); } ARCReader arc = ARCReaderFactory.get((String) cmdlineArgs.get(0), offset); arc.setStrict(strict); // We must parse headers if we need to skip them. if (format.equals(NOHEAD) || format.equals(HEADER)) { parse = true; } arc.setParseHttpHeaders(parse); outputRecord(arc, format); } else { for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { String urlOrPath = (String) i.next(); try { ARCReader r = ARCReaderFactory.get(urlOrPath); r.setStrict(strict); r.setParseHttpHeaders(parse); r.setDigest(digest); output(r, format); } catch (RuntimeException e) { // Write out name of file we failed on to help with // debugging. Then print stack trace and try to keep // going. We do this for case where we're being fed // a bunch of ARCs; just note the bad one and move // on to the next. System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } } } }
From source file:it.uniud.ailab.dcore.launchers.Launcher.java
/** * Starts the Distiller using the specified configuration, analyzing the * specified file, writing the output in the specified folder. * * @param args the command-line parameters. *//*w w w .ja va 2s .c o m*/ public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); createOptions(); CommandLine cmd; try { // parse the command line arguments cmd = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong printError("Error while parsing command line options: " + exp.getLocalizedMessage()); return; } // if no options has been selected, just return. if (cmd.getOptions().length == 0) { printHelp(); return; } // read the options. if (readOptions(cmd)) { // everything's good! proceed doWork(); } else { printError("Unexpected error while parsing command line options\n" + "Please contact the developers of the framwork to get " + "additional help."); return; } }