List of usage examples for org.apache.commons.cli GnuParser GnuParser
GnuParser
From source file:edu.ksu.cis.indus.staticanalyses.concurrency.independence.IndependenceDetectionCLI.java
/** * The entry point to the program via command line. * //ww w .j a va2s . c o m * @param args is the command line arguments. * @throws RuntimeException when CLI fails. */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("o", "output", true, "Directory into which jimple files will be written into. [required]"); _option.setArgs(1); _option.setArgName("ouput-directory"); _option.setRequired(true); _options.addOption(_option); _option = new Option("h", "help", false, "Display message."); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path."); _option.setArgs(1); _option.setArgName("classpath"); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("useV2", false, "Use version 2 of the atomicity detection algorithm."); _options.addOption(_option); _option = new Option("scheme", false, "Scheme to indicate atomicity. Valid values are 'tag-stmt' and 'tag-region'. By default, 'tag-stmt' " + "scheme is used. "); _option.setArgs(1); _option.setArgName("scheme-name"); _options.addOption(_option); _option = new Option("S", "scope", true, "The scope that should be analyzed."); _option.setArgs(1); _option.setArgName("scope"); _option.setRequired(false); _options.addOption(_option); final CommandLineParser _parser = new GnuParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption("h")) { final String _cmdLineSyn = "java " + IndependenceDetectionCLI.class.getName() + " <options> <classnames>"; (new HelpFormatter()).printHelp(_cmdLineSyn, _options); System.exit(1); } if (_cl.getArgList().isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } final IndependenceDetectionCLI _cli; if (_cl.hasOption("useV2")) { _cli = new IndependenceDetectionCLI(new IndependentStmtDetectorv2()); } else { _cli = new IndependenceDetectionCLI(new IndependentStmtDetector()); } if (_cl.hasOption('p')) { _cli.addToSootClassPath(_cl.getOptionValue('p')); } if (_cl.hasOption('S')) { _cli.setScopeSpecFile(_cl.getOptionValue('S')); } _cli.setClassNames(_cl.getArgList()); _cli.setOutputDir(_cl.getOptionValue('o')); _cli.<ITokens>execute(_cl); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line." + _e); final String _cmdLineSyn = "java " + IndependenceDetectionCLI.class.getName() + " <options> <classnames>"; (new HelpFormatter()).printHelp(_cmdLineSyn, "Options are:", _options, ""); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:co.turnus.analysis.buffers.MpcBoundedSchedulingCliLauncher.java
public static void main(String[] args) { try {/* w w w.j av a 2 s . co m*/ CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(cliOptions, args); Configuration config = parseCommandLine(cmd); // init models AnalysisActivator.init(); // set logger verbosity if (config.getBoolean(VERBOSE, false)) { TurnusLogger.setLevel(TurnusLevel.ALL); } File tDir = new File(config.getString(TRACE_PROJECT)); TraceProject project = TraceProject.load(tDir); MpcBoundedScheduling mpc = new MpcBoundedScheduling(project); mpc.setConfiguration(config); BufferMinimizationData data = mpc.run(); TurnusLogger.info("Storing results..."); File outPath = new File(config.getString(OUTPUT_PATH)); // store the analysis report String uuid = UUID.randomUUID().toString(); File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT); Report report = DataFactory.eINSTANCE.createReport(); report.setDate(new Date()); report.setComment("Report with only Bounded Buffer Scheduling results analysis"); report.getDataSet().add(data); EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile); TurnusLogger.info("TURNUS report stored in " + rFile); // store formatted reports String xlsName = config.getString(XLS, ""); if (!xlsName.isEmpty()) { File xlsFile = new File(outPath, xlsName + ".xls"); new XlsBufferMinimizationDataWriter().write(data, xlsFile); TurnusLogger.info("XLS report stored in " + xlsFile); } String bxdfName = config.getString(BXDF, ""); if (!bxdfName.isEmpty()) { File bxdfFile = new File(outPath, bxdfName + ".bxdf"); new XmlBufferMinimizationDataWriter().write(data, bxdfFile); TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath); } TurnusLogger.info("Analysis Done!"); } catch (ParseException e) { TurnusLogger.error(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AlgorithmicBottlenecksCliLauncher.class.getSimpleName(), cliOptions); } catch (Exception e) { TurnusLogger.error(e.getMessage()); } }
From source file:de.prozesskraft.ptest.Launch.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w ww. j av a 2 s . c o m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option ospl = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory] directory with sample input data") // .isRequired() .create("spl"); Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory, default: .] directory where the test will be performed") // .isRequired() .create("instancedir"); Option ocall = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory, default: random call in spl-directory] file with call-string") // .isRequired() .create("call"); Option oaltapp = OptionBuilder.withArgName("STRING").hasArg() .withDescription( "[optional] alternative app. this String replaces the first line of the .call-file.") // .isRequired() .create("altapp"); Option oaddopt = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] add an option to the call.") // .isRequired() .create("addopt"); Option onolaunch = new Option("nolaunch", "only create instance directory, copy all spl files, but do NOT launch the process"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ospl); options.addOption(oinstancedir); options.addOption(ocall); options.addOption(oaltapp); options.addOption(oaddopt); options.addOption(onolaunch); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("launch", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ boolean error = false; String spl = null; String instancedir = null; String call = null; String altapp = null; ArrayList<String> addopt = new ArrayList<String>(); // spl initialisieren if (commandline.hasOption("spl")) { spl = commandline.getOptionValue("spl"); } else { System.err.println("option -spl is mandatory"); error = true; } // instancedir initialisieren if (commandline.hasOption("instancedir")) { instancedir = commandline.getOptionValue("instancedir"); } else { instancedir = System.getProperty("user.dir"); } // call initialisieren if (commandline.hasOption("call")) { call = commandline.getOptionValue("call"); } // altapp initialisieren if (commandline.hasOption("altapp")) { altapp = commandline.getOptionValue("altapp"); } // addopt initialisieren if (commandline.hasOption("addopt")) { for (String actString : commandline.getOptionValues("addopt")) { addopt.add(actString); } } // wenn fehler, dann exit if (error) { exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // das erste spl-objekt geben lassen Spl actSpl = new Splset(spl).getSpl().get(0); // den call, result und altapp ueberschreiben actSpl.setName("default"); if (call != null) { actSpl.setCall(new java.io.File(call)); } if (actSpl.getCall() == null) { System.err.println("error: no call information found"); System.exit(1); } if (altapp != null) { actSpl.setAltapp(altapp); } if (addopt.size() > 0) { actSpl.setAddopt(addopt); } actSpl.setResult(null); // das instancedir erstellen java.io.File actSplInstanceDir = new java.io.File(instancedir); System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath()); actSplInstanceDir.mkdirs(); // Inputdaten in das InstanceDir exportieren actSpl.exportInput(actSplInstanceDir); // exit, wenn --nolaunch if (commandline.hasOption("nolaunch")) { System.err.println("info: exiting, because of -nolaunch"); System.exit(0); } // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht) String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log"; String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt"; String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt"; String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid"; // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden // syscall ersetzt die zeichensequenz wieder zurueck in ein " " ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList(); ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>(); for (String actString : callFuerSyscall) { callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%")); } try { // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory' ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(ini.get("apps", "pkraft-syscall").split(" "))); // die sonstigen argumente hinzufuegen processSyscallWithArgs.add("-call"); processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen)); // processSyscallWithArgs.add("\""+call+"\""); processSyscallWithArgs.add("-stdout"); processSyscallWithArgs.add(AbsStdout); processSyscallWithArgs.add("-stderr"); processSyscallWithArgs.add(AbsStderr); processSyscallWithArgs.add("-pid"); processSyscallWithArgs.add(AbsPid); processSyscallWithArgs.add("-mylog"); processSyscallWithArgs.add(AbsLogSyscallWrapper); processSyscallWithArgs.add("-maxrun"); processSyscallWithArgs.add("" + 3000); // erstellen prozessbuilder ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // erweitern des PATHs um den prozesseigenen path // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // log("debug", "$PATH="+path); // path = this.parent.getAbsPath()+":"+path; // env.put("PATH", path); // log("info", "path: "+path); // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll) java.io.File directory = new java.io.File(instancedir); System.err.println("info: setting execution directory to: " + directory.getCanonicalPath()); pb.directory(directory); // zum debuggen ein paar ausgaben // java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt"); // p1.waitFor(); // java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt"); // p2.waitFor(); // java.lang.Process pro = Runtime.getRuntime().exec("nautilus"); // java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()])); // p3.waitFor(); System.err.println("info: calling: " + pb.command()); // starten des prozesses java.lang.Process sysproc = pb.start(); // einfangen der stdout- und stderr des subprozesses InputStream is_stdout = sysproc.getInputStream(); InputStream is_stderr = sysproc.getErrorStream(); // Send your InputStream to an InputStreamReader: InputStreamReader isr_stdout = new InputStreamReader(is_stdout); InputStreamReader isr_stderr = new InputStreamReader(is_stderr); // That needs to go to a BufferedReader: BufferedReader br_stdout = new BufferedReader(isr_stdout); BufferedReader br_stderr = new BufferedReader(isr_stderr); // // oeffnen der OutputStreams zu den Ausgabedateien // FileWriter fw_stdout = new FileWriter(sStdout); // FileWriter fw_stderr = new FileWriter(sStderr); // zeilenweise in die files schreiben String line_out = new String(); String line_err = new String(); while (br_stdout.readLine() != null) { } // while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null)) // { // if (!(line_out == null)) // { // System.out.println(line_out); // System.out.flush(); // } // if (!(line_err == null)) // { // System.err.println(line_err); // System.err.flush(); // } // } int exitValue = sysproc.waitFor(); // fw_stdout.close(); // fw_stderr.close(); System.err.println("exitvalue: " + exitValue); sysproc.destroy(); System.exit(exitValue); // alternativer aufruf // java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " ")); // log("info", "call executed. pid="+sysproc.hashCode()); // wait 2 seconds for becoming the pid-file visible // Thread.sleep(2000); // int exitValue = sysproc.waitFor(); // // der prozess soll bis laengstens // if(exitValue != 0) // { // System.err.println("error: call returned a value indicating an error: "+exitValue); // } // else // { // System.err.println("info: call returned value: "+exitValue); // } // System.err.println("info: "+new Date().toString()); // System.err.println("info: bye"); // // sysproc.destroy(); // // System.exit(sysproc.exitValue()); } catch (Exception e2) { System.err.println("error: " + e2.getMessage()); System.exit(1); } }
From source file:com.algollabs.rgx.java
public static void main(String[] args) throws Exception { CommandLine cli;/*from ww w . j a v a 2s . c om*/ // create the command line parser CommandLineParser parser = new GnuParser(); // create the Options options.addOption("h", "help", false, "print this help message"); options.addOption("d", "daemonize", false, "run rgx:Java as a daemon"); options.addOption(OptionBuilder.withLongOpt("pattern") .withDescription("Java regular expression raw pattern").hasArg().withArgName("PATTERN").create()); options.addOption(OptionBuilder.withLongOpt("subject") .withDescription("subject to test the pattern against").hasArg().withArgName("SUBJECT").create()); options.addOption( OptionBuilder.withLongOpt("interface").withDescription("the interface to bind to when daemonized") .hasArg().withArgName("INTERFACE").create()); options.addOption(OptionBuilder.withLongOpt("port").withDescription("the port to bind to when daemonized") .hasArg().withArgName("PORT").create()); try { // parse the command line arguments cli = parser.parse(options, args); } catch (ParseException exp) { System.out.println("Unexpected exception:" + exp.getMessage()); return; } if (cli.hasOption("help")) { printHelp(); return; } if (cli.hasOption("daemonize")) { String port = "9400"; String host = "0.0.0.0"; if (cli.hasOption("port")) { port = cli.getOptionValue("port"); } if (cli.hasOption("interface")) { host = cli.getOptionValue("interface"); } Container container = new rgx(); Server server = new ContainerServer(container); Connection connection = new SocketConnection(server); SocketAddress address = new InetSocketAddress(host, Integer.parseInt(port)); connection.connect(address); System.out.println("Accepting requests on " + host + ":" + port); } else { String ptrn = null; String subj = null; String flags = null; if (!cli.hasOption("pattern") || !cli.hasOption("subject")) { printHelp(); return; } ptrn = cli.getOptionValue("pattern"); subj = cli.getOptionValue("subject"); if (cli.hasOption("flags")) flags = cli.getOptionValue("flags"); System.out.println(new Construct(ptrn, subj, flags, false).test()); } }
From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java
/** * Password Manager entry point//from w ww .j a v a 2 s. co m * * @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:de.prozesskraft.ptest.Fingerprint.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w w w. j av a2 s . co m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option opath = OptionBuilder.withArgName("PATH").hasArg() .withDescription( "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.") // .isRequired() .create("path"); Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription( "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]") // .isRequired() .create("sizetol"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes") // .isRequired() .create("md5"); Option oignore = OptionBuilder.withArgName("STRING").hasArgs() .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint") // .isRequired() .create("ignore"); Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint") // .isRequired() .create("ignorefile"); Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file") // .isRequired() .create("output"); Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(opath); options.addOption(osizetol); options.addOption(omd5); options.addOption(oignore); options.addOption(oignorefile); options.addOption(ooutput); options.addOption(of); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fingerprint", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ String path = ""; String sizetol = ""; boolean md5 = false; Float sizetolFloat = null; String output = ""; java.io.File ignorefile = null; ArrayList<String> ignore = new ArrayList<String>(); if (!(commandline.hasOption("path"))) { System.err.println("setting default for -path=."); path = "."; } else { path = commandline.getOptionValue("path"); } if (!(commandline.hasOption("sizetol"))) { System.err.println("setting default for -sizetol=0.02"); sizetol = "0.02"; sizetolFloat = 0.02F; } else { sizetol = commandline.getOptionValue("sizetol"); sizetolFloat = Float.parseFloat(sizetol); if ((sizetolFloat > 1) || (sizetolFloat < 0)) { System.err.println("use only values >=0.0 and <1.0 for -sizetol"); System.exit(1); } } if (!(commandline.hasOption("md5"))) { System.err.println("setting default for -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); System.exit(1); } if (commandline.hasOption("ignore")) { ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore"))); } if (commandline.hasOption("ignorefile")) { ignorefile = new java.io.File(commandline.getOptionValue("ignorefile")); if (!ignorefile.exists()) { System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath()); } } if (!(commandline.hasOption("output"))) { System.err.println("setting default for -output=" + path + "/fingerprint.xml"); output = path + "/fingerprint.xml"; } else { output = commandline.getOptionValue("output"); } // wenn output bereits existiert -> abbruch java.io.File outputFile = new File(output); if (outputFile.exists()) { if (commandline.hasOption("f")) { outputFile.delete(); } else { System.err .println("error: output file (" + output + ") already exists. use -f to force overwrite."); System.exit(1); } } // if ( !( commandline.hasOption("output")) ) // { // System.err.println("option -output is mandatory."); // exiter(); // } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Dir dir = new Dir(); dir.setBasepath(path); dir.setOutfilexml(output); // ignore file in ein Array lesen if ((ignorefile != null) && (ignorefile.exists())) { Scanner sc = new Scanner(ignorefile); while (sc.hasNextLine()) { ignore.add(sc.nextLine()); } sc.close(); } // // autoignore hinzufuegen // String autoIgnoreString = ini.get("autoignore", "autoignore"); // ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(","))); // // debug // System.out.println("ignorefile content:"); // for(String actLine : ignore) // { // System.out.println("line: "+actLine); // } try { dir.genFingerprint(sizetolFloat, md5, ignore); } catch (NullPointerException e) { System.err.println("file/dir does not exist " + path); e.printStackTrace(); exiter(); } catch (IOException e) { e.printStackTrace(); exiter(); } System.out.println("writing to file: " + dir.getOutfilexml()); dir.writeXml(); }
From source file:de.prozesskraft.pkraft.Manager.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, CloneNotSupportedException { // try//ww w . ja va 2 s . co m // { // if (args.length != 1) // { // System.out.println("Please specify Inputfile and Outputfile (prozessinstanz.lri)"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify procesdefinition.lrd and processinstance.lri\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Manager.class) + "/" + "../etc/pkraft-manager.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); exit = true; } /*---------------------------- create boolean options ----------------------------*/ Option help = new Option("help", "print this message"); Option v = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option instance = OptionBuilder.withArgName("instance").hasArg() .withDescription("[mandatory] process instance file") // .isRequired() .create("instance"); Option stop = OptionBuilder.withArgName("stop") // .hasArg() .withDescription("[optional] stops a running manager for given instance") // .isRequired() .create("stop"); Option kill = OptionBuilder.withArgName("kill") // .hasArg() .withDescription("[optional] kills all applications that have been started by steps") // .isRequired() .create("kill"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(help); options.addOption(v); options.addOption(instance); options.addOption(stop); options.addOption(kill); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments line = parser.parse(options, args); } // catch ( ParseException exp ) catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("manager", options); exit = true; System.exit(0); } else if (line.hasOption("v")) { System.out.println("author: info@prozesskraft.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); exit = true; System.exit(0); } else if (!(line.hasOption("instance"))) { exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { exit = true; System.exit(1); } /*---------------------------- business logic ----------------------------*/ Process actualProcess = null; try { Process p1 = new Process(); // die dauer des loops festlegen. Dies soll kein standardwert sein, da sonst bei vielen subprozessen die Prozessorlast stark oszilliert // zwischen 12 und 17 sekunden // Random rand = new Random(System.currentTimeMillis()); // int loop_period_seconds = rand.nextInt((17 - 12) + 1) + 12; // System.err.println("loop period is randomly set to: "+loop_period_seconds); fileBinary = new java.io.File(line.getOptionValue("instance")); String pathBinary = ""; if (fileBinary.exists()) { pathBinary = fileBinary.getAbsolutePath(); System.err.println("file does exist: " + pathBinary); } else { System.err.println("file does not exist: " + fileBinary.getAbsolutePath()); exiter(); } if (line.hasOption("stop") || line.hasOption("kill")) { p1.setInfilebinary(pathBinary); Process p2 = p1.readBinary(); p2.log("debug", "setting new manager-Id (0) to signal actual manager (" + p2.getManagerid() + ") that he is no longer in charge "); System.err.println("info: stopping instance"); System.err.println("debug: setting new manager-Id (0) to signal actual manager (" + p2.getManagerid() + ") that he is no longer in charge "); p2.setManagerid(0); p2.run = false; p2.setOutfilebinary(pathBinary); p2.writeBinary(); if (line.hasOption("kill")) { System.err.println("info: killing all steps of instance"); String returnStringOfKills = p2.kill(); System.err.println("info: killing returns: " + returnStringOfKills); } boolean pradar = (!(p2.isWrapper())); // pradar checkout if (pradar) { pradarAttend(p2.getRootdir() + "/process.pmb"); // pradarCheckout(p2.getId(), p2.getName(), "0"); } exit = true; System.exit(0); } startZyklischerThread(0); // prozessinstanz einlesen p1.setInfilebinary(pathBinary); managerid = p1.genManagerid(); Process p2; p2 = p1.readBinary(); // beim aufruf des programms wird erstmal die instanz occupiert p2.setManagerid(managerid); System.err.println("debug: manager " + managerid + ": occupying instance."); p2.log("info", "manager " + managerid + ": occupying instance."); p2.log("debug", "manager " + managerid + ": setting new manager-id to signal other running managers that they are not longer needed."); p2.log("debug", "manager " + managerid + ": setting binary file for input to: " + pathBinary); // System.out.println("setting binary file for input to: "+line.getOptionValue("instance")); p2.log("debug", "manager " + managerid + ": reading binary file: " + pathBinary); p2.setInfilebinary(pathBinary); p2.setOutfilebinary(pathBinary); p2.log("debug", "manager " + managerid + ": setting binary file for output: " + pathBinary); // instanz auf platte schreiben (um anderen managern zu signalisieren, dass sie nicht mehr gebraucht werden // System.out.println("setting manager-id to: "+managerid); p2.log("debug", "manager " + managerid + ": writing process to binary file to occupy instance."); // wenn es kein wrapper-prozess ist, dann soll die komunikation mit pradar vom manager uebernommen werden boolean pradar = (!(p2.isWrapper())); System.err.println("debug: setting instance to run"); p2.run = true; // pradar checkin if (pradar && p2.run && p2.touchInMillis == 0) { pradarAttend(p2.getRootdir() + "/process.pmb"); // p2.log("debug", "pradar-checkin id="+p2.getId()+", process="+p2.getName()+", processversion="+p2.getVersion()+", id2="+p2.getId2()+", parentid="+p2.getParentid()+", resource="+p2.getRootdir()+"/process.pmb"); // pradarCheckin(p2.getId(), p2.getName(), p2.getVersion(), p2.getId2(), p2.getParentid(), getPid(), p2.getRootdir()+"/process.pmb"); } System.err.println("debug: writing binary"); p2.writeBinary(); // process weiter schubsen pushProcessAsFarAsPossible(pathBinary, false); // try // { // // der thread soll so lange schlafen, wie die periode lang ist. die schlafdauer wird mit der anzahl multipliziert, wie oft das loadAverage zu hoch war (max 5) // int faktorForPeriod = Math.min(10, p2.counterLoadAverageTooHigh + 1); // // int secondsToSleep = loop_period_seconds * faktorForPeriod; // System.err.println("debug: sleeping for " + secondsToSleep + " seconds"); // // int millisecondsToSleep = secondsToSleep*1000; // System.err.println("debug: sleeping for " + millisecondsToSleep + " milliseconds"); // // Thread.sleep(millisecondsToSleep); // } // catch (InterruptedException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // // // ausgabe in das debugLogFile // exiterException(actualProcess.getOutfilebinary(), e); // } } catch (Exception e) { if (actualProcess != null) { actualProcess.log("fatal", e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); updateFile(actualProcess); e.printStackTrace(); // ausgabe in das debugLogFile exiterException(actualProcess.getOutfilebinary(), e); } exit = true; System.exit(10); } }
From source file:com.github.brandtg.switchboard.FileLogAggregator.java
/** Main. */ public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption("h", "help", false, "Prints help message"); opts.addOption("f", "file", true, "File to output aggregated logs to"); opts.addOption("s", "separator", true, "Line separator in log"); CommandLine cli = new GnuParser().parse(opts, args); if (cli.getArgs().length == 0 || cli.hasOption("help")) { new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts); System.exit(1);/*from w ww . jav a 2s . c o m*/ } // Parse sources Set<InetSocketAddress> sources = new HashSet<>(); for (int i = 0; i < cli.getArgs().length; i++) { String[] tokens = cli.getArgs()[i].split(":"); sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1]))); } // Parse output stream OutputStream outputStream; if (cli.hasOption("file")) { outputStream = new FileOutputStream(cli.getOptionValue("file")); } else { outputStream = System.out; } // Separator String separator = cli.getOptionValue("separator", "\n"); if (separator.length() != 1) { throw new IllegalArgumentException("Separator must only be 1 character"); } final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0), outputStream); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { fileLogAggregator.stop(); } catch (Exception e) { LOG.error("Error when stopping log aggregator", e); } } }); fileLogAggregator.start(); }
From source file:com.basistech.ninja.Train.java
/** * Command line interface to train a model. * * <pre>/*from w w w .jav a 2s . co m*/ * usage: Train [options] * --batch-size <arg> batch size (default = 10) * --epochs <arg> epochs (default = 5) * --examples <arg> input examples file (required) * --layer-sizes <arg> layer sizes, including input/output, e.g. 3 4 2 (required) * --learning-rate <arg> learning-rate (default = 0.7) * --model <arg> output model file (required) * </pre> * * @param args command line arguments * @throws IOException */ public static void main(String[] args) throws IOException { String defaultBatchSize = "10"; String deafaultEpochs = "5"; String defaultLearningRate = "0.7"; Options options = new Options(); Option option; option = new Option(null, "examples", true, "input examples file (required)"); option.setRequired(true); options.addOption(option); option = new Option(null, "model", true, "output model file (required)"); option.setRequired(true); options.addOption(option); option = new Option(null, "layer-sizes", true, "layer sizes, including input/output, e.g. 3 4 2 (required)"); option.setRequired(true); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); option = new Option(null, "batch-size", true, String.format("batch size (default = %s)", defaultBatchSize)); options.addOption(option); option = new Option(null, "epochs", true, String.format("epochs (default = %s)", deafaultEpochs)); options.addOption(option); option = new Option(null, "learning-rate", true, String.format("learning-rate (default = %s)", defaultLearningRate)); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine cmdline = null; try { cmdline = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.err.println(e.getMessage()); usage(options); System.exit(1); } String[] remaining = cmdline.getArgs(); if (remaining == null) { usage(options); System.exit(1); } List<Integer> layerSizes = Lists.newArrayList(); for (String s : cmdline.getOptionValues("layer-sizes")) { layerSizes.add(Integer.parseInt(s)); } File examplesFile = new File(cmdline.getOptionValue("examples")); Train that = new Train(layerSizes, examplesFile); int batchSize = Integer.parseInt(cmdline.getOptionValue("batch-size", defaultBatchSize)); int epochs = Integer.parseInt(cmdline.getOptionValue("epochs", deafaultEpochs)); double learningRate = Double.parseDouble(cmdline.getOptionValue("learning-rate", defaultLearningRate)); File modelFile = new File(cmdline.getOptionValue("model")); that.train(batchSize, epochs, learningRate, modelFile); }
From source file:jamm.tools.JammCleaner.java
/** * Our main method/*w w w. j a v a 2 s. c o m*/ * * @param argv command line arguments */ public static final void main(String argv[]) { Options opts = getOptions(); CommandLine cmdl = null; Parser parser = new GnuParser(); boolean sane = true; BasicConfigurator.configure(); try { cmdl = parser.parse(opts, argv); } catch (MissingOptionException e) { LOG.error("Missing required options." + e.toString()); sane = false; } catch (MissingArgumentException e) { LOG.error("Missing required Arguments." + e.toString()); sane = false; } catch (ParseException e) { LOG.error("Error parsing command line", e); sane = false; } // Load properties first loadProperties(); // Allow command line args to override properties file parseArgs(opts, cmdl); sane = sane && sanityCheck(); if (!sane) { printHelp(opts); System.exit(1); } AccountCleaner ac = new AccountCleaner(); ac.cleanUp(); DomainCleaner dc = new DomainCleaner(); dc.cleanUp(); }