List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:CTmousetrack.java
public static void main(String[] args) { String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder String srcName = "CTmousetrack"; // name of the output CT source long blockPts = 10; // points per block flush long sampInterval = 10; // time between sampling updates, msec double trimTime = 0.0; // amount of data to keep (trim time), sec boolean debug = false; // turn on debug? // Specify the CT output connection CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data String serverHost = ""; // Server (FTP or HTTP/S) host:port String serverUser = ""; // Server (FTP or HTTPS) username String serverPassword = ""; // Server (FTP or HTTPS) password // For UDP output mode DatagramSocket udpServerSocket = null; InetAddress udpServerAddress = null; String udpHost = ""; int udpPort = -1; // Concatenate all of the CTWriteMode types String possibleWriteModes = ""; for (CTWriteMode wm : CTWriteMode.values()) { possibleWriteModes = possibleWriteModes + ", " + wm.name(); }//from ww w.j a va 2 s .com // Remove ", " from start of string possibleWriteModes = possibleWriteModes.substring(2); // // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption(Option.builder("o").argName("base output dir").hasArg().desc( "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \"" + outLoc + "\".") .build()); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write data to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("b").argName("points per block").hasArg() .desc("Number of points per block; UDP output mode will use 1 point/block; default = " + Long.toString(blockPts) + ".") .build()); options.addOption(Option.builder("dt").argName("samp interval msec").hasArg() .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build()); options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc( "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption( Option.builder("w").argName("write mode").hasArg() .desc("Type of write connection; one of " + possibleWriteModes + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".") .build()); options.addOption(Option.builder("host").argName("host[:port]").hasArg() .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build()); options.addOption(Option.builder("u").argName("username,password").hasArg() .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build()); options.addOption("x", "debug", false, "Enable CloudTurbine debug output."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTmousetrack", "", options, "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port."); return; } outLoc = line.getOptionValue("o", outLoc); if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) { outLoc = outLoc + File.separator; } // Make sure the base output folder location ends in "CTdata" if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) { outLoc = outLoc + "CTdata" + File.separator; } srcName = line.getOptionValue("s", srcName); blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts))); sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval))); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); // Type of output connection String writeModeStr = line.getOptionValue("w", writeMode.name()); boolean bMatch = false; for (CTWriteMode wm : CTWriteMode.values()) { if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) { writeMode = wm; bMatch = true; } } if (!bMatch) { System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of " + possibleWriteModes); System.exit(0); } if (writeMode != CTWriteMode.LOCAL) { // User must have specified the host // If FTP or HTTPS, they may also specify username/password serverHost = line.getOptionValue("host", serverHost); if (serverHost.isEmpty()) { System.err.println( "When using write mode \"" + writeModeStr + "\", you must specify the server host."); System.exit(0); } if (writeMode == CTWriteMode.UDP) { // Force blockPts to be 1 blockPts = 1; // User must have specified both host and port int colonIdx = serverHost.indexOf(':'); if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) { System.err.println( "For UDP output mode, both the host and port (<host>:<port>)) must be specified."); System.exit(0); } udpHost = serverHost.substring(0, colonIdx); String udpPortStr = serverHost.substring(colonIdx + 1); try { udpPort = Integer.parseInt(udpPortStr); } catch (NumberFormatException nfe) { System.err.println("The UDP port must be a positive integer."); System.exit(0); } } if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) { String userpassStr = line.getOptionValue("u", ""); if (!userpassStr.isEmpty()) { // This string should be comma-delimited username and password String[] userpassCSV = userpassStr.split(","); if (userpassCSV.length != 2) { System.err.println("When specifying a username and password for write mode \"" + writeModeStr + "\", separate the username and password by a comma."); System.exit(0); } serverUser = userpassCSV[0]; serverPassword = userpassCSV[1]; } } } debug = line.hasOption("debug"); System.err.println("CTmousetrack parameters:"); System.err.println("\toutput mode = " + writeMode.name()); if (writeMode == CTWriteMode.UDP) { System.err.println("\twrite to " + udpHost + ":" + udpPort); } else { System.err.println("\tsource = " + srcName); System.err.println("\ttrim time = " + trimTime + " sec"); } System.err.println("\tpoints per block = " + blockPts); System.err.println("\tsample interval = " + sampInterval + " msec"); try { // // Setup CTwriter or UDP output // CTwriter ctw = null; CTinfo.setDebug(debug); if (writeMode == CTWriteMode.LOCAL) { ctw = new CTwriter(outLoc + srcName, trimTime); System.err.println("\tdata will be written to local folder \"" + outLoc + "\""); } else if (writeMode == CTWriteMode.FTP) { CTftp ctftp = new CTftp(srcName); try { ctftp.login(serverHost, serverUser, serverPassword); } catch (Exception e) { throw new IOException( new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage())); } ctw = ctftp; // upcast to CTWriter System.err.println("\tdata will be written to FTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTP) { // Don't send username/pw in HTTP mode since they will be unencrypted CThttp cthttp = new CThttp(srcName, "http://" + serverHost); ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTPS) { CThttp cthttp = new CThttp(srcName, "https://" + serverHost); // Username/pw are optional for HTTPS mode; only use them if username is not empty if (!serverUser.isEmpty()) { try { cthttp.login(serverUser, serverPassword); } catch (Exception e) { throw new IOException(new String( "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage())); } } ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTPS server at " + serverHost); } else if (writeMode == CTWriteMode.UDP) { try { udpServerSocket = new DatagramSocket(); } catch (SocketException se) { System.err.println("Error creating socket for UDP:\n" + se); System.exit(0); } try { udpServerAddress = InetAddress.getByName(udpHost); } catch (UnknownHostException uhe) { System.err.println("Error getting UDP server host address:\n" + uhe); System.exit(0); } } if (writeMode != CTWriteMode.UDP) { ctw.setBlockMode(blockPts > 1, blockPts > 1); ctw.autoFlush(0); // no autoflush ctw.autoSegment(1000); } // screen dims Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); // use Map for consolidated putData Map<String, Object> cmap = new LinkedHashMap<String, Object>(); // loop and write some output for (int i = 0; i < 1000000; i++) { // go until killed long currentTime = System.currentTimeMillis(); Point mousePos = MouseInfo.getPointerInfo().getLocation(); float x_pt = (float) (mousePos.getX() / width); // normalize float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0) if (writeMode != CTWriteMode.UDP) { // CT output mode ctw.setTime(currentTime); cmap.clear(); cmap.put("x", x_pt); cmap.put("y", y_pt); ctw.putData(cmap); if (((i + 1) % blockPts) == 0) { ctw.flush(); System.err.print("."); } } else { // UDP output mode // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time // Write the following data (21 bytes total): // header = "MOUSE", 5 bytes // current time, long, 8 bytes // 2 floats (x,y) 4 bytes each, 8 bytes int len = 21; ByteBuffer bb = ByteBuffer.allocate(len); String headerStr = "MOUSE"; bb.put(headerStr.getBytes("UTF-8")); bb.putLong(currentTime); bb.putFloat(x_pt); bb.putFloat(y_pt); // Might be able to use the following, but not sure: // byte[] sendData = bb.array(); byte[] sendData = new byte[len]; bb.position(0); bb.get(sendData, 0, len); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress, udpPort); try { udpServerSocket.send(sendPacket); } catch (IOException e) { System.err.println("Test server caught exception trying to send data to UDP client:\n" + e); } System.err.print("."); } try { Thread.sleep(sampInterval); } catch (Exception e) { } ; } if (writeMode != CTWriteMode.UDP) { ctw.flush(); // wrap up } } catch (Exception e) { System.err.println("CTmousetrack exception: " + e); e.printStackTrace(); } }
From source file:com.twitter.heron.scheduler.RuntimeManagerMain.java
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, ParseException { Options options = constructOptions(); Options helpOptions = constructHelpOptions(); CommandLineParser parser = new DefaultParser(); // parse the help options first. CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(options);//from w w w. ja va 2 s .co m return; } try { // Now parse the required options cmd = parser.parse(options, args); } catch (ParseException e) { usage(options); throw new RuntimeException("Error parsing command line options: ", e); } Boolean verbose = false; Level logLevel = Level.INFO; if (cmd.hasOption("v")) { logLevel = Level.ALL; verbose = true; } // init log LoggingHelper.loggerInit(logLevel, false); String cluster = cmd.getOptionValue("cluster"); String role = cmd.getOptionValue("role"); String environ = cmd.getOptionValue("environment"); String heronHome = cmd.getOptionValue("heron_home"); String configPath = cmd.getOptionValue("config_path"); String overrideConfigFile = cmd.getOptionValue("override_config_file"); String releaseFile = cmd.getOptionValue("release_file"); String topologyName = cmd.getOptionValue("topology_name"); String commandOption = cmd.getOptionValue("command"); // Optional argument in the case of restart // TODO(karthik): convert into CLI String containerId = Integer.toString(-1); if (cmd.hasOption("container_id")) { containerId = cmd.getOptionValue("container_id"); } Command command = Command.makeCommand(commandOption); // first load the defaults, then the config from files to override it Config.Builder defaultsConfig = Config.newBuilder().putAll(ClusterDefaults.getDefaults()) .putAll(ClusterConfig.loadConfig(heronHome, configPath, releaseFile)); // add config parameters from the command line Config.Builder commandLineConfig = Config.newBuilder().put(Keys.cluster(), cluster).put(Keys.role(), role) .put(Keys.environ(), environ).put(Keys.verbose(), verbose) .put(Keys.topologyContainerId(), containerId); Config.Builder topologyConfig = Config.newBuilder().put(Keys.topologyName(), topologyName); Config.Builder overrideConfig = Config.newBuilder() .putAll(ClusterConfig.loadOverrideConfig(overrideConfigFile)); // build the final config by expanding all the variables Config config = Config .expand(Config.newBuilder().putAll(defaultsConfig.build()).putAll(overrideConfig.build()) .putAll(commandLineConfig.build()).putAll(topologyConfig.build()).build()); LOG.fine("Static config loaded successfully "); LOG.fine(config.toString()); // Create a new instance of RuntimeManagerMain RuntimeManagerMain runtimeManagerMain = new RuntimeManagerMain(config, command); boolean isSuccessful = runtimeManagerMain.manageTopology(); // Log the result and exit if (!isSuccessful) { throw new RuntimeException(String.format("Failed to %s topology %s", command, topologyName)); } else { LOG.log(Level.FINE, "Topology {0} {1} successfully", new Object[] { topologyName, command }); } }
From source file:com.act.lcms.v2.TraceIndexAnalyzer.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*ww w . j a v a 2 s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!rocksDBFile.exists()) { System.err.format("Index file at %s does not exist, nothing to analyze", rocksDBFile.getAbsolutePath()); HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } LOGGER.info("Starting analysis"); TraceIndexAnalyzer analyzer = new TraceIndexAnalyzer(); analyzer.runExtraction(rocksDBFile, new File(cl.getOptionValue(OPTION_OUTPUT_PATH))); LOGGER.info("Done"); }
From source file:jena.RuleMap.java
/** * General command line utility to process one RDF file into another * by application of a set of forward chaining rules. * <pre>/*from w ww .j a va 2 s. co m*/ * Usage: RuleMap [-il inlang] [-ol outlang] -d infile rulefile * </pre> */ public static void main(String[] args) { try { // Parse the command line String usage = "Usage: RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)"; final CommandLineParser parser = new DefaultParser(); Options options = new Options().addOption("il", "inputLang", true, "input language") .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?"); CommandLine cl = parser.parse(options, args); final List<String> filenameArgs = cl.getArgList(); if (filenameArgs.size() != 2) { System.err.println(usage); System.exit(1); } String inLang = cl.getOptionValue("inputLang"); String fname = filenameArgs.get(1); Model inModel = null; if (fname.equals("-")) { inModel = ModelFactory.createDefaultModel(); inModel.read(System.in, null, inLang); } else { inModel = FileManager.get().loadModel(fname, inLang); } String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3"; boolean deductionsOnly = cl.hasOption('d'); // Fetch the rule set and create the reasoner BuiltinRegistry.theRegistry.register(new Deduce()); Map<String, String> prefixes = new HashMap<>(); List<Rule> rules = loadRules(filenameArgs.get(0), prefixes); Reasoner reasoner = new GenericRuleReasoner(rules); // Process InfModel infModel = ModelFactory.createInfModel(reasoner, inModel); infModel.prepare(); infModel.setNsPrefixes(prefixes); // Output try (PrintWriter writer = new PrintWriter(System.out)) { if (deductionsOnly) { Model deductions = infModel.getDeductionsModel(); deductions.setNsPrefixes(prefixes); deductions.setNsPrefixes(inModel); deductions.write(writer, outLang); } else { infModel.write(writer, outLang); } } } catch (Throwable t) { System.err.println("An error occured: \n" + t); t.printStackTrace(); } }
From source file:edu.ifpb.pos.restletclient.CommandLineApp.java
public static void main(String[] args) { try {// w w w . j a v a 2s . c o m CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(getOp(), args); execute(line); } catch (ParseException ex) { System.out.println("ERROR: " + ex.getMessage()); } catch (IOException ex) { Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.maxpowered.amazon.advertising.api.app.App.java
public static void main(final String... args) throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException { try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) { /*/*w w w.ja va2s . c o m*/ * Get default options based on spring configs */ final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR); final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE : inputDefault + PROCESSED_EXT; final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT, STD_OUT_STR); int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE, String.valueOf(DEFAULT_APP_THROTTLE))); // Maximum of 25000 requests per hour throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE); /* * Get options from the CLI args */ final Options options = new Options(); options.addOption("h", false, "Display this help."); options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault); options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name."); // Add a note that the output depends on the configured processors. If none are configured, it defaults to a // std.out processor options.addOption("o", true, "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault); options.addOption("1", false, "Override output file and always output fetched info xml to std.out."); options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). " + DEFAULT_STR + throttleDefault); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; boolean needsHelp = false; try { cmd = parser.parse(options, args); } catch (final ParseException e) { needsHelp = true; } if (cmd.hasOption("h") || needsHelp) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("App", options); return; } // Get throttle rate final int throttle = Math.min( cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault, MAX_APP_THROTTLE); LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle); // We don't want to hit our limit, just under an hour worth of milliseconds final int requestWait = 3540000 / throttle; // Get input stream String input; if (cmd.hasOption("i")) { input = cmd.getOptionValue("i"); } else { input = inputDefault; } LOG.debug("Input name (default {}) is {}", inputDefault, input); // Get processed file String processed; if (cmd.hasOption("p")) { processed = cmd.getOptionValue("p"); } else { processed = input + PROCESSED_EXT; } LOG.debug("Processed file name (default {}) is {}", processedDefault, processed); final File processedFile = new File(processed); processedFile.createNewFile(); try (final InputStream inputStream = getInputStream(input)) { // Get output stream String output; if (cmd.hasOption("o")) { output = cmd.getOptionValue("o"); } else { output = outputDefault; } if (cmd.hasOption("1")) { output = STD_OUT_STR; } LOG.debug("Output (default {}) name is {}", outputDefault, output); // Special logic to set the FileProcessor output if (output.equals(STD_OUT_STR)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputStream(System.out); } else if (!output.equals(outputDefault)) { final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class); fileProcessor.setOutputFile(output); } // This could be easily configured through CLI or properties final List<String> responseGroups = Lists.newArrayList(); for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES, ResponseGroup.ITEM_ATTRIBUTES }) { responseGroups.add(responseGroup.getResponseGroupName()); } final String responseGroupString = Joiner.on(",").join(responseGroups); // Search the list of remaining ASINs final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class); fetcher.setProcessedFile(processedFile); fetcher.setRequestWait(requestWait); fetcher.setInputStream(inputStream); fetcher.setResponseGroups(responseGroupString); // This ensures that statistics of processed asins should almost always get printed at the end Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { fetcher.logStatistics(); } }); fetcher.fetchProductInformation(); } } }
From source file:com.act.analysis.surfactant.SurfactantLabeler.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w w w . ja v a 2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File inputFile = new File(cl.getOptionValue(OPTION_INPUT_FILE)); if (!inputFile.isFile()) { System.err.format("No input file at: %s\n", inputFile.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_FILE)); if (outputFile.exists()) { System.err.format("WARNING: output file at %s already exists\n", outputFile.getAbsolutePath()); } /* Sometimes the InChIs might not appear in the input file (like in regression results). Instead a corpus of * names and InChIs can be specified in a separate file and looked up as molecules are read/visualized. The join * field is the key on which the InChI for a given row in the input file is found. */ File inchiSourceFile = null; if (cl.hasOption(OPTION_INCHI_SOURCE)) { inchiSourceFile = new File(cl.getOptionValue(OPTION_INCHI_SOURCE)); boolean err = false; if (!inchiSourceFile.isFile()) { System.err.format("No inchi source file at: %s\n", inchiSourceFile.getAbsolutePath()); err = true; } if (!cl.hasOption(OPTION_INCHI_SOURCE_JOIN_FIELD)) { System.err.format("Must specify a join field when using an inchi source file.\n"); err = true; } if (err) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } } SurfactantLabeler surfactantLabeler = new SurfactantLabeler(); surfactantLabeler.runAnalysis(cl.getOptionValue(OPTION_LICENSE_FILE), inputFile, outputFile, inchiSourceFile, cl.getOptionValue(OPTION_INCHI_SOURCE_JOIN_FIELD)); }
From source file:com.act.utils.parser.UniprotInterpreter.java
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, CompoundNotFoundException { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from w w w . j ava 2 s.com*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH)); if (!uniprotFile.exists()) { String msg = "Uniprot file path is null"; LOGGER.error(msg); throw new RuntimeException(msg); } else { UniprotInterpreter reader = new UniprotInterpreter(uniprotFile); reader.init(); } }
From source file:com.act.reachables.ConditionalReachabilityInterpreter.java
public static void main(String[] args) throws Exception { // Parse the command line options Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from ww w . ja v a2 s. com } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(BingSearchRanker.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(BingSearchRanker.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } String inputPath = cl.getOptionValue(OPTION_INPUT_ACT_FILEPATH); String outputPath = cl.getOptionValue(OPTION_OUTPUT_FILEPATH); String dbName = cl.getOptionValue(OPTION_DB_NAME); LOGGER.info("Starting to deserialize reachables forest."); ActData.instance().deserialize(inputPath); ActData actData = ActData.instance(); LOGGER.info("Finished deserializing reachables forest."); NoSQLAPI db = new NoSQLAPI(dbName, dbName); ConditionalReachabilityInterpreter conditionalReachabilityInterpreter = new ConditionalReachabilityInterpreter( actData, db); conditionalReachabilityInterpreter.run(outputPath); }
From source file:com.act.biointerpretation.BiointerpretationDriver.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//ww w . j ava2s .c om } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } if (cl.hasOption(OPTION_CONFIGURATION_FILE)) { List<BiointerpretationStep> steps; File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE)); if (!configFile.exists()) { String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath()); LOGGER.error(msg); throw new RuntimeException(msg); } // Read the whole config file. try (InputStream is = new FileInputStream(configFile)) { steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() { }); } catch (IOException e) { LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage()); throw e; // Crash after logging if the config file can't be read. } // Ask for explicit confirmation before dropping databases. LOGGER.info("Biointerpretation plan:"); for (BiointerpretationStep step : steps) { crashIfInvalidDBName(step.getReadDBName()); crashIfInvalidDBName(step.getWriteDBName()); LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName()); } LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences"); LOGGER.info("Proceed? [y/n]"); String readLine; try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { readLine = reader.readLine(); } readLine.trim(); if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) { LOGGER.info("Biointerpretation plan confirmed, commencing"); for (BiointerpretationStep step : steps) { performOperation(step, true); } LOGGER.info("Biointerpretation plan completed"); } else { LOGGER.info("Biointerpretation plan not confirmed, exiting"); } } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) { if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) { String msg = "Must specify read and write DB names when performing a single operation"; LOGGER.error(msg); throw new RuntimeException(msg); } BiointerpretationOperation operation; try { operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION)); } catch (IllegalArgumentException e) { LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s", cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage()); throw e; // Crash if we can't interpret the operation. } String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB)); String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB)); performOperation(new BiointerpretationStep(operation, readDB, writeDB), false); } else { String msg = "Must specify either a config file or a single operation to perform."; LOGGER.error(msg); throw new RuntimeException(msg); } }