List of usage examples for org.apache.commons.cli Option setRequired
public void setRequired(boolean required)
From source file:eu.edisonproject.training.execute.Main.java
public static void main(String args[]) { Options options = new Options(); Option operation = new Option("op", "operation", true, "type of operation to perform. " + "For term extraction use 'x'.\n" + "Example: -op x -i E-COCO/documentation/sampleTextFiles/databases.txt " + "-o E-COCO/documentation/sampleTextFiles/databaseTerms.csv" + "For word sense disambiguation use 'w'.\n" + "Example: -op w -i E-COCO/documentation/sampleTextFiles/databaseTerms.csv " + "-o E-COCO/documentation/sampleTextFiles/databse.avro\n" + "For tf-idf vector extraction use 't'.\n" + "For running the apriori algorithm use 'a'"); operation.setRequired(true); options.addOption(operation);/* w w w . j a v a2 s . c o m*/ Option input = new Option("i", "input", true, "input file path"); input.setRequired(true); options.addOption(input); Option output = new Option("o", "output", true, "output file"); output.setRequired(true); options.addOption(output); Option popertiesFile = new Option("p", "properties", true, "path for a properties file"); popertiesFile.setRequired(false); options.addOption(popertiesFile); Option termsFile = new Option("t", "terms", true, "terms file"); termsFile.setRequired(false); options.addOption(termsFile); String helpmasg = "Usage: \n"; for (Object obj : options.getOptions()) { Option op = (Option) obj; helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t" + op.getDescription() + "\n"; } try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); String propPath = cmd.getOptionValue("properties"); if (propPath == null) { prop = ConfigHelper .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties"); } else { prop = ConfigHelper.getProperties(propPath); } // ${user.home} switch (cmd.getOptionValue("operation")) { case "x": termExtraction(cmd.getOptionValue("input"), cmd.getOptionValue("output")); break; case "w": wsd(cmd.getOptionValue("input"), cmd.getOptionValue("output")); break; case "t": calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output")); break; // case "tt": // calculateTermTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("terms"), cmd.getOptionValue("output")); // break; case "a": apriori(cmd.getOptionValue("input"), cmd.getOptionValue("output")); break; default: System.out.println(helpmasg); } } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex); } }
From source file:com.blackducksoftware.integration.hubdiff.HubDiff.java
public static void main(String[] args) throws IOException, IllegalArgumentException, EncryptionException, HubIntegrationException, JSONException { Options options = new Options(); Option optUrl1 = new Option("h1", "hub-url-1", true, "the base url to the hub. Example: http://int-hub01.dc1.lan:8080"); Option optUsername1 = new Option("u1", "username-1", true, "the username for your hub instance"); Option optPassword1 = new Option("p1", "password-1", true, "the password for your hub instance and username"); Option optUrl2 = new Option("h2", "hub-url-2", true, "the base url to the hub. Example: http://int-auto.dc1.lan:9000"); Option optUsername2 = new Option("u2", "username-2", true, "the username for your hub instance"); Option optPassword2 = new Option("p2", "password-2", true, "the password for your hub instance and username"); Option optOutputFile = new Option("o", "output", true, "the file path to your output file"); optUrl1.setRequired(true); optUsername1.setRequired(true);/*w w w . ja v a 2 s .c om*/ optPassword1.setRequired(true); optUsername2.setRequired(true); optUrl1.setRequired(true); optPassword2.setRequired(true); optOutputFile.setRequired(false); // Add options to collection options.addOption(optUrl1); options.addOption(optUsername1); options.addOption(optPassword1); options.addOption(optUrl2); options.addOption(optUsername2); options.addOption(optPassword2); options.addOption(optOutputFile); // Parse the arguments array for the options CommandLineParser cliParser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine optionParser; try { optionParser = cliParser.parse(options, args); } catch (ParseException e) { formatter.printHelp("hub-model-generator", options); log.error(e.getMessage()); System.exit(1); return; } // Read arguments String url1 = optionParser.getOptionValue("hub-url-1"); String username1 = optionParser.getOptionValue("username-1"); String password1 = optionParser.getOptionValue("password-1"); String url2 = optionParser.getOptionValue("hub-url-2"); String username2 = optionParser.getOptionValue("username-2"); String password2 = optionParser.getOptionValue("password-2"); String outputFilePath = optionParser.getOptionValue("output"); HubServerConfigBuilder configBuilder = new HubServerConfigBuilder(); configBuilder.setHubUrl(url1); configBuilder.setUsername(username1); configBuilder.setPassword(password1); HubServerConfig config1 = configBuilder.build(); HubServerConfigBuilder configBuilder2 = new HubServerConfigBuilder(); configBuilder2.setHubUrl(url2); configBuilder2.setUsername(username2); configBuilder2.setPassword(password2); HubServerConfig config2 = configBuilder2.build(); HubDiff hubDiff = new HubDiff(config1, config2); hubDiff.printDiff(System.out); if (outputFilePath != null) { File outputFile = new File(outputFilePath); hubDiff.writeDiffAsCSV(outputFile); } }
From source file:com.genentech.struchk.oeStruchk.OEStruchk.java
/** * Command line interface to {@link OEStruchk}. *//*from w ww.j a va 2s . c o m*/ public static void main(String[] args) throws ParseException, JDOMException, IOException { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion()); // create command line Options object Options options = new Options(); Option opt = new Option("f", true, "specify the configuration file name"); opt.setRequired(false); options.addOption(opt); opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file"); options.addOption(opt); opt = new Option("printRules", true, "Print HTML listing all the rules to filename."); options.addOption(opt); opt = new Option("errorsAsWarnings", false, "Treat errors as warnings."); options.addOption(opt); opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger."); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } URL confFile; if (cmd.hasOption("f")) { confFile = new File(cmd.getOptionValue("f")).toURI().toURL(); } else { confFile = getResourceURL(OEStruchk.class, "Struchk.xml"); } boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings"); if (cmd.hasOption("printRules")) { String fName = cmd.getOptionValue("printRules"); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName))); OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); structFlagAssigner.printRules(out); out.close(); return; } if (args.length < 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("oeStruck", options); throw new Error("missing input file\n"); } BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); StringBuilder mol = new StringBuilder(); StringBuilder data = new StringBuilder(); PrintStream out = System.out; if (args.length > 1) out = new PrintStream(args[1]); // create OEStruchk from config file OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings); Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)"); String line; boolean inMolFile = true; boolean atEnd = false; while (!atEnd) { if ((line = in.readLine()) == null) { if ("".equals(mol.toString().trim())) break; if (!inMolFile) throw new Error("Invalid end of sd file!"); line = "$$$$"; atEnd = true; } if (line.startsWith("$$$$")) { OEStruchk oeStruchk; StructureFlag sFlag = null; Matcher mat = sFlagPat.matcher(data); if (!mat.find()) { oeStruchk = structFlagAssigner; } else { oeStruchk = structFlagChecker; sFlag = StructureFlag.fromString(mat.group(1)); } if (!oeStruchk.applyRules(mol.toString(), null, sFlag)) nErrors++; out.print(oeStruchk.getTransformedMolfile(null)); out.print(data); if (!cmd.hasOption("noMsg")) { List<Message> msgs = oeStruchk.getStructureMessages(null); if (msgs.size() > 0) { nMessages += msgs.size(); out.println("> <errors_oe2>"); for (Message msg : msgs) out.printf("%s: %s\n", msg.getLevel(), msg.getText()); out.println(); } //System.err.println(oeStruchk.getTransformedMolfile("substance")); out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName()); out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null)); out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null)); out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent")); out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode()); out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(), oeStruchk.countStereoDBondStr()); } out.println(line); nStruct++; mol.setLength(0); data.setLength(0); inMolFile = true; } else if (!inMolFile || line.startsWith(">")) { inMolFile = false; data.append(line).append("\n"); } else { mol.append(line).append("\n"); } } structFlagAssigner.delete(); structFlagChecker.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); if (in != null) in.close(); } if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } }
From source file:edu.ksu.cis.indus.staticanalyses.flow.instances.ofa.OFAXMLizerCLI.java
/** * The entry point to the program via command line. * //from w w w.j a v a 2 s .c o m * @param args is the command line arguments. * @throws RuntimeException when object flow analysis fails. */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("c", "cumulative", false, "Consider all root methods in the same execution."); _options.addOption(_option); _option = new Option("o", "output", true, "Directory into which xml files will be written into."); _option.setArgs(1); _options.addOption(_option); _option = new Option("j", "jimple", false, "Dump xmlized jimple."); _options.addOption(_option); _option = new Option("h", "help", false, "Display message."); _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("t", "ofa-type", false, "Type of analysis : fioi, fsoi, fios, fsos, fioirt, fsoirt."); _option.setArgs(1); _option.setArgName("type"); _option.setOptionalArg(false); _option.setRequired(true); _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 PosixParser _parser = new PosixParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption("h")) { printUsage(_options); System.exit(1); } String _outputDir = _cl.getOptionValue('o'); if (_outputDir == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Defaulting to current directory for output."); } _outputDir = "."; } if (_cl.getArgList().isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } final OFAXMLizerCLI _cli = new OFAXMLizerCLI(); _cli.xmlizer.setXmlOutputDir(_outputDir); _cli.xmlizer.setGenerator(new UniqueJimpleIDGenerator()); _cli.setCumulative(_cl.hasOption('c')); _cli.setClassNames(_cl.getArgList()); _cli.type = _cl.getOptionValue('t'); if (_cl.hasOption('p')) { _cli.addToSootClassPath(_cl.getOptionValue('p')); } if (_cl.hasOption('S')) { _cli.setScopeSpecFile(_cl.getOptionValue('S')); } _cli.initialize(); _cli.<ITokens>execute(_cl.hasOption('j')); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line. \n" + _e); printUsage(_options); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java
/** * Entry point for the program.//w ww . j a v a 2s. c o m * * @param args * arguments from the command line * @throws IOException */ @SuppressWarnings("static-access") public static void main(String[] args) throws IOException { Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg() .withDescription("Specify configuration directory.").create("configDir"); // tempDir option is used by the YARN client. Option tempDir = OptionBuilder.withArgName("temporary directory (overwrites configured option)").hasArg() .withDescription("Specify temporary directory.").create(ARG_CONF_DIR); configDirOpt.setRequired(true); tempDir.setRequired(false); Options options = new Options(); options.addOption(configDirOpt); options.addOption(tempDir); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("CLI Parsing failed. Reason: " + e.getMessage()); System.exit(FAILURE_RETURN_CODE); } String configDir = line.getOptionValue(configDirOpt.getOpt(), null); String tempDirVal = line.getOptionValue(tempDir.getOpt(), null); // First, try to load global configuration GlobalConfiguration.loadConfiguration(configDir); if (tempDirVal != null // the YARN TM runner has set a value for the temp dir // the configuration does not contain a temp direcory && GlobalConfiguration.getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, null) == null) { Configuration c = GlobalConfiguration.getConfiguration(); c.setString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, tempDirVal); LOG.info("Setting temporary directory to " + tempDirVal); GlobalConfiguration.includeConfiguration(c); } System.err.println("Configuration " + GlobalConfiguration.getConfiguration()); LOG.info("Current user " + UserGroupInformation.getCurrentUser().getShortUserName()); { // log the available JVM memory long maxMemoryMiBytes = Runtime.getRuntime().maxMemory() >>> 20; LOG.info("Starting TaskManager in a JVM with " + maxMemoryMiBytes + " MiBytes maximum heap size."); } // Create a new task manager object try { new TaskManager(); } catch (Exception e) { LOG.fatal("Taskmanager startup failed: " + e.getMessage(), e); System.exit(FAILURE_RETURN_CODE); } // park the main thread to keep the JVM alive (all other threads may be daemon threads) Object mon = new Object(); synchronized (mon) { try { mon.wait(); } catch (InterruptedException ex) { } } }
From source file:gov.noaa.ncdc.iosp.avhrr.util.AvhrrLevel1B2Netcdf.java
/** * @param args// w w w . j ava 2 s. c o m * the command line arguments */ public static void main(String args[]) throws Exception { // create the Options object Options options = new Options(); options.addOption(OPTION_NOGUI, false, "command line mode"); options.addOption(OPTION_ALLVAR, false, "Process all channels"); options.addOption(OPTION_CH1, false, "Process channel 1"); options.addOption(OPTION_CH2, false, "Process channel 2"); options.addOption(OPTION_CH3, false, "Process channel 3"); options.addOption(OPTION_CH4, false, "Process channel 4"); options.addOption(OPTION_CH5, false, "Process channel 5"); options.addOption(OPTION_DEFAULT, false, "Output All Channels, Brightness Temperature and Latitude and Longitude"); options.addOption(OPTION_TEMP, false, "Output calibrated temperatures/albedos"); options.addOption(OPTION_RAW, false, "Output raw values"); options.addOption(OPTION_RADIANCE, false, "Output radiance values"); options.addOption(OPTION_LATLON, false, "Output latitude and longitude"); options.addOption(OPTION_ALLVAR, false, "Output all variables)"); options.addOption(OPTION_CLOBBER, false, "Overwrite existing netCDF file."); options.addOption(OPTION_CALIBRATION, false, "Output calibration variables"); options.addOption(OPTION_QUALITY, false, "Output quality variables."); options.addOption(OPTION_METADATA, false, "Output metadata variables."); options.addOption("memory", false, "java heap space."); Option logOption = new Option("logFile", true, "Send output to file"); options.addOption(logOption); Option outdirOption = new Option("outputdir", true, "Output Directory."); options.addOption(outdirOption); // 2nd way is by creating an Option and then adding it Option timeOption = new Option(OPTION_AVHRR, true, "Process the Level1B file"); timeOption.setRequired(false); options.addOption(timeOption); // now lets parse the input CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException pe) { usage(options); return; } // now lets interrogate the options and execute the relevant parts if (cmd.hasOption(OPTION_NOGUI)) { // process command line args - need to refactor this (doing this // twice--BAD!!!!!) List<String> list = processCommandLineArgs(cmd); String file = cmd.getOptionValue(OPTION_AVHRR); if (null == file) { System.out.println("You must specify a file to convert!! missing -avhrr argument"); usage(options); return; } String outdir = cmd.getOptionValue("outputdir"); if (null == outdir || outdir.trim().length() < 1) { File f = new File("."); outdir = f.getAbsolutePath(); } // try { Avhrr2Netcdf.convert(file, list, outdir); // } catch (Exception e) { // System.out.println("this blew up"); // TODO Auto-generated catch block // e.printStackTrace(); // } } else { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); for (int i = 0; i < info.length; i++) { // Get the name of the look and feel that is suitable // for // display to the user String className = info[i].getClassName(); } String javaLF = UIManager.getSystemLookAndFeelClassName(); try { // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); UIManager.setLookAndFeel(javaLF); } catch (ClassNotFoundException e) { // log.error(e.getMessage()); } catch (InstantiationException e) { // log.error(e.getMessage()); } catch (IllegalAccessException e) { // log.error(e.getMessage()); } catch (UnsupportedLookAndFeelException e) { // log.error(e.getMessage()); } mFrame = new AvhrrLevel1B2Netcdf(); mFrame.setVisible(true); } }); } }
From source file:edu.ksu.cis.indus.staticanalyses.callgraphs.CallGraphXMLizerCLI.java
/** * The entry point to the program via command line. * //from w ww . ja v a 2 s .c o m * @param args is the command line arguments. * @throws RuntimeException when the analyses fail. */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("c", "cumulative", false, "Builds one call graph that includes all root methods."); _options.addOption(_option); _option = new Option("o", "output", true, "Directory into which xml files will be written into. Defaults to current directory if omitted"); _option.setArgs(1); _option.setArgName("output-dir"); _options.addOption(_option); _option = new Option("j", "jimple", false, "Dump xmlized jimple."); _option.setArgName("dump-jimple"); _options.addOption(_option); _option = new Option("p", "soot-classpath", true, "Prepend this to soot class path."); _option.setArgs(1); _option.setArgName("classpath"); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("h", "help", false, "Display message."); _option.setOptionalArg(false); _options.addOption(_option); _option = new Option("t", "call-graph-type", true, "Call graph type. This has to be one of {cha, rta, ofa-oi, " + "ofa-oirt, ofa-os}."); _option.setArgs(1); _option.setArgName("type"); _option.setRequired(true); _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 PosixParser _parser = new PosixParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption('h')) { printUsage(_options); System.exit(1); } String _outputDir = _cl.getOptionValue('o'); if (_outputDir == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Defaulting to current directory for output."); } _outputDir = "."; } if (_cl.getArgList().isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } final CallGraphXMLizerCLI _cli = new CallGraphXMLizerCLI(); _cli.xmlizer.setXmlOutputDir(_outputDir); _cli.xmlizer.setGenerator(new UniqueJimpleIDGenerator()); _cli.setCumulative(_cl.hasOption('c')); _cli.setClassNames(_cl.getArgList()); _cli.addToSootClassPath(_cl.getOptionValue('p')); if (_cl.hasOption('S')) { _cli.setScopeSpecFile(_cl.getOptionValue('S')); } _cli.initialize(); _cli.execute(_cl.hasOption('j'), _cl.getOptionValue('t')); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line." + _e); printUsage(_options); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:com.jug.MoMA.java
/** * PROJECT MAIN/*from w w w .j a va2s. c o m*/ * * @param args */ public static void main(final String[] args) { if (showIJ) new ImageJ(); // // ===== set look and feel ======================================================================== // try { // // Set cross-platform Java L&F (also called "Metal") // UIManager.setLookAndFeel( // UIManager.getCrossPlatformLookAndFeelClassName() ); // } catch ( final UnsupportedLookAndFeelException e ) { // // handle exception // } catch ( final ClassNotFoundException e ) { // // handle exception // } catch ( final InstantiationException e ) { // // handle exception // } catch ( final IllegalAccessException e ) { // // handle exception // } // ===== command line parsing ====================================================================== // create Options object & the parser final Options options = new Options(); final CommandLineParser parser = new BasicParser(); // defining command line options final Option help = new Option("help", "print this message"); final Option headless = new Option("h", "headless", false, "start without user interface (note: input-folder must be given!)"); headless.setRequired(false); final Option timeFirst = new Option("tmin", "min_time", true, "first time-point to be processed"); timeFirst.setRequired(false); final Option timeLast = new Option("tmax", "max_time", true, "last time-point to be processed"); timeLast.setRequired(false); final Option optRange = new Option("orange", "opt_range", true, "initial optimization range"); optRange.setRequired(false); final Option numChannelsOption = new Option("c", "channels", true, "number of channels to be loaded and analyzed."); numChannelsOption.setRequired(true); final Option minChannelIdxOption = new Option("cmin", "min_channel", true, "the smallest channel index (usually 0 or 1, default is 1)."); minChannelIdxOption.setRequired(false); final Option infolder = new Option("i", "infolder", true, "folder to read data from"); infolder.setRequired(false); final Option outfolder = new Option("o", "outfolder", true, "folder to write preprocessed data to (equals infolder if not given)"); outfolder.setRequired(false); final Option userProps = new Option("p", "props", true, "properties file to be loaded (mm.properties)"); userProps.setRequired(false); options.addOption(help); options.addOption(headless); options.addOption(numChannelsOption); options.addOption(minChannelIdxOption); options.addOption(timeFirst); options.addOption(timeLast); options.addOption(optRange); options.addOption(infolder); options.addOption(outfolder); options.addOption(userProps); // get the commands parsed CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final ParseException e1) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "... [-p props-file] -i in-folder [-o out-folder] -c <num-channels> [-cmin start-channel-ids] [-tmin idx] [-tmax idx] [-orange num-frames] [-headless]", "", options, "Error: " + e1.getMessage()); System.exit(0); } if (cmd.hasOption("help")) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("... -i <in-folder> -o [out-folder] [-headless]", options); System.exit(0); } if (cmd.hasOption("h")) { System.out.println(">>> Starting MM in headless mode."); HEADLESS = true; if (!cmd.hasOption("i")) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Headless-mode requires option '-i <in-folder>'...", options); System.exit(0); } } File inputFolder = null; if (cmd.hasOption("i")) { inputFolder = new File(cmd.getOptionValue("i")); if (!inputFolder.isDirectory()) { System.out.println("Error: Input folder is not a directory!"); System.exit(2); } if (!inputFolder.canRead()) { System.out.println("Error: Input folder cannot be read!"); System.exit(2); } } File outputFolder = null; if (!cmd.hasOption("o")) { if (inputFolder == null) { System.out.println( "Error: Output folder would be set to a 'null' input folder! Please check your command line arguments..."); System.exit(3); } outputFolder = inputFolder; STATS_OUTPUT_PATH = outputFolder.getAbsolutePath(); } else { outputFolder = new File(cmd.getOptionValue("o")); if (!outputFolder.isDirectory()) { System.out.println("Error: Output folder is not a directory!"); System.exit(3); } if (!inputFolder.canWrite()) { System.out.println("Error: Output folder cannot be written to!"); System.exit(3); } STATS_OUTPUT_PATH = outputFolder.getAbsolutePath(); } fileUserProps = null; if (cmd.hasOption("p")) { fileUserProps = new File(cmd.getOptionValue("p")); } if (cmd.hasOption("cmin")) { minChannelIdx = Integer.parseInt(cmd.getOptionValue("cmin")); } if (cmd.hasOption("c")) { numChannels = Integer.parseInt(cmd.getOptionValue("c")); } if (cmd.hasOption("tmin")) { minTime = Integer.parseInt(cmd.getOptionValue("tmin")); } if (cmd.hasOption("tmax")) { maxTime = Integer.parseInt(cmd.getOptionValue("tmax")); } if (cmd.hasOption("orange")) { initOptRange = Integer.parseInt(cmd.getOptionValue("orange")); } // ******** CHECK GUROBI ********* CHECK GUROBI ********* CHECK GUROBI ********* final String jlp = System.getProperty("java.library.path"); // System.out.println( jlp ); try { new GRBEnv("MoMA_gurobi.log"); } catch (final GRBException e) { final String msgs = "Initial Gurobi test threw exception... check your Gruobi setup!\n\nJava library path: " + jlp; if (HEADLESS) { System.out.println(msgs); } else { JOptionPane.showMessageDialog(MoMA.guiFrame, msgs, "Gurobi Error?", JOptionPane.ERROR_MESSAGE); } e.printStackTrace(); System.exit(98); } catch (final UnsatisfiedLinkError ulr) { final String msgs = "Could initialize Gurobi.\n" + "You might not have installed Gurobi properly or you miss a valid license.\n" + "Please visit 'www.gurobi.com' for further information.\n\n" + ulr.getMessage() + "\nJava library path: " + jlp; if (HEADLESS) { System.out.println(msgs); } else { JOptionPane.showMessageDialog(MoMA.guiFrame, msgs, "Gurobi Error?", JOptionPane.ERROR_MESSAGE); ulr.printStackTrace(); } System.out.println("\n>>>>> Java library path: " + jlp + "\n"); System.exit(99); } // ******* END CHECK GUROBI **** END CHECK GUROBI **** END CHECK GUROBI ******** final MoMA main = new MoMA(); if (!HEADLESS) { guiFrame = new JFrame(); main.initMainWindow(guiFrame); } System.out.println("VERSION: " + VERSION_STRING); props = main.loadParams(); BGREM_TEMPLATE_XMIN = Integer .parseInt(props.getProperty("BGREM_TEMPLATE_XMIN", Integer.toString(BGREM_TEMPLATE_XMIN))); BGREM_TEMPLATE_XMAX = Integer .parseInt(props.getProperty("BGREM_TEMPLATE_XMAX", Integer.toString(BGREM_TEMPLATE_XMAX))); BGREM_X_OFFSET = Integer.parseInt(props.getProperty("BGREM_X_OFFSET", Integer.toString(BGREM_X_OFFSET))); GL_WIDTH_IN_PIXELS = Integer .parseInt(props.getProperty("GL_WIDTH_IN_PIXELS", Integer.toString(GL_WIDTH_IN_PIXELS))); MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS = Integer.parseInt(props.getProperty( "MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS", Integer.toString(MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS))); GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS = Integer .parseInt(props.getProperty("GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS", Integer.toString(GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS))); GL_OFFSET_BOTTOM = Integer .parseInt(props.getProperty("GL_OFFSET_BOTTOM", Integer.toString(GL_OFFSET_BOTTOM))); if (GL_OFFSET_BOTTOM == -1) { GL_OFFSET_BOTTOM_AUTODETECT = true; } else { GL_OFFSET_BOTTOM_AUTODETECT = false; } GL_OFFSET_TOP = Integer.parseInt(props.getProperty("GL_OFFSET_TOP", Integer.toString(GL_OFFSET_TOP))); GL_OFFSET_LATERAL = Integer .parseInt(props.getProperty("GL_OFFSET_LATERAL", Integer.toString(GL_OFFSET_LATERAL))); MIN_CELL_LENGTH = Integer.parseInt(props.getProperty("MIN_CELL_LENGTH", Integer.toString(MIN_CELL_LENGTH))); MIN_GAP_CONTRAST = Float .parseFloat(props.getProperty("MIN_GAP_CONTRAST", Float.toString(MIN_GAP_CONTRAST))); SIGMA_PRE_SEGMENTATION_X = Float.parseFloat( props.getProperty("SIGMA_PRE_SEGMENTATION_X", Float.toString(SIGMA_PRE_SEGMENTATION_X))); SIGMA_PRE_SEGMENTATION_Y = Float.parseFloat( props.getProperty("SIGMA_PRE_SEGMENTATION_Y", Float.toString(SIGMA_PRE_SEGMENTATION_Y))); SIGMA_GL_DETECTION_X = Float .parseFloat(props.getProperty("SIGMA_GL_DETECTION_X", Float.toString(SIGMA_GL_DETECTION_X))); SIGMA_GL_DETECTION_Y = Float .parseFloat(props.getProperty("SIGMA_GL_DETECTION_Y", Float.toString(SIGMA_GL_DETECTION_Y))); SEGMENTATION_MIX_CT_INTO_PMFRF = Float.parseFloat(props.getProperty("SEGMENTATION_MIX_CT_INTO_PMFRF", Float.toString(SEGMENTATION_MIX_CT_INTO_PMFRF))); SEGMENTATION_CLASSIFIER_MODEL_FILE = props.getProperty("SEGMENTATION_CLASSIFIER_MODEL_FILE", SEGMENTATION_CLASSIFIER_MODEL_FILE); CELLSIZE_CLASSIFIER_MODEL_FILE = props.getProperty("CELLSIZE_CLASSIFIER_MODEL_FILE", CELLSIZE_CLASSIFIER_MODEL_FILE); DEFAULT_PATH = props.getProperty("DEFAULT_PATH", DEFAULT_PATH); GUROBI_TIME_LIMIT = Double .parseDouble(props.getProperty("GUROBI_TIME_LIMIT", Double.toString(GUROBI_TIME_LIMIT))); GUROBI_MAX_OPTIMALITY_GAP = Double.parseDouble( props.getProperty("GUROBI_MAX_OPTIMALITY_GAP", Double.toString(GUROBI_MAX_OPTIMALITY_GAP))); GUI_POS_X = Integer.parseInt(props.getProperty("GUI_POS_X", Integer.toString(DEFAULT_GUI_POS_X))); GUI_POS_Y = Integer.parseInt(props.getProperty("GUI_POS_Y", Integer.toString(DEFAULT_GUI_POS_X))); GUI_WIDTH = Integer.parseInt(props.getProperty("GUI_WIDTH", Integer.toString(GUI_WIDTH))); GUI_HEIGHT = Integer.parseInt(props.getProperty("GUI_HEIGHT", Integer.toString(GUI_HEIGHT))); GUI_CONSOLE_WIDTH = Integer .parseInt(props.getProperty("GUI_CONSOLE_WIDTH", Integer.toString(GUI_CONSOLE_WIDTH))); if (!HEADLESS) { // Iterate over all currently attached monitors and check if sceen // position is actually possible, // otherwise fall back to the DEFAULT values and ignore the ones // coming from the properties-file. boolean pos_ok = false; final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice[] gs = ge.getScreenDevices(); for (int i = 0; i < gs.length; i++) { if (gs[i].getDefaultConfiguration().getBounds() .contains(new java.awt.Point(GUI_POS_X, GUI_POS_Y))) { pos_ok = true; } } // None of the screens contained the top-left window coordinates --> // fall back onto default values... if (!pos_ok) { GUI_POS_X = DEFAULT_GUI_POS_X; GUI_POS_Y = DEFAULT_GUI_POS_Y; } } String path = props.getProperty("import_path", System.getProperty("user.home")); if (inputFolder == null || inputFolder.equals("")) { inputFolder = main.showStartupDialog(guiFrame, path); } System.out.println("Default filename decoration = " + inputFolder.getName()); defaultFilenameDecoration = inputFolder.getName(); path = inputFolder.getAbsolutePath(); props.setProperty("import_path", path); GrowthLineSegmentationMagic.setClassifier(SEGMENTATION_CLASSIFIER_MODEL_FILE, ""); if (!HEADLESS) { // Setting up console window... main.initConsoleWindow(); main.showConsoleWindow(true); } // ------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------ final MoMAModel mmm = new MoMAModel(main); instance = main; try { main.processDataFromFolder(path, minTime, maxTime, minChannelIdx, numChannels); } catch (final Exception e) { e.printStackTrace(); System.exit(11); } // ------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------ // show loaded and annotated data if (showIJ) { new ImageJ(); ImageJFunctions.show(main.imgRaw, "Rotated & cropped raw data"); // ImageJFunctions.show( main.imgTemp, "Temporary" ); // ImageJFunctions.show( main.imgAnnotated, "Annotated ARGB data" ); // main.getCellSegmentedChannelImgs() // ImageJFunctions.show( main.imgClassified, "Classification" ); // ImageJFunctions.show( main.getCellSegmentedChannelImgs(), "Segmentation" ); } gui = new MoMAGui(mmm); if (!HEADLESS) { System.out.print("Build GUI..."); main.showConsoleWindow(false); // final JFrameSnapper snapper = new JFrameSnapper(); // snapper.addFrame( main.frameConsoleWindow ); // snapper.addFrame( guiFrame ); gui.setVisible(true); guiFrame.add(gui); guiFrame.setSize(GUI_WIDTH, GUI_HEIGHT); guiFrame.setLocation(GUI_POS_X, GUI_POS_Y); guiFrame.setVisible(true); // SwingUtilities.invokeLater( new Runnable() { // // @Override // public void run() { // snapper.snapFrames( main.frameConsoleWindow, guiFrame, JFrameSnapper.EAST ); // } // } ); System.out.println(" done!"); } else { // final String name = inputFolder.getName(); gui.exportHtmlOverview(); gui.exportDataFiles(); instance.saveParams(); System.exit(0); } }
From source file:edu.ksu.cis.indus.staticanalyses.dependency.DependencyXMLizerCLI.java
/** * This is the entry point via command-line. * //from w w w .ja v a 2 s .c o m * @param args is the command line arguments. * @throws RuntimeException when an Throwable exception beyond our control occurs. * @pre args != null */ public static void main(final String[] args) { final Options _options = new Options(); Option _option = new Option("o", "output", true, "Directory into which xml files will be written into. Defaults to current directory if omitted"); _option.setArgs(1); _option.setArgName("output-directory"); _options.addOption(_option); _option = new Option("j", "jimple", false, "Dump xmlized jimple."); _options.addOption(_option); final DivergenceDA _fidda = DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION); _fidda.setConsiderCallSites(true); final DivergenceDA _bidda = DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION); _bidda.setConsiderCallSites(true); final NonTerminationSensitiveEntryControlDA _ncda = new NonTerminationSensitiveEntryControlDA(); final Object[][] _dasOptions = { { "ibdda1", "Identifier based data dependence (Soot)", new IdentifierBasedDataDA() }, { "ibdda2", "Identifier based data dependence (Indus)", new IdentifierBasedDataDAv2() }, { "ibdda3", "Identifier based data dependence (Indus Optimized)", new IdentifierBasedDataDAv3() }, { "rbdda", "Reference based data dependence", new ReferenceBasedDataDA() }, { "nscda", "Non-termination sensitive Entry control dependence", _ncda }, { "nicda", "Non-termination insensitive Entry control dependence", new NonTerminationInsensitiveEntryControlDA(), }, { "xcda", "Exit control dependence", new ExitControlDA() }, { "sda", "Synchronization dependence", new SynchronizationDA() }, { "frda1", "Forward Ready dependence v1", ReadyDAv1.getForwardReadyDA() }, { "brda1", "Backward Ready dependence v1", ReadyDAv1.getBackwardReadyDA() }, { "frda2", "Forward Ready dependence v2", ReadyDAv2.getForwardReadyDA() }, { "brda2", "Backward Ready dependence v2", ReadyDAv2.getBackwardReadyDA() }, { "frda3", "Forward Ready dependence v3", ReadyDAv3.getForwardReadyDA() }, { "brda3", "Backward Ready dependence v3", ReadyDAv3.getBackwardReadyDA() }, { "ida1", "Interference dependence v1", new InterferenceDAv1() }, { "ida2", "Interference dependence v2", new InterferenceDAv2() }, { "ida3", "Interference dependence v3", new InterferenceDAv3() }, { "fdda", "Forward Intraprocedural Divergence dependence", DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION), }, { "bdda", "Backward Intraprocedural Divergence dependence", DivergenceDA.getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION), }, { "fidda", "Forward Intra+Interprocedural Divergence dependence", _fidda }, { "bidda", "Backward Intra+Interprocedural Divergence dependence", _bidda }, { "fpidda", "Forward Interprocedural Divergence dependence", InterProceduralDivergenceDA .getDivergenceDA(IDependencyAnalysis.Direction.FORWARD_DIRECTION), }, { "bpidda", "Backward Interprocedural Divergence dependence", InterProceduralDivergenceDA .getDivergenceDA(IDependencyAnalysis.Direction.BACKWARD_DIRECTION), }, }; _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("aliasedusedefv1", false, "Use version 1 of aliased use-def info."); _options.addOption(_option); _option = new Option("safelockanalysis", false, "Use safe-lock-analysis for ready dependence."); _options.addOption(_option); _option = new Option("ofaforinterference", false, "Use OFA for interference dependence."); _options.addOption(_option); _option = new Option("ofaforready", false, "Use OFA for ready dependence."); _options.addOption(_option); _option = new Option("exceptionalexits", false, "Consider exceptional exits for control dependence."); _options.addOption(_option); _option = new Option("commonuncheckedexceptions", false, "Consider common unchecked exceptions."); _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); for (int _i = 0; _i < _dasOptions.length; _i++) { final String _shortOption = _dasOptions[_i][0].toString(); final String _description = _dasOptions[_i][1].toString(); _option = new Option(_shortOption, false, _description); _options.addOption(_option); } final CommandLineParser _parser = new GnuParser(); try { final CommandLine _cl = _parser.parse(_options, args); if (_cl.hasOption("h")) { printUsage(_options); System.exit(1); } final DependencyXMLizerCLI _xmlizerCLI = new DependencyXMLizerCLI(); String _outputDir = _cl.getOptionValue('o'); if (_outputDir == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Defaulting to current directory for output."); } _outputDir = "."; } _xmlizerCLI.xmlizer.setXmlOutputDir(_outputDir); if (_cl.hasOption('p')) { _xmlizerCLI.addToSootClassPath(_cl.getOptionValue('p')); } if (_cl.hasOption('S')) { _xmlizerCLI.setScopeSpecFile(_cl.getOptionValue('S')); } _xmlizerCLI.dumpJimple = _cl.hasOption('j'); _xmlizerCLI.useAliasedUseDefv1 = _cl.hasOption("aliasedusedefv1"); _xmlizerCLI.useSafeLockAnalysis = _cl.hasOption("safelockanalysis"); _xmlizerCLI.exceptionalExits = _cl.hasOption("exceptionalexits"); _xmlizerCLI.commonUncheckedException = _cl.hasOption("commonuncheckedexceptions"); final List<String> _classNames = _cl.getArgList(); if (_classNames.isEmpty()) { throw new MissingArgumentException("Please specify atleast one class."); } _xmlizerCLI.setClassNames(_classNames); final int _exitControlDAIndex = 6; if (_cl.hasOption(_dasOptions[_exitControlDAIndex][0].toString())) { _xmlizerCLI.das.add(_ncda); for (final Iterator<DependenceSort> _i = _ncda.getIds().iterator(); _i.hasNext();) { final DependenceSort _id = _i.next(); MapUtils.putIntoCollectionInMapUsingFactory(_xmlizerCLI.info, _id, _ncda, SetUtils.getFactory()); } } if (!parseForDependenceOptions(_dasOptions, _cl, _xmlizerCLI)) { throw new ParseException("Atleast one dependence analysis must be requested."); } _xmlizerCLI.<ITokens>execute(); } catch (final ParseException _e) { LOGGER.error("Error while parsing command line.", _e); System.out.println("Error while parsing command line." + _e); printUsage(_options); } catch (final Throwable _e) { LOGGER.error("Beyond our control. May day! May day!", _e); throw new RuntimeException(_e); } }
From source file:au.id.hazelwood.xmltvguidebuilder.runner.Main.java
private static Option createOptionWithArg(String opt, boolean required, String argName, Class<?> argType, String description) {/*from ww w . j a v a2 s . co m*/ Option option = new Option(opt, true, description); option.setRequired(required); option.setArgName(argName); option.setType(argType); return option; }