List of usage examples for org.apache.commons.cli ParseException getMessage
public String getMessage()
From source file:de.fischer.thotti.core.runner.NDRunner.java
/** * Main method of the {@link NDRunner}.//from w w w . j av a 2 s .c om */ public static void main(String[] args) throws IOException { try { // @todo Evaluate --jopt-simple Options options = createCommandLineOption(); CommandLineParser parser = new GnuParser(); try { // parse the command line arguments org.apache.commons.cli.CommandLine line = parser.parse(options, args); if (line.hasOption("slave")) { if (!line.hasOption("executionid")) { throw new ParseException("Execution id is missing."); } String eid = line.getOptionValue("executionid"); int eidInt = Integer.valueOf(eid); new NDRunner().runSlaveMode(eidInt); } else { new NDRunner().runMasterMode(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } } catch (RunnerException e) { if (e.getCause() != null) { e.printStackTrace(System.err); System.err.println(); } System.err.println(e.getMessage()); System.exit(ERROR); } }
From source file:com.act.lcms.db.analysis.ConfigurableAnalysis.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 .j a va2 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 lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } File configFile = new File(cl.getOptionValue(OPTION_CONFIG_FILE)); if (!configFile.isFile()) { throw new IllegalArgumentException( String.format("Not a regular file at %s", configFile.getAbsolutePath())); } TSVParser parser = new TSVParser(); parser.parse(configFile); try (DB db = DB.openDBFromCLI(cl)) { System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); List<AnalysisStep> steps = new ArrayList<>(parser.getResults().size()); int i = 0; for (Map<String, String> row : parser.getResults()) { AnalysisStep step = mapToStep(db, i, row); if (step != null) { System.out.format("%d: %s '%s' %s %s %f %s\n", step.getIndex(), step.getKind(), step.getLabel(), step.getPlateBarcode(), step.getPlateCoords(), step.getExactMass(), step.getUseFineGrainedMZTolerance()); } steps.add(step); i++; } System.out.format("Running analysis\n"); runAnalysis(db, lcmsDir, cl.getOptionValue(OPTION_OUTPUT_PREFIX), steps, cl.hasOption(OPTION_USE_HEATMAP), fontScale, cl.hasOption(OPTION_USE_SNR)); } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java
public static void main(String[] args) throws IOException { if (logger == null) { System.out.println("About to initialize Log4j"); logger = LogManager.getLogger(); System.out.println("Finished initializing Log4j"); }/*from ww w . j a v a 2 s .c o m*/ logger.debug("Entering main()"); // WIP: the following command line code was pulled from FITS Options options = new Options(); Option inputFileOption = new Option(PARAM_I, true, "input file"); options.addOption(inputFileOption); options.addOption(PARAM_V, false, "print version information"); options.addOption(PARAM_H, false, "help information"); options.addOption(PARAM_O, true, "output sub-directory"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args, true); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); } // print version info if (cmd.hasOption(PARAM_V)) { if (StringUtils.isEmpty(applicationVersion)) { applicationVersion = "<not set>"; System.exit(1); } System.out.println("Version: " + applicationVersion); System.exit(0); } // print help info if (cmd.hasOption(PARAM_H)) { displayHelp(); System.exit(0); } // input parameter if (cmd.hasOption(PARAM_I)) { String input = cmd.getOptionValue(PARAM_I); boolean hasValue = cmd.hasOption(PARAM_I); logger.debug("Has option {} value: [{}]", PARAM_I, hasValue); String paramVal = cmd.getOptionValue(PARAM_I); logger.debug("value of option: [{}] ****", paramVal); File inputFile = new File(input); if (!inputFile.exists()) { logger.warn("{} does not exist or is not readable.", input); System.exit(1); } String subDir = cmd.getOptionValue(PARAM_O); PdfaConvert convert; if (!StringUtils.isEmpty(subDir)) { convert = new PdfaConvert(subDir); } else { convert = new PdfaConvert(); } if (inputFile.isDirectory()) { if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) { logger.warn("Input directory is empty, nothing to process."); System.exit(1); } else { logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(), inputFile.listFiles().length); DirectoryStream<Path> dirStream = null; dirStream = Files.newDirectoryStream(inputFile.toPath()); for (Path filePath : dirStream) { logger.debug("Have file name: {}", filePath.toString()); // Note: only handling files, not recursively going into sub-directories if (filePath.toFile().isFile()) { // Catch possible exception for each file so can handle other files in directory. try { convert.examine(filePath.toFile()); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", filePath.getFileName(), e.getMessage()); } } else { logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing } } dirStream.close(); } } else { logger.debug("About to process file: {}", inputFile.getPath()); try { convert.examine(inputFile); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage()); logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage(), e); } } } else { System.err.println("Missing required option: " + PARAM_I); displayHelp(); System.exit(-1); } System.exit(0); }
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 ww .j a va2 s .co 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:au.edu.flinders.ehl.filmweekly.FwImporter.java
/** * Main method for the class/* ww w . ja v a2s .c o m*/ * * @param args array of command line arguments */ public static void main(String[] args) { // before we do anything, output some useful information for (int i = 0; i < APP_HEADER.length; i++) { System.out.println(APP_HEADER[i]); } // parse the command line options CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(createOptions(), args); } catch (org.apache.commons.cli.ParseException e) { // something bad happened so output help message printCliHelp("Error in parsing options:\n" + e.getMessage()); } // get and check on the log4j properties path option if required if (cmd.hasOption("log4j") == true) { String log4jPath = cmd.getOptionValue("log4j"); if (FileUtils.isAccessible(log4jPath) == false) { printCliHelp("Unable to access the specified log4j properties file\n " + log4jPath); } // configure the log4j framework PropertyConfigurator.configure(log4jPath); } // get and check on the properties path option String propertiesPath = cmd.getOptionValue("properties"); if (FileUtils.isAccessible(propertiesPath) == false) { printCliHelp("Unable to access the specified properties file\n " + propertiesPath); } // get and check on the input file path option String inputPath = cmd.getOptionValue("input"); if (FileUtils.isAccessible(inputPath) == false) { printCliHelp("Unable to access the specified input file"); } // open the properties file Configuration config = null; try { config = new PropertiesConfiguration(propertiesPath); } catch (ConfigurationException e) { printCliHelp("Unable to read the properties file file: \n" + e.getMessage()); } // check to make sure all of the required configuration properties are present for (int i = 0; i < REQD_PROPERTIES.length; i++) { if (config.containsKey(REQD_PROPERTIES[i]) == false) { printCliHelp("Unable to find the required property: " + REQD_PROPERTIES[i]); } } if (cmd.hasOption("debug_coord_list") == true) { // output debug info logger.debug("undertaking the debug-coord-list task"); // undertake the debug coordinate list task if (FileUtils.doesFileExist(cmd.getOptionValue("debug_coord_list")) == true) { printCliHelp("the debug_coord_list file already exists"); } else { CoordList list = new CoordList(inputPath, cmd.getOptionValue("debug_coord_list")); try { list.openFiles(); list.doTask(); } catch (IOException e) { logger.error("unable to undertake the debug-coord-list task", e); errorExit(); } System.out.println("Task completed"); System.exit(0); } } if (cmd.hasOption("debug_json_list") == true) { // output debug info logger.debug("undertaking the debug-json-list task"); // undertake the debug coordinate list task if (FileUtils.doesFileExist(cmd.getOptionValue("debug_json_list")) == true) { printCliHelp("the debug_json_list file already exists"); } else { JsonList list = new JsonList(inputPath, cmd.getOptionValue("debug_json_list")); try { list.openFiles(); list.doTask(); } catch (IOException e) { logger.error("unable to undertake the debug_json_list task", e); errorExit(); } System.out.println("Task completed"); System.exit(0); } } // if no debug options present assume import System.out.println("Importing data into the database."); System.out.println( "*Note* if this input file has been processed before duplicate records *will* be created."); // get a connection to the database try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { logger.error("unable to load the MySQL database classes", e); errorExit(); } Connection database = null; //private static final String[] REQD_PROPERTIES = {"db-host", "db-user", "db-password", "db-name"}; String connectionString = "jdbc:mysql://" + config.getString(REQD_PROPERTIES[0]) + "/" + config.getString(REQD_PROPERTIES[1]) + "?user=" + config.getString(REQD_PROPERTIES[2]) + "&password=" + config.getString(REQD_PROPERTIES[3]); try { database = DriverManager.getConnection(connectionString); } catch (SQLException e) { logger.error("unable to connect to the MySQL database", e); errorExit(); } // do the import DataImporter importer = new DataImporter(database, inputPath); try { importer.openFiles(); importer.doTask(); System.out.println("Task completed"); System.exit(0); } catch (IOException e) { logger.error("unable to complete the import"); errorExit(); } catch (ImportException e) { logger.error("unable to complete the import"); errorExit(); } finally { // play nice and tidy up try { database.close(); } catch (SQLException e) { logger.error("Unable to close the database connection: ", e); } } }
From source file:com.google.flightmap.parsing.faa.amr.AviationMasterRecordParser.java
/** * Runs FAA Aviation Master Record parser with given command line arguments. *//*from www . j a v a2s .com*/ public static void main(String args[]) { CommandLine line = null; try { final CommandLineParser parser = new PosixParser(); line = parser.parse(OPTIONS, args); } catch (ParseException pEx) { System.err.println(pEx.getMessage()); printHelp(line); System.exit(1); } if (line.hasOption(HELP_OPTION)) { printHelp(line); System.exit(0); } final String airportSourceFile = line.getOptionValue(AIRPORT_MR_OPTION); final String runwaySourceFile = line.getOptionValue(RUNWAY_MR_OPTION); final String iataToIcaoFile = line.getOptionValue(IATA_TO_ICAO_OPTION); final String dbFile = line.getOptionValue(AVIATION_DB_OPTION); try { (new AviationMasterRecordParser(airportSourceFile, runwaySourceFile, iataToIcaoFile, dbFile)).execute(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }
From source file:com.continuent.tungsten.common.security.PasswordManagerCtrl.java
/** * Password Manager entry point//from w ww . ja v a 2 s. c o m * * @param argv * @throws Exception */ public static void main(String argv[]) throws Exception { pwd = new PasswordManagerCtrl(); // --- Options --- ClientApplicationType clientApplicationType = null; String securityPropertiesFileLocation = null; String username = null; String password = null; CommandLine line = null; try { CommandLineParser parser = new GnuParser(); // --- Parse the command line arguments --- // --- Help line = parser.parse(pwd.helpOptions, argv, true); if (line.hasOption(_HELP)) { DisplayHelpAndExit(EXIT_CODE.EXIT_OK); } // --- Program command line options line = parser.parse(pwd.options, argv); // --- Handle options --- // --- Optional arguments : Get options --- if (line.hasOption(_HELP)) { DisplayHelpAndExit(EXIT_CODE.EXIT_OK); } if (line.hasOption(_TARGET_APPLICATION)) // Target Application { String target = line.getOptionValue(TARGET_APPLICATION); clientApplicationType = PasswordManagerCtrl.getClientApplicationType(target); } if (line.hasOption(_FILE)) // security.properties file location { securityPropertiesFileLocation = line.getOptionValue(_FILE); } if (line.hasOption(_AUTHENTICATE)) { // Make sure username + password are provided String[] authenticateArgs = line.getOptionValues(_AUTHENTICATE); if (authenticateArgs.length < 2) throw new MissingArgumentException(authenticate); username = authenticateArgs[0]; password = authenticateArgs[1]; } if (line.hasOption(_CREATE)) { // Make sure username + password are provided String[] createArgs = line.getOptionValues(_CREATE); if (createArgs.length < 2) throw new MissingArgumentException(create); username = createArgs[0]; password = createArgs[1]; } // --- Options to replace values in security.properties file --- if (line.hasOption(_ENCRYPTED_PASSWORD)) pwd.useEncryptedPassword = true; if (line.hasOption(_TRUSTSTORE_LOCATION)) pwd.truststoreLocation = line.getOptionValue(_TRUSTSTORE_LOCATION); if (line.hasOption(_TRUSTSTORE_PASSWORD)) pwd.truststorePassword = line.getOptionValue(_TRUSTSTORE_PASSWORD); if (line.hasOption(_KEYSTORE_LOCATION)) pwd.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION); if (line.hasOption(_KEYSTORE_PASSWORD)) pwd.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD); if (line.hasOption(_PASSWORD_FILE_LOCATION)) pwd.passwordFileLocation = (String) line.getOptionValue(_PASSWORD_FILE_LOCATION); try { pwd.passwordManager = new PasswordManager(securityPropertiesFileLocation, clientApplicationType); AuthenticationInfo authenticationInfo = pwd.passwordManager.getAuthenticationInfo(); // --- Substitute with user provided options if (pwd.useEncryptedPassword != null) authenticationInfo.setUseEncryptedPasswords(pwd.useEncryptedPassword); if (pwd.truststoreLocation != null) authenticationInfo.setTruststoreLocation(pwd.truststoreLocation); if (pwd.truststorePassword != null) authenticationInfo.setTruststorePassword(pwd.truststorePassword); if (pwd.keystoreLocation != null) authenticationInfo.setKeystoreLocation(pwd.keystoreLocation); if (pwd.keystorePassword != null) authenticationInfo.setKeystorePassword(pwd.keystorePassword); if (pwd.passwordFileLocation != null) authenticationInfo.setPasswordFileLocation(pwd.passwordFileLocation); // --- Display summary of used parameters --- logger.info("Using parameters: "); logger.info("-----------------"); if (authenticationInfo.getParentPropertiesFileLocation() != null) logger.info(MessageFormat.format("security.properties \t = {0}", authenticationInfo.getParentPropertiesFileLocation())); logger.info(MessageFormat.format("password_file.location \t = {0}", authenticationInfo.getPasswordFileLocation())); logger.info(MessageFormat.format("encrypted.password \t = {0}", authenticationInfo.isUseEncryptedPasswords())); // --- Keystore if (line.hasOption(_AUTHENTICATE)) { logger.info(MessageFormat.format("keystore.location \t = {0}", authenticationInfo.getKeystoreLocation())); logger.info(MessageFormat.format("keystore.password \t = {0}", authenticationInfo.getKeystorePassword())); } // --- Truststore if (authenticationInfo.isUseEncryptedPasswords()) { logger.info(MessageFormat.format("truststore.location \t = {0}", authenticationInfo.getTruststoreLocation())); logger.info(MessageFormat.format("truststore.password \t = {0}", authenticationInfo.getTruststorePassword())); } logger.info("-----------------"); // --- AuthenticationInfo consistency check // Try to create files if possible pwd.passwordManager.try_createAuthenticationInfoFiles(); authenticationInfo.checkAndCleanAuthenticationInfo(); } catch (ConfigurationException ce) { logger.error(MessageFormat.format( "Could not retrieve configuration information: {0}\nTry to specify a security.properties file location, provide options on the command line, or have the cluster.home variable set.", ce.getMessage())); System.exit(EXIT_CODE.EXIT_ERROR.value); } catch (ServerRuntimeException sre) { logger.error(sre.getLocalizedMessage()); // AuthenticationInfo consistency check : failed DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR); } // --- Perform commands --- // ######### Authenticate ########## if (line.hasOption(_AUTHENTICATE)) { try { boolean authOK = pwd.passwordManager.authenticateUser(username, password); String msgAuthOK = (authOK) ? "SUCCESS" : "FAILED"; logger.info( MessageFormat.format("Authenticating {0}:{1} = {2}", username, password, msgAuthOK)); } catch (Exception e) { logger.error(MessageFormat.format("Error while authenticating user: {0}", e.getMessage())); } } // ######### Create ########## if (line.hasOption(_CREATE)) { try { pwd.passwordManager.setPasswordForUser(username, password); logger.info(MessageFormat.format("User created successfuly: {0}", username)); } catch (Exception e) { logger.error(MessageFormat.format("Error while creating user: {0}", e.getMessage())); } } // ########## DELETE ########## else if (line.hasOption(_DELETE)) { username = line.getOptionValue(_DELETE); try { pwd.passwordManager.deleteUser(username); logger.info(MessageFormat.format("User deleted successfuly: {0}", username)); } catch (Exception e) { logger.error(MessageFormat.format("Error while deleting user: {0}", e.getMessage())); } } } catch (ParseException exp) { logger.error(exp.getMessage()); DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR); } }
From source file:net.k3rnel.arena.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//from w w w . j a v a2 s . co 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:act.installer.bing.BingSearchRanker.java
public static void main(final String[] args) throws Exception { // Parse the command line options Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());// w w w .j a v a2s . 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(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_FILEPATH); String outputPath = cl.getOptionValue(OPTION_OUTPUT_FILEPATH); Boolean isTSVInput = cl.hasOption(OPTION_TSV_INPUT); // Read the molecule corpus LOGGER.info("Reading the input molecule corpus"); MoleculeCorpus moleculeCorpus = new MoleculeCorpus(); if (isTSVInput) { LOGGER.info("Input format is TSV"); moleculeCorpus.buildCorpusFromTSVFile(inputPath); } else { LOGGER.info("Input format is raw InChIs"); moleculeCorpus.buildCorpusFromRawInchis(inputPath); } // Get the inchi set Set<String> inchis = moleculeCorpus.getMolecules(); LOGGER.info("Found %d molecules in the input corpus", inchis.size()); // Update the Bing Search results in the Installer database BingSearchRanker bingSearchRanker = new BingSearchRanker(cl.hasOption(OPTION_INCLUDE_CHEBI_APPLICATIONS), cl.hasOption(OPTION_INCLUDE_WIKIPEDIA_URL), cl.hasOption(OPTION_INCLUDE_USAGE_EXPLORER_URL), cl.hasOption(OPTION_FORCE_UPDATE)); LOGGER.info("Updating the Bing Search results in the Installer database"); bingSearchRanker.addBingSearchResults(inchis); LOGGER.info("Done updating the Bing Search results"); // Write the results in a TSV file LOGGER.info("Writing results to output file"); bingSearchRanker.writeBingSearchRanksAsTSV(inchis, outputPath); LOGGER.info("Bing Search ranker is done. \"I'm tired, boss.\""); }
From source file:com.twentyn.patentSearch.DocumentSearch.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();//from w w w .j a va2 s . co m Options opts = new Options(); opts.addOption(Option.builder("x").longOpt("index").hasArg().required().desc("Path to index file to read") .build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build()); opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build()); opts.addOption(Option.builder("f").longOpt("field").hasArg().desc("The indexed field to search").build()); opts.addOption( Option.builder("q").longOpt("query").hasArg().desc("The query to use when searching").build()); opts.addOption(Option.builder("l").longOpt("list-file").hasArg() .desc("A file containing a list of queries to run in sequence").build()); opts.addOption( Option.builder("e").longOpt("enumerate").desc("Enumerate the documents in the index").build()); opts.addOption(Option.builder("d").longOpt("dump").hasArg() .desc("Dump terms in the document index for a specified field").build()); opts.addOption( Option.builder("o").longOpt("output").hasArg().desc("Write results JSON to this file.").build()); opts.addOption(Option.builder("n").longOpt("inchi-field").hasArg() .desc("The index of the InChI field if an input TSV is specified.").build()); opts.addOption(Option.builder("s").longOpt("synonym-field").hasArg() .desc("The index of the chemical synonym field if an input TSV is specified.").build()); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser cmdLineParser = new DefaultParser(); CommandLine cmdLine = null; try { cmdLine = cmdLineParser.parse(opts, args); } catch (ParseException e) { System.out.println("Caught exception when parsing command line: " + e.getMessage()); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("help")) { helpFormatter.printHelp("DocumentIndexer", opts); System.exit(0); } if (!(cmdLine.hasOption("enumerate") || cmdLine.hasOption("dump") || (cmdLine.hasOption("field") && (cmdLine.hasOption("query") || cmdLine.hasOption("list-file"))))) { System.out.println("Must specify one of 'enumerate', 'dump', or 'field' + {'query', 'list-file'}"); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("verbose")) { // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2 LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration ctxConfig = ctx.getConfiguration(); LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); logConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); LOGGER.debug("Verbose logging enabled"); } ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); LOGGER.info("Opening index at " + cmdLine.getOptionValue("index")); try (Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath()); IndexReader indexReader = DirectoryReader.open(indexDir);) { if (cmdLine.hasOption("enumerate")) { /* Enumerate all documents in the index. * With help from * http://stackoverflow.com/questions/2311845/is-it-possible-to-iterate-through-documents-stored-in-lucene-index */ for (int i = 0; i < indexReader.maxDoc(); i++) { Document doc = indexReader.document(i); LOGGER.info("Doc " + i + ":"); LOGGER.info(doc); } } else if (cmdLine.hasOption("dump")) { /* Dump indexed terms for a specific field. * With help from http://stackoverflow.com/questions/11148036/find-list-of-terms-indexed-by-lucene */ Terms terms = SlowCompositeReaderWrapper.wrap(indexReader).terms(cmdLine.getOptionValue("dump")); LOGGER.info("Has positions: " + terms.hasPositions()); LOGGER.info("Has offsets: " + terms.hasOffsets()); LOGGER.info("Has freqs: " + terms.hasFreqs()); LOGGER.info("Stats: " + terms.getStats()); LOGGER.info(terms); TermsEnum termsEnum = terms.iterator(); BytesRef br = null; while ((br = termsEnum.next()) != null) { LOGGER.info(" " + br.utf8ToString()); } } else { IndexSearcher searcher = new IndexSearcher(indexReader); String field = cmdLine.getOptionValue("field"); List<Pair<String, String>> queries = null; if (cmdLine.hasOption("query")) { queries = Collections.singletonList(Pair.of("", cmdLine.getOptionValue("query"))); } else if (cmdLine.hasOption("list-file")) { if (!(cmdLine.hasOption("inchi-field") && cmdLine.hasOption("synonym-field"))) { LOGGER.error("Must specify both inchi-field and synonym-field when using list-file."); System.exit(1); } Integer inchiField = Integer.parseInt(cmdLine.getOptionValue("inchi-field")); Integer synonymField = Integer.parseInt(cmdLine.getOptionValue("synonym-field")); queries = new LinkedList<>(); BufferedReader r = new BufferedReader(new FileReader(cmdLine.getOptionValue("list-file"))); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (!line.isEmpty()) { // TODO: use a proper TSV reader; this is intentionally terrible as is. String[] fields = line.split("\t"); queries.add(Pair.of(fields[inchiField].replace("\"", ""), fields[synonymField])); } } r.close(); } if (queries == null || queries.size() == 0) { LOGGER.error("Found no queries to run."); return; } List<SearchResult> searchResults = new ArrayList<>(queries.size()); for (Pair<String, String> queryPair : queries) { String inchi = queryPair.getLeft(); String rawQueryString = queryPair.getRight(); /* The Lucene query parser interprets the kind of structural annotations we see in chemical entities * as query directives, which is not what we want at all. Phrase queries seem to work adequately * with the analyzer we're currently using. */ String queryString = rawQueryString.trim().toLowerCase(); String[] parts = queryString.split("\\s+"); PhraseQuery query = new PhraseQuery(); for (String p : parts) { query.add(new Term(field, p)); } LOGGER.info("Running query: " + query.toString()); BooleanQuery bq = new BooleanQuery(); bq.add(query, BooleanClause.Occur.MUST); bq.add(new TermQuery(new Term(field, "yeast")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "ferment")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentation")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentive")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "saccharomyces")), BooleanClause.Occur.SHOULD); LOGGER.info(" Full query: " + bq.toString()); TopDocs topDocs = searcher.search(bq, 100); ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length == 0) { LOGGER.info("Search returned no results."); } List<ResultDocument> results = new ArrayList<>(scoreDocs.length); for (int i = 0; i < scoreDocs.length; i++) { ScoreDoc scoreDoc = scoreDocs[i]; Document doc = indexReader.document(scoreDoc.doc); LOGGER.info("Doc " + i + ": " + scoreDoc.doc + ", score " + scoreDoc.score + ": " + doc.get("id") + ", " + doc.get("title")); results.add(new ResultDocument(scoreDoc.doc, scoreDoc.score, doc.get("title"), doc.get("id"), null)); } LOGGER.info("----- Done with query " + query.toString()); // TODO: reduce memory usage when not writing results to an output file. searchResults.add(new SearchResult(inchi, rawQueryString, bq, results)); } if (cmdLine.hasOption("output")) { try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"));) { writer.write(objectMapper.writeValueAsString(searchResults)); } } } } }