List of usage examples for org.apache.commons.cli HelpFormatter printHelp
public void printHelp(String cmdLineSyntax, Options options)
options
with the specified command line syntax. From source file:com.github.s4ke.moar.cli.Main.java
public static void main(String[] args) throws ParseException, IOException { // create Options object Options options = new Options(); options.addOption("rf", true, "file containing the regexes to test against (multiple regexes are separated by one empty line)"); options.addOption("r", true, "regex to test against"); options.addOption("mf", true, "file/folder to read the MOA from"); options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)"); options.addOption("sf", true, "file to read the input string(s) from"); options.addOption("s", true, "string to test the MOA/Regex against"); options.addOption("m", false, "multiline matching mode (search in string for regex)"); options.addOption("ls", false, "treat every line of the input string file as one string"); options.addOption("t", false, "trim lines if -ls is set"); options.addOption("d", false, "only do determinism check"); options.addOption("help", false, "prints this dialog"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("moar-cli", options); return;/* ww w . j a va 2 s. com*/ } List<String> patternNames = new ArrayList<>(); List<MoaPattern> patterns = new ArrayList<>(); List<String> stringsToCheck = new ArrayList<>(); if (cmd.hasOption("r")) { String regexStr = cmd.getOptionValue("r"); try { patterns.add(MoaPattern.compile(regexStr)); patternNames.add(regexStr); } catch (Exception e) { System.out.println(e.getMessage()); } } if (cmd.hasOption("rf")) { String fileName = cmd.getOptionValue("rf"); List<String> regexFileContents = readFileContents(new File(fileName)); int emptyLineCountAfterRegex = 0; StringBuilder regexStr = new StringBuilder(); for (String line : regexFileContents) { if (emptyLineCountAfterRegex >= 1) { if (regexStr.length() > 0) { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } regexStr.setLength(0); emptyLineCountAfterRegex = 0; } if (line.trim().equals("")) { if (regexStr.length() > 0) { ++emptyLineCountAfterRegex; } } else { regexStr.append(line); } } if (regexStr.length() > 0) { try { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } catch (Exception e) { System.out.println(e.getMessage()); return; } regexStr.setLength(0); } } if (cmd.hasOption("mf")) { String fileName = cmd.getOptionValue("mf"); File file = new File(fileName); if (file.isDirectory()) { System.out.println(fileName + " is a directory, using all *.moar files as patterns"); File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar")); for (File moar : moarFiles) { String jsonString = readWholeFile(moar); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(moar.getAbsolutePath()); } } else { System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)"); String jsonString = readWholeFile(file); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(fileName); } } if (cmd.hasOption("s")) { String str = cmd.getOptionValue("s"); stringsToCheck.add(str); } if (cmd.hasOption("sf")) { boolean treatLineAsString = cmd.hasOption("ls"); boolean trim = cmd.hasOption("t"); String fileName = cmd.getOptionValue("sf"); StringBuilder stringBuilder = new StringBuilder(); boolean firstLine = true; for (String str : readFileContents(new File(fileName))) { if (treatLineAsString) { if (trim) { str = str.trim(); if (str.length() == 0) { continue; } } stringsToCheck.add(str); } else { if (!firstLine) { stringBuilder.append("\n"); } if (firstLine) { firstLine = false; } stringBuilder.append(str); } } if (!treatLineAsString) { stringsToCheck.add(stringBuilder.toString()); } } if (cmd.hasOption("d")) { //at this point we have already built the Patterns //so just give the user a short note. System.out.println("All Regexes seem to be deterministic."); return; } if (patterns.size() == 0) { System.out.println("no patterns to check"); return; } if (cmd.hasOption("mo")) { String folder = cmd.getOptionValue("mo"); File folderFile = new File(folder); if (!folderFile.exists()) { System.out.println(folder + " does not exist. creating..."); if (!folderFile.mkdirs()) { System.out.println("folder " + folder + " could not be created"); } } int cnt = 0; for (MoaPattern pattern : patterns) { String patternAsJSON = MoarJSONSerializer.toJSON(pattern); try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) { writer.write(patternAsJSON); } } System.out.println("stored " + cnt + " patterns in " + folder); } if (stringsToCheck.size() == 0) { System.out.println("no strings to check"); return; } boolean multiline = cmd.hasOption("m"); for (String string : stringsToCheck) { int curPattern = 0; for (MoaPattern pattern : patterns) { MoaMatcher matcher = pattern.matcher(string); if (!multiline) { if (matcher.matches()) { System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\""); } else { System.out.println( "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\""); } } else { StringBuilder buffer = new StringBuilder(string); int additionalCharsPerMatch = ("<match>" + "</match>").length(); int matchCount = 0; while (matcher.nextMatch()) { buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch, matcher.getEnd() + matchCount * additionalCharsPerMatch, "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>"); ++matchCount; } System.out.println(buffer.toString()); } } ++curPattern; } }
From source file:com.addthis.bark.ZkCmdLine.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "something helpful."); options.addOption("z", "zk", true, "zk servers,port"); options.addOption("c", "chroot", true, "chroot"); options.addOption("n", "znode", true, "znode"); options.addOption("d", "dir", true, "directory root"); options.addOption("p", "put-data", true, "directory root"); // for copying options.addOption("", "to-zk", true, "zk servers,port"); options.addOption("", "to-chroot", true, "chroot"); options.addOption("", "to-znode", true, "znode"); CommandLineParser parser = new PosixParser(); CommandLine cmdline = null;/*w w w. j a va 2 s.c o m*/ try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(0); } HelpFormatter formatter = new HelpFormatter(); if (cmdline.hasOption("help") || cmdline.getArgList().size() < 1) { System.out.println("commands: get jclean jcleanrecur kids grandkids"); formatter.printHelp("ZkCmdLine", options); System.exit(0); } ZkCmdLine zkcl = new ZkCmdLine(cmdline); zkcl.runCmd((String) cmdline.getArgList().get(0)); }
From source file:escada.tpc.common.clients.jmx.ClientEmulationStartup.java
public static void main(String args[]) { // create Options object Options options = new Options(); // add clients option options.addOption("clients", true, "Number of clients concurrently accessing the database."); options.addOption("frag", true, "It shifts the clients in order to access different warehouses."); options.addOption("hostId", true, "Host identifier, allow to have statistics per host."); options.addOption("dbConnectionString", true, "Database JDBC url."); try {/* w w w.jav a 2s .co m*/ CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); ClientEmulationStartup c = new ClientEmulationStartup(); String clients = cmd.getOptionValue("clients"); if (clients != null) { c.getWorkloadResources().setClients(new Integer(clients)); } String frag = cmd.getOptionValue("frag"); if (frag != null) { c.getWorkloadResources().setFrag(new Integer(frag)); } String hostId = cmd.getOptionValue("hostId"); if (hostId != null) { c.getWorkloadResources().setHostId(new Integer(hostId)); } String dbConnectionString = cmd.getOptionValue("dbConnectionString"); if (dbConnectionString != null) { c.getDatabaseResources().setConnectionString(dbConnectionString); } c.start(true); } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ClientEmulationStartup", options); } catch (NumberFormatException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ClientEmulationStartup", options); } catch (Exception ex) { Thread.dumpStack(); System.exit(-1); } }
From source file:apps.quantification.LearnQuantificationSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnQuantificationSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_learn> <path to svm_perf_classify> <trainingIndexDirectory> <outputDirectory>"; Options options = new Options(); OptionBuilder.withArgName("f"); OptionBuilder.withDescription("Number of folds"); OptionBuilder.withLongOpt("f"); OptionBuilder.isRequired(true);/*from www .ja va 2s . c om*/ OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("l"); OptionBuilder.withDescription("The loss function to optimize (default 2):\n" + " 0 Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n" + " 1 F1: 100 minus the F1-score in percent.\n" + " 2 Errorrate: Percentage of errors in prediction vector.\n" + " 3 Prec/Rec Breakeven: 100 minus PRBEP in percent.\n" + " 4 Prec@p: 100 minus precision at p in percent.\n" + " 5 Rec@p: 100 minus recall at p in percent.\n" + " 10 ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea)."); OptionBuilder.withLongOpt("l"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("w"); OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n" + " 0: n-slack algorithm described in [2]\n" + " 1: n-slack algorithm with shrinking heuristic\n" + " 2: 1-slack algorithm (primal) described in [5]\n" + " 3: 1-slack algorithm (dual) described in [5]\n" + " 4: 1-slack algorithm (dual) with constraint cache [5]\n" + " 9: custom algorithm in svm_struct_learn_custom.c"); OptionBuilder.withLongOpt("w"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("p"); OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)"); OptionBuilder.withLongOpt("p"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfLearnerCustomizer classificationLearnerCustomizer = null; SvmPerfClassifierCustomizer classificationCustomizer = null; int folds = -1; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); classificationCustomizer = new SvmPerfClassifierCustomizer(remainingArgs[1]); folds = Integer.parseInt(line.getOptionValue("f")); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("w")) classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w"))); if (line.hasOption("p")) classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p"))); if (line.hasOption("l")) classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l"))); if (line.hasOption("v")) classificationLearnerCustomizer.printSvmPerfOutput(true); if (line.hasOption("s")) classificationLearnerCustomizer.setDeleteTrainingFiles(false); if (line.hasOption("t")) { classificationLearnerCustomizer.setTempPath(line.getOptionValue("t")); classificationCustomizer.setTempPath(line.getOptionValue("t")); } } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } assert (classificationLearnerCustomizer != null); if (remainingArgs.length != 4) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[2]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String outputPath = remainingArgs[3]; SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false); fssm.open(); IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers"); IOperationStatusListener status = new IOperationStatusListener() { @Override public void operationStatus(double percentage) { progressBar.signal((int) percentage); } }; QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner, classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY, new LogisticFunction(), status); IQuantifier[] quantifiers = quantificationLearner.learn(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); IDataManager classifierDataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify")); String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-" + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL(); if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5) description += "_P-" + classificationLearnerCustomizer.getP(); if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0) description += "_" + classificationLearnerCustomizer.getAdditionalParameters(); String quantifierPrefix = indexName + "_Quantifier-" + folds + description; FileSystemStorageManager fssmo = new FileSystemStorageManager( outputPath + File.separatorChar + quantifierPrefix, true); fssmo.open(); QuantificationLearner.write(quantifiers, fssmo, classifierDataManager); fssmo.close(); BufferedWriter bfs = new BufferedWriter( new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt")); TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs(); TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs(); ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = training.getCategoryDB().getCategoryName(cat); ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
public static void main(String[] args) { Options options = new Options(); options.addOption(Option.builder("Xfu").longOpt("Xforceupdate").desc("Force the patching process").build()); options.addOption(Option.builder("Xh").longOpt("Xhelp").desc("Help!").build()); CommandLineParser parser = new DefaultParser(); try {/* w ww . j a v a2 s. c o m*/ CommandLine commandLine = parser.parse(options, args, true); if (commandLine.hasOption("Xhelp")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar bootstrapper.jar", options); } else if (commandLine.hasOption("Xforceupdate")) { forceUpdate(); } else { // boolean shouldStart = true; // ServerSocket socket = null; // try { // socket = new ServerSocket(21354); // } catch (IOException e) { // shouldStart = false; // } finally { // if (socket != null) { // socket.close(); // } // } // if (shouldStart) { String[] forward = commandLine.getArgs(); HeliosData heliosData = loadHelios(); System.out.println("Running Helios version " + heliosData.buildNumber); System.getProperties().put("com.heliosdecompiler.buildNumber", String.valueOf(heliosData.buildNumber)); System.getProperties().put("com.heliosdecompiler.version", String.valueOf(heliosData.version)); System.getProperties().put("com.heliosdecompiler.args", args); new Thread(new UpdaterTask(heliosData.buildNumber)).start(); ClassLoader classLoader = new URLClassLoader(new URL[] { IMPL_FILE.toURI().toURL() }, null); Class<?> bootloader = Class.forName(heliosData.mainClass, false, classLoader); bootloader.getMethod("main", String[].class).invoke(null, new Object[] { forward }); // } else { // String message = Arrays.asList(forward).stream().collect(Collectors.joining(" ")); // Socket clientSocket = new Socket("127.0.0.1", 21354); // clientSocket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); // clientSocket.getOutputStream().close(); // clientSocket.close(); // } } } catch (Throwable t) { displayError(t); System.exit(1); } }
From source file:com.shoddytcg.server.GameServer.java
/** * If you don't know what this method does, you clearly don't know enough Java to be working on this. * @param args// w w w . jav a 2s. c o m */ public static void main(String[] args) { /* * Pipe errors to a file */ try { PrintStream p = new PrintStream(new File("./errors.txt")); System.setErr(p); } catch (Exception e) { e.printStackTrace(); } /* * Server settings */ Options options = new Options(); options.addOption("s", "settings", true, "Can be low, medium, or high."); options.addOption("p", "players", true, "Sets the max number of players."); options.addOption("ng", "nogui", false, "Starts server in headless mode."); options.addOption("ar", "autorun", false, "Runs without asking a single question."); options.addOption("h", "help", false, "Shows this menu."); if (args.length > 0) { CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); /* * The following sets the server's settings based on the * computing ability of the server specified by the server owner. */ if (line.hasOption("settings")) { String settings = line.getOptionValue("settings"); if (settings.equalsIgnoreCase("low")) { m_movementThreads = 4; } else if (settings.equalsIgnoreCase("medium")) { m_movementThreads = 8; } else if (settings.equalsIgnoreCase("high")) { m_movementThreads = 12; } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } } else { System.err.println("Server requires a settings parameter"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); System.exit(0); } if (line.hasOption("players")) { m_maxPlayers = Integer.parseInt(line.getOptionValue("players")); if (m_maxPlayers == 0 || m_maxPlayers == -1) m_maxPlayers = 99999; } else { System.err.println("WARNING: No maximum player count provided. Will default to 500 players."); m_maxPlayers = 500; } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } /* * Create the server gui */ @SuppressWarnings("unused") GameServer gs; if (line.hasOption("nogui")) { if (line.hasOption("autorun")) gs = new GameServer(true); else gs = new GameServer(false); } else { if (line.hasOption("autorun")) System.out.println("autorun doesn't work with GUI"); gs = new GameServer(false); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java GameServer [param] <args>", options); } } else { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); System.err.println("Server requires a settings parameter"); formatter.printHelp("java GameServer [param] <args>", options); } }
From source file:de.prozesskraft.pkraft.Waitinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file/*from w w w.j ava2 s. c o m*/ ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/" + "../etc/pkraft-waitinstance.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 oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'") // .isRequired() .create("instance"); Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.") // .isRequired() .create("scandir"); Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription( "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.") // .isRequired() .create("maxrun"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oscandir); options.addOption(omaxrun); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("waitinstance", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ Integer maxrun = new Integer(4320); String pathInstance = null; String pathScandir = null; // instance & scandir if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) { System.err.println("one of the options -instance/-scandir is mandatory"); exiter(); } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) { System.err.println("both options -instance/-scandir are not allowed"); exiter(); } else if (commandline.hasOption("instance")) { pathInstance = commandline.getOptionValue("instance"); } else if (commandline.hasOption("scandir")) { pathScandir = commandline.getOptionValue("scandir"); } // maxrun if (commandline.hasOption("maxrun")) { maxrun = new Integer(commandline.getOptionValue("maxrun")); } /*---------------------------- 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 ----------------------------*/ // scannen nach dem ersten process.pmb if ((pathScandir != null) && (pathInstance == null)) { String[] allBinariesOfScanDir = getProcessBinaries(pathScandir); if (allBinariesOfScanDir.length == 0) { System.err.println("no instance (process.pmb) found in directory tree " + pathScandir); exiter(); } else { pathInstance = allBinariesOfScanDir[0]; System.err.println("found instance: " + pathInstance); } } // ueberpruefen ob instance file existiert java.io.File fileInstance = new java.io.File(pathInstance); if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } if (!fileInstance.isFile()) { System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath()); exiter(); } // zeitpunkt wenn spaetestens beendet werden soll long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000); // logging System.err.println("waiting for instance: " + fileInstance.getAbsolutePath()); System.err.println("checking its status every 5 minutes"); System.err.println("now is: " + new Timestamp(startInMillis).toString()); System.err.println("maxrun till: " + new Timestamp(runTill).toString()); // instanz einlesen Process p1 = new Process(); p1.setInfilebinary(fileInstance.getAbsolutePath()); Process p2 = p1.readBinary(); // schleife, die prozess einliest und ueberprueft ob er noch laeuft while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) { // logging System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus()); // 5 minuten schlafen: 300000 millis try { Thread.sleep(300000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage) if (System.currentTimeMillis() > runTill) { System.err .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis())); System.exit(2); } // den prozess frisch einlesen p2 = p1.readBinary(); } System.err.println("exiting because instance status is: " + p2.getStatus()); System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString()); System.exit(0); }
From source file:it.anyplace.sync.client.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("C", "set-config", true, "set config file for s-client"); options.addOption("c", "config", false, "dump config"); options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers"); options.addOption("q", "query", true, "query directory server for device id"); options.addOption("d", "discovery", true, "discovery local network for device id"); options.addOption("p", "pull", true, "pull file from network"); options.addOption("P", "push", true, "push file to network"); options.addOption("o", "output", true, "set output file/directory"); options.addOption("i", "input", true, "set input file/directory"); options.addOption("lp", "list-peers", false, "list peer addresses"); options.addOption("a", "address", true, "use this peer addresses"); options.addOption("L", "list-remote", false, "list folder (root) content from network"); options.addOption("I", "list-info", false, "dump folder info from network"); options.addOption("li", "list-info", false, "list folder info from local db"); // options.addOption("l", "list-local", false, "list folder content from local (saved) index"); options.addOption("s", "search", true, "search local index for <term>"); options.addOption("D", "delete", true, "push delete to network"); options.addOption("M", "mkdir", true, "push directory create to network"); options.addOption("h", "help", false, "print help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("s-client", options); return;//from w ww. j a v a 2 s.c o m } File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C")) : new File(System.getProperty("user.home"), ".s-client.properties"); logger.info("using config file = {}", configFile); ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile); FileUtils.cleanDirectory(configuration.getTemp()); KeystoreHandler.newLoader().loadAndStore(configuration); if (cmd.hasOption("c")) { logger.info("configuration =\n{}", configuration.newWriter().dumpToString()); } else { logger.trace("configuration =\n{}", configuration.newWriter().dumpToString()); } logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace()); if (cmd.hasOption("sp")) { List<String> peers = Lists.newArrayList(Lists.transform( Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() { @Override public String apply(String input) { return input.trim(); } })); logger.info("set peers = {}", peers); configuration.edit().setPeers(Collections.<DeviceInfo>emptyList()); for (String peer : peers) { KeystoreHandler.validateDeviceId(peer); configuration.edit().addPeers(new DeviceInfo(peer, null)); } configuration.edit().persistNow(); } if (cmd.hasOption("q")) { String deviceId = cmd.getOptionValue("q"); logger.info("query device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId); logger.info("server response = {}", deviceAddresses); } if (cmd.hasOption("d")) { String deviceId = cmd.getOptionValue("d"); logger.info("discovery device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId); logger.info("local response = {}", deviceAddresses); } if (cmd.hasOption("p")) { String path = cmd.getOptionValue("p"); logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) { InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete() .getInputStream(); String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName(); File file; if (cmd.hasOption("o")) { File param = new File(cmd.getOptionValue("o")); file = param.isDirectory() ? new File(param, fileName) : param; } else { file = new File(fileName); } FileUtils.copyInputStreamToFile(inputStream, file); logger.info("saved file to = {}", file.getAbsolutePath()); } } if (cmd.hasOption("P")) { String path = cmd.getOptionValue("P"); File file = new File(cmd.getOptionValue("i")); checkArgument(!path.startsWith("/")); //TODO check path syntax logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file), folder, path)) { while (!fileUploadObserver.isCompleted()) { fileUploadObserver.waitForProgressUpdate(); logger.debug("upload progress {}", fileUploadObserver.getProgressMessage()); } logger.info("uploaded file to network"); } } if (cmd.hasOption("D")) { String path = cmd.getOptionValue("D"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("delete path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDelete(folder, path)) { observer.waitForComplete(); logger.info("deleted path"); } } if (cmd.hasOption("M")) { String path = cmd.getOptionValue("M"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("dir path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDir(folder, path)) { observer.waitForComplete(); logger.info("uploaded dir to network"); } } if (cmd.hasOption("L")) { try (SyncthingClient client = new SyncthingClient(configuration)) { client.waitForRemoteIndexAquired(); for (String folder : client.getIndexHandler().getFolderList()) { try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder() .setFolder(folder).build()) { logger.info("list folder = {}", indexBrowser.getFolder()); for (FileInfo fileInfo : indexBrowser.listFiles()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } } } } if (cmd.hasOption("I")) { try (SyncthingClient client = new SyncthingClient(configuration)) { if (cmd.hasOption("a")) { String deviceId = cmd.getOptionValue("a").substring(0, 63), address = cmd.getOptionValue("a").substring(64); try (BlockExchangeConnectionHandler connection = client.getConnection( DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) { client.getIndexHandler().waitForRemoteIndexAquired(connection); } } else { client.waitForRemoteIndexAquired(); } String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("li")) { try (SyncthingClient client = new SyncthingClient(configuration)) { String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("lp")) { try (SyncthingClient client = new SyncthingClient(configuration); DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler() .newDeviceAddressSupplier()) { String deviceAddressesStr = ""; for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) { deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : " + deviceAddress.getAddress(); } logger.info("device addresses:\n{}\n", deviceAddressesStr); } } if (cmd.hasOption("s")) { String term = cmd.getOptionValue("s"); try (SyncthingClient client = new SyncthingClient(configuration); IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) { client.waitForRemoteIndexAquired(); logger.info("search term = '{}'", term); IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term); if (event.hasGoodResults()) { logger.info("search results for term = '{}' :", term); for (FileInfo fileInfo : event.getResultList()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } else if (event.hasTooManyResults()) { logger.info("too many results found for term = '{}'", term); } else { logger.info("no result found for term = '{}'", term); } } } // if (cmd.hasOption("l")) { // String indexDump = new IndexHandler(configuration).dumpIndex(); // logger.info("index dump = \n\n{}\n", indexDump); // } IOUtils.closeQuietly(configuration); }
From source file:com.genentech.application.property.TPSA.java
public static void main(String args[]) { try {//from w w w .j a va 2s . c o m boolean countP = false; boolean countS = false; String[] molFiles; // create Options object Options options = new Options(); // add options options.addOption("P", false, "Count phosphorus atoms"); options.addOption("S", false, "Count sulfur atoms"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("P")) countP = true; if (cmd.hasOption("S")) countS = true; //get rest of arguments as an array of string molFiles = cmd.getArgs(); if (molFiles.length < 1) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("TPSA [options] <mol files> ... ", options); System.exit(1); } TPSA myTPSA = new TPSA(); myTPSA.runTest(countP, countS); OEGraphMol mol = new OEGraphMol(); oemolistream ifs = new oemolistream(); ; for (int i = 0; i < molFiles.length; i++) { ifs = new oemolistream(molFiles[i]); while (oechem.OEReadMolecule(ifs, mol)) { double tpsa = myTPSA.calculateTPSA(mol, countP, countS); if (tpsa < 0) { System.out.printf("%s 0\n", mol.GetTitle()); } else { System.out.printf("%s %d\n", mol.GetTitle(), (int) tpsa); } } } ifs.close(); } catch (ParseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:it.polimi.tower4clouds.rules.batch.BatchTool.java
public static void main(String[] args) { Options options = buildOptions();/*w w w . j a v a2 s . c om*/ CommandLineParser parser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); FileInputStream inputFile = null; try { // parse the command line arguments CommandLine cmd = parser.parse(options, args); if (cmd.getOptions().length != 1) { System.err.println("Parsing failed: Reason: one and only one option is required"); formatter.printHelp("qos-models", options); } else if (cmd.hasOption("h")) { formatter.printHelp("qos-models", options); } else if (cmd.hasOption("v")) { String file = cmd.getOptionValue("v"); inputFile = new FileInputStream(file); MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class); RulesValidator validator = new RulesValidator(); Set<Problem> problems = validator.validateAllRules(rules); printResult(problems); } else if (cmd.hasOption("c")) { String file = cmd.getOptionValue("c"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); QoSValidator validator = new QoSValidator(); Set<Problem> problems = validator.validateAllConstraints(constraints); printResult(problems); } else if (cmd.hasOption("r")) { String file = cmd.getOptionValue("r"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); MonitoringRuleFactory factory = new MonitoringRuleFactory(); MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints); XMLHelper.serialize(rules, System.out); } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); formatter.printHelp("qos-models", options); } catch (FileNotFoundException e) { System.err.println("Could not locate input file: " + e.getMessage()); } catch (JAXBException | SAXException e) { System.err.println("Input file could not be parsed: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Unknown error: "); e.printStackTrace(); } finally { if (inputFile != null) { try { inputFile.close(); } catch (IOException e) { } } } }