List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:com.act.lcms.db.io.LoadConstructAnalysisTableIntoDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required() .longOpt("input-file").build()); // DB connection options. opts.addOption(Option.builder().argName("database url") .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build()); opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg() .longOpt("db-user").build()); opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg() .longOpt("db-pass").build()); opts.addOption(Option.builder("H").argName("database host") .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host") .build());//from w w w . j ava 2s .c om opts.addOption(Option.builder("P").argName("database port") .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port") .build()); opts.addOption(Option.builder("N").argName("database name") .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg() .longOpt("db-name").build()); // Everybody needs a little help from their friends. opts.addOption( Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build()); 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()); HelpFormatter fmt = new HelpFormatter(); fmt.printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } if (cl.hasOption("help")) { new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true); return; } File inputFile = new File(cl.getOptionValue("input-file")); if (!inputFile.exists()) { System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file")); new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } DB db; if (cl.hasOption("db-url")) { db = new DB().connectToDB(cl.getOptionValue("db-url")); } else { Integer port = null; if (cl.getOptionValue("P") != null) { port = Integer.parseInt(cl.getOptionValue("P")); } db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"), cl.getOptionValue("p")); } try { db.getConn().setAutoCommit(false); ConstructAnalysisFileParser parser = new ConstructAnalysisFileParser(); parser.parse(inputFile); List<Pair<Integer, DB.OPERATION_PERFORMED>> results = ChemicalAssociatedWithPathway .insertOrUpdateChemicalsAssociatedWithPathwayFromParser(db, parser); if (results != null) { for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) { System.out.format("%d: %s\n", r.getLeft(), r.getRight()); } } // If we didn't encounter an exception, commit the transaction. db.getConn().commit(); } catch (Exception e) { System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n", e.getMessage()); db.getConn().rollback(); throw (e); } finally { db.getConn().close(); } }
From source file:com.twentyn.patentScorer.PatentScorer.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();// w w w . j a v a2s.c o m Options opts = new Options(); opts.addOption(Option.builder("i").longOpt("input").hasArg().required() .desc("Input file or directory to score").build()); opts.addOption(Option.builder("o").longOpt("output").hasArg().required() .desc("Output file to which to write score JSON").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()); 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("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"); } String inputFileOrDir = cmdLine.getOptionValue("input"); File splitFileOrDir = new File(inputFileOrDir); if (!(splitFileOrDir.exists())) { LOGGER.error("Unable to find directory at " + inputFileOrDir); System.exit(1); } try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"))) { PatentScorer scorer = new PatentScorer(PatentModel.getModel(), writer); PatentCorpusReader corpusReader = new PatentCorpusReader(scorer, splitFileOrDir); corpusReader.readPatentCorpus(); } }
From source file:microbiosima.Microbiosima.java
/** * @param args/* w w w . j ava 2 s .com*/ * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { //Init with default values int populationSize = 500; int microSize = 1000; int numberOfSpecies = 150; int numberOfGeneration = 10000; int numberOfObservation = 100; int numberOfReplication = 1; double pctEnv = 0; double pctPool = 0; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation" + " [default: 500 1000 150 10000]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 2) { System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n"); System.out.println(sb.toString()); // System.exit(3); // LogNormalDistribution lgd=new LogNormalDistribution(0,1); // environment=lgd.sample(150); // double environment_sum=0; // for (int i=0;i<No;i++){ // environment_sum+=environment[i]; // } // for (int i=0;i<No;i++){ // environment[i]/=environment_sum; // } double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0, 0); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); file3.print(population.betaDiversity(true)); file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); } population.getNextGen(); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:dyco4j.instrumentation.internals.CLI.java
public static void main(final String[] args) throws IOException { final Options _options = new Options(); _options.addOption(Option.builder().longOpt(IN_FOLDER_OPTION).required().hasArg(true) .desc("Folders containing the classes to be instrumented.").build()); _options.addOption(Option.builder().longOpt(OUT_FOLDER_OPTION).required().hasArg(true) .desc("Folder containing the classes (as descendants) with instrumentation.").build()); _options.addOption(Option.builder().longOpt(CLASSPATH_CONFIG_OPTION).hasArg(true) .desc("File containing class path (1 entry per line) used by classes to be instrumented.").build()); final String _msg = MessageFormat.format("Regex identifying the methods to be instrumented. Default: {0}.", METHOD_NAME_REGEX);//www . j a va 2 s. c o m _options.addOption(Option.builder().longOpt(METHOD_NAME_REGEX_OPTION).hasArg(true).desc(_msg).build()); _options.addOption(Option.builder().longOpt(TRACE_ARRAY_ACCESS_OPTION).hasArg(false) .desc("Instrument to trace array access.").build()); _options.addOption(Option.builder().longOpt(TRACE_FIELD_ACCESS_OPTION).hasArg(false) .desc("Instrument to trace field access.").build()); _options.addOption(Option.builder().longOpt(TRACE_METHOD_ARGUMENTS_OPTION).hasArg(false) .desc("Instrument to trace method arguments.").build()); _options.addOption(Option.builder().longOpt(TRACE_METHOD_CALL_OPTION).hasArg(false) .desc("Instrument to trace method calls (compile-time signatures).").build()); _options.addOption(Option.builder().longOpt(TRACE_METHOD_RETURN_VALUE_OPTION).hasArg(false) .desc("Instrument to trace method return values.").build()); try { final CommandLine _cmdLine = new DefaultParser().parse(_options, args); extendClassPath(_cmdLine); processCommandLine(_cmdLine); } catch (final ParseException _ex1) { new HelpFormatter().printHelp(CLI.class.getName(), _options); } }
From source file:com.ibm.zurich.Main.java
public static void main(String[] args) throws NoSuchAlgorithmException, IOException { Option help = new Option(HELP, "print this message"); Option version = new Option(VERSION, "print the version information"); Options options = new Options(); Option useCurve = Option.builder(USECURVE).hasArg().argName("curve") .desc("Specify the BN Curve. Options: " + curveOptions()).build(); Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL") .desc("Generate Issuer key pair and empty revocation list and store it in files").build(); Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1") .desc("Create an authenticator secret key and perform the first step of the join protocol").build(); Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2") .desc("Complete the join protocol").build(); Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL") .desc("Verify a signature").build(); Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig") .desc("create a signature").build(); options.addOption(help);/*w w w . j av a 2 s . co m*/ options.addOption(version); options.addOption(useCurve); options.addOption(isskeygen); options.addOption(sign); options.addOption(verify); options.addOption(join1); options.addOption(join2); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new DefaultParser(); //FIXME Choose a proper instantiation of SecureRandom depending on the platform SecureRandom random = new SecureRandom(); Base64.Encoder encoder = Base64.getUrlEncoder(); Base64.Decoder decoder = Base64.getUrlDecoder(); try { CommandLine line = parser.parse(options, args); BNCurveInstantiation instantiation = null; BNCurve curve = null; if (line.hasOption(HELP) || line.getOptions().length == 0) { formatter.printHelp(USAGE, options); } else if (line.hasOption(VERSION)) { System.out.println("Version " + Main.class.getPackage().getImplementationVersion()); } else if (line.hasOption(USECURVE)) { instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE)); curve = new BNCurve(instantiation); } else { System.out.println("Specify the curve to use."); return; } if (line.hasOption(IKEYGEN)) { String[] optionValues = line.getOptionValues(IKEYGEN); // Create secret key IssuerSecretKey sk = Issuer.createIssuerKey(curve, random); // Store pk writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]); // Store sk writeToFile(sk.toJson(curve), optionValues[1]); // Create empty revocation list and store HashSet<BigInteger> rl = new HashSet<BigInteger>(); writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]); } else if (line.hasOption(SIGN)) { //("ipk><authsk><msg2><appId><krd><sig") String[] optionValues = line.getOptionValues(SIGN); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1]))); JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2])); // setup a new authenticator Authenticator auth = new Authenticator(curve, ipk, authsk); auth.EcDaaJoin1(curve.getRandomModOrder(random)); if (auth.EcDaaJoin2(msg2)) { EcDaaSignature sig = auth.EcDaaSign(optionValues[3]); // Write krd to file writeToFile(sig.krd, optionValues[4]); // Write signature to file writeToFile(sig.encode(curve), optionValues[5]); System.out.println("Signature written to " + optionValues[5]); } else { System.out.println("JoinMsg2 invalid"); } } else if (line.hasOption(VERIFY)) { Verifier ver = new Verifier(curve); String[] optionValues = line.getOptionValues(VERIFY); String pkFile = optionValues[0]; String sigFile = optionValues[1]; String krdFile = optionValues[2]; String appId = optionValues[3]; String rlPath = optionValues[4]; byte[] krd = Files.readAllBytes(Paths.get(krdFile)); IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile)); EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve); boolean valid = ver.verify(sig, appId, pk, Verifier.revocationListFromJson(readStringFromFile(rlPath), curve)); System.out.println("Signature is " + (valid ? "valid." : "invalid.")); } else if (line.hasOption(JOIN1)) { String[] optionValues = line.getOptionValues(JOIN1); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); // Create authenticator key BigInteger sk = curve.getRandomModOrder(random); writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]); Authenticator auth = new Authenticator(curve, ipk, sk); JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random)); writeToFile(msg1.toJson(curve), optionValues[2]); } else if (line.hasOption(JOIN2)) { String[] optionValues = line.getOptionValues(JOIN2); // create issuer with the specified key IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1])); Issuer iss = new Issuer(curve, sk, pk); JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2])); // Note that we do not check for nonce freshness. JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false); if (msg2 == null) { System.out.println("Join message invalid."); } else { System.out.println("Join message valid, msg2 written to file."); writeToFile(msg2.toJson(curve), optionValues[3]); } } } catch (ParseException e) { System.out.println("Error parsing input."); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:microbiosima.SelectiveMicrobiosima.java
/** * @param args/*from w w w . ja v a 2 s . c om*/ * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int populationSize = 500;//Integer.parseInt(parameters[1]); int microSize = 1000;//Integer.parseInt(parameters[2]); int numberOfSpecies = 150;//Integer.parseInt(parameters[3]); int numberOfGeneration = 10000; int Ngene = 10; int numberOfObservation = 100; int numberOfReplication = 10; double Ngenepm = 5; double pctEnv = 0; double pctPool = 0; double msCoeff = 1; double hsCoeff = 1; boolean HMS_or_TMS = true; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe" + " [default: 500 1000 150 10000 10 5]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + " msCoeff Parameter related to microbe selection strength\n" + " hsCoeff Parameter related to host selection strength\n" + " HMS_or_TMS String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 5) { System.out.println( "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); msCoeff = Double.parseDouble(pct_config[2]); hsCoeff = Double.parseDouble(pct_config[3]); if (pct_config[4].equals("HMS")) HMS_or_TMS = true; if (pct_config[4].equals("TMS")) HMS_or_TMS = false; if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } if (msCoeff < 1) { System.out.println( "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff=" + msCoeff + ")! EXIT"); System.exit(3); } if (hsCoeff < 1) { System.out.println( "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff=" + hsCoeff + ")! EXIT"); System.exit(3); } if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) { System.out.println( "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS=" + pct_config[4] + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); Ngene = Integer.parseInt(configs[4]); Ngenepm = Double.parseDouble(configs[5]); if (Ngenepm > Ngene) { System.out.println( "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT"); System.exit(3); } } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication) .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ") .append(Ngenepm).append("\n"); System.out.println(sb.toString()); double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } int[] fitnessToHost = new int[Ngene]; int[] fitnessToMicrobe = new int[Ngene]; for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix; if (HMS_or_TMS) sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt"; else sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); PrintWriter file7 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix))); PrintWriter file8 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix))); PrintWriter file9 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix))); PrintWriter file10 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix))); PrintWriter file11 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix))); PrintWriter file12 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix))); for (int i = 0; i < Ngene; i++) { fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1; fitnessToHost[i] = MathUtil.getNextInt(2) - 1; } MathUtil.setSeed(rep % numberOfReplication); SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm, msCoeff, fitnessToHost, fitnessToMicrobe); MathUtil.setSeed(); SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize, pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { //file1.print(population.gammaDiversity(false)); //file2.print(population.alphaDiversity(false)); //file1.print("\t"); //file2.print("\t"); file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); //file3.print(population.betaDiversity(true)); //file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); file7.print(population.averageHostFitness()); file7.print("\t"); file7.println(population.varianceHostFitness()); file8.println(population.cosOfMH()); file9.println(population.printOutHFitness()); file10.println(population.printOutMFitness()); file11.println(population.printBacteriaContents()); } population.getNextGen(); } for (SelectiveIndividual host : population.getIndividuals()) { file12.println(host.printBacteriaContents()); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); file7.close(); file8.close(); file9.close(); file10.close(); file11.close(); file12.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:it.anyplace.sync.client.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("C", "set-config", true, "set config file for s-client"); options.addOption("c", "config", false, "dump config"); options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers"); options.addOption("q", "query", true, "query directory server for device id"); options.addOption("d", "discovery", true, "discovery local network for device id"); options.addOption("p", "pull", true, "pull file from network"); options.addOption("P", "push", true, "push file to network"); options.addOption("o", "output", true, "set output file/directory"); options.addOption("i", "input", true, "set input file/directory"); options.addOption("lp", "list-peers", false, "list peer addresses"); options.addOption("a", "address", true, "use this peer addresses"); options.addOption("L", "list-remote", false, "list folder (root) content from network"); options.addOption("I", "list-info", false, "dump folder info from network"); options.addOption("li", "list-info", false, "list folder info from local db"); // options.addOption("l", "list-local", false, "list folder content from local (saved) index"); options.addOption("s", "search", true, "search local index for <term>"); options.addOption("D", "delete", true, "push delete to network"); options.addOption("M", "mkdir", true, "push directory create to network"); options.addOption("h", "help", false, "print help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("s-client", options); return;/*from ww w.ja v a2 s .c om*/ } File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C")) : new File(System.getProperty("user.home"), ".s-client.properties"); logger.info("using config file = {}", configFile); ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile); FileUtils.cleanDirectory(configuration.getTemp()); KeystoreHandler.newLoader().loadAndStore(configuration); if (cmd.hasOption("c")) { logger.info("configuration =\n{}", configuration.newWriter().dumpToString()); } else { logger.trace("configuration =\n{}", configuration.newWriter().dumpToString()); } logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace()); if (cmd.hasOption("sp")) { List<String> peers = Lists.newArrayList(Lists.transform( Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() { @Override public String apply(String input) { return input.trim(); } })); logger.info("set peers = {}", peers); configuration.edit().setPeers(Collections.<DeviceInfo>emptyList()); for (String peer : peers) { KeystoreHandler.validateDeviceId(peer); configuration.edit().addPeers(new DeviceInfo(peer, null)); } configuration.edit().persistNow(); } if (cmd.hasOption("q")) { String deviceId = cmd.getOptionValue("q"); logger.info("query device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId); logger.info("server response = {}", deviceAddresses); } if (cmd.hasOption("d")) { String deviceId = cmd.getOptionValue("d"); logger.info("discovery device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId); logger.info("local response = {}", deviceAddresses); } if (cmd.hasOption("p")) { String path = cmd.getOptionValue("p"); logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) { InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete() .getInputStream(); String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName(); File file; if (cmd.hasOption("o")) { File param = new File(cmd.getOptionValue("o")); file = param.isDirectory() ? new File(param, fileName) : param; } else { file = new File(fileName); } FileUtils.copyInputStreamToFile(inputStream, file); logger.info("saved file to = {}", file.getAbsolutePath()); } } if (cmd.hasOption("P")) { String path = cmd.getOptionValue("P"); File file = new File(cmd.getOptionValue("i")); checkArgument(!path.startsWith("/")); //TODO check path syntax logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file), folder, path)) { while (!fileUploadObserver.isCompleted()) { fileUploadObserver.waitForProgressUpdate(); logger.debug("upload progress {}", fileUploadObserver.getProgressMessage()); } logger.info("uploaded file to network"); } } if (cmd.hasOption("D")) { String path = cmd.getOptionValue("D"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("delete path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDelete(folder, path)) { observer.waitForComplete(); logger.info("deleted path"); } } if (cmd.hasOption("M")) { String path = cmd.getOptionValue("M"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("dir path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDir(folder, path)) { observer.waitForComplete(); logger.info("uploaded dir to network"); } } if (cmd.hasOption("L")) { try (SyncthingClient client = new SyncthingClient(configuration)) { client.waitForRemoteIndexAquired(); for (String folder : client.getIndexHandler().getFolderList()) { try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder() .setFolder(folder).build()) { logger.info("list folder = {}", indexBrowser.getFolder()); for (FileInfo fileInfo : indexBrowser.listFiles()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } } } } if (cmd.hasOption("I")) { try (SyncthingClient client = new SyncthingClient(configuration)) { if (cmd.hasOption("a")) { String deviceId = cmd.getOptionValue("a").substring(0, 63), address = cmd.getOptionValue("a").substring(64); try (BlockExchangeConnectionHandler connection = client.getConnection( DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) { client.getIndexHandler().waitForRemoteIndexAquired(connection); } } else { client.waitForRemoteIndexAquired(); } String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("li")) { try (SyncthingClient client = new SyncthingClient(configuration)) { String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("lp")) { try (SyncthingClient client = new SyncthingClient(configuration); DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler() .newDeviceAddressSupplier()) { String deviceAddressesStr = ""; for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) { deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : " + deviceAddress.getAddress(); } logger.info("device addresses:\n{}\n", deviceAddressesStr); } } if (cmd.hasOption("s")) { String term = cmd.getOptionValue("s"); try (SyncthingClient client = new SyncthingClient(configuration); IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) { client.waitForRemoteIndexAquired(); logger.info("search term = '{}'", term); IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term); if (event.hasGoodResults()) { logger.info("search results for term = '{}' :", term); for (FileInfo fileInfo : event.getResultList()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } else if (event.hasTooManyResults()) { logger.info("too many results found for term = '{}'", term); } else { logger.info("no result found for term = '{}'", term); } } } // if (cmd.hasOption("l")) { // String indexDump = new IndexHandler(configuration).dumpIndex(); // logger.info("index dump = \n\n{}\n", indexDump); // } IOUtils.closeQuietly(configuration); }
From source file:com.examples.cloud.speech.SyncRecognizeClient.java
public static void main(String[] args) throws Exception { String audioFile = ""; String host = "speech.googleapis.com"; Integer port = 443;//from w w w. ja v a 2 s.c om Integer sampling = 16000; CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").hasArg() .withArgName("FILE_PATH").create()); options.addOption( OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com") .hasArg().withArgName("ENDPOINT").create()); options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg() .withArgName("PORT").create()); options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000") .hasArg().withArgName("RATE").create()); try { CommandLine line = parser.parse(options, args); if (line.hasOption("uri")) { audioFile = line.getOptionValue("uri"); } else { System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw)."); System.exit(1); } if (line.hasOption("host")) { host = line.getOptionValue("host"); } else { System.err.println("An API enpoint must be specified (typically speech.googleapis.com)."); System.exit(1); } if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } else { System.err.println("An SSL port must be specified (typically 443)."); System.exit(1); } if (line.hasOption("sampling")) { sampling = Integer.parseInt(line.getOptionValue("sampling")); } else { System.err.println("An Audio sampling rate must be specified."); System.exit(1); } } catch (ParseException exp) { System.err.println("Unexpected exception:" + exp.getMessage()); System.exit(1); } ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port); SyncRecognizeClient client = new SyncRecognizeClient(channel, URI.create(audioFile), sampling); try { client.recognize(); } finally { client.shutdown(); } }
From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java
/** * @param args/*from w w w . ja v a 2s . c o m*/ */ public static void main(String[] args) { Options options = createOptions(); CommandLineParser parser = new DefaultParser(); int returnValue = 0; boolean dontExit = false; try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printHelp(options); return; } if (commandLine.hasOption("de")) dontExit = true; String senderKey = null; String senderPass = null; if (commandLine.hasOption("sk")) senderKey = commandLine.getOptionValue("sk"); if (commandLine.hasOption("sp")) senderPass = commandLine.getOptionValue("sp"); LicenseManagerDeployer manager = new LicenseManagerDeployer(); try { manager.init(senderKey, senderPass); long currentMili = 0; EthValue balance = null; if (commandLine.hasOption("calcDeploymendCost")) { currentMili = System.currentTimeMillis(); balance = manager.ethereum.getBalance(manager.sender); } if (commandLine.hasOption("observeBlock")) { manager.ethereum.events().observeBlocks() .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts)); } if (commandLine.hasOption("f")) { String[] values = commandLine.getOptionValues("f"); String filename = values[0]; String isCompiled = values[1]; manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled)); } if (commandLine.hasOption("millis")) { manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis"))); } if (commandLine.hasOption("c")) { String[] values = commandLine.getOptionValues("c"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: paymentAddress,name"); System.out.println(""); printHelp(options); return; } String paymentAddress = values[0]; String name = values[1]; manager.deployLicenseManager(EthAddress.of(paymentAddress), name); } else if (commandLine.hasOption("l")) { String contractAddress = commandLine.getOptionValue("l"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.listContractData(EthAddress.of(contractAddress)); } else if (commandLine.hasOption("cic")) { String[] values = commandLine.getOptionValues("cic"); if (values == null || values.length != 6) { System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String itemName = values[1]; String textHash = values[2]; String url = values[3]; String lifeTime = values[4]; String price = values[5]; manager.setManager(EthAddress.of(contractAddress)); manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime), Integer.parseInt(price)); } else if (commandLine.hasOption("bli")) { String[] values = commandLine.getOptionValues("bli"); if (values == null || values.length < 2 || values.length > 3) { System.out.println( "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender."); System.out.println(""); printHelp(options); return; } String issuerAddress = values[0]; String name = values[1]; String address = values.length > 2 ? values[2] : null; manager.buyLicense(issuerAddress, name, address); } else if (commandLine.hasOption("v")) { String[] values = commandLine.getOptionValues("v"); String issuerAddress = values[0]; String message = values[1]; String signature = values[2]; String publicKey = values[3]; manager.verifyLicense(issuerAddress, message, signature, publicKey); } else if (commandLine.hasOption("cs")) { String message = commandLine.getOptionValue("cs"); if (message == null) { System.out.println("Error. Need 1 parameter: message"); System.out.println(""); printHelp(options); return; } String signature = createSignature(manager.sender, message); String publicKeyString = toPublicKeyString(manager.sender); System.out.println("The signature for the message is:"); System.out.println(signature); System.out.println("The public key is:"); System.out.println(publicKeyString); } else if (commandLine.hasOption("co")) { String[] values = commandLine.getOptionValues("co"); if (values == null || values.length != 2) { System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress"); System.out.println(""); printHelp(options); return; } String contractAddress = values[0]; String newOwner = values[1]; manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner)); } else if (commandLine.hasOption("si")) { String contractAddress = commandLine.getOptionValue("si"); if (contractAddress == null) { System.out.println("Error. Need 1 parameters: contract address"); System.out.println(""); printHelp(options); return; } manager.setManager(EthAddress.of(contractAddress)); manager.stopIssue(contractAddress); } else if (commandLine.hasOption("ppuk")) { System.out.println("Public key: " + toPublicKeyString(manager.sender)); } if (manager.licenseManager != null && commandLine.hasOption("wca")) { String[] values = commandLine.getOptionValues("wca"); String filename = values[0]; File file = new File(filename); IOUtils.write( !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x() : manager.licenseManager.contractInstance .contracts(manager.licenseManager.contractInstance.contractCount() - 1) .withLeading0x(), new FileOutputStream(file), "UTF-8"); } if (commandLine.hasOption("calcDeploymendCost")) { balance = balance.minus(manager.ethereum.getBalance(manager.sender)); BigDecimal divide = new BigDecimal(balance.inWei()) .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L)); System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei() + " time need: " + (System.currentTimeMillis() - currentMili)); } } catch (Exception e) { System.out.println(e.getMessage()); printHelp(options); returnValue = 10; } } catch (ParseException e1) { System.out.println(e1.getMessage()); printHelp(options); returnValue = 10; } if (!dontExit) System.exit(returnValue); }
From source file:com.twentyn.patentScorer.ScoreMerger.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();/*from w w w.ja v a 2 s . co m*/ Options opts = new Options(); opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build()); opts.addOption(Option.builder("r").longOpt("results").required().hasArg() .desc("A directory of search results to read").build()); opts.addOption(Option.builder("s").longOpt("scores").required().hasArg() .desc("A directory of patent classification scores to read").build()); opts.addOption(Option.builder("o").longOpt("output").required().hasArg() .desc("The output file where results will be written.").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); } File scoresDirectory = new File(cmdLine.getOptionValue("scores")); if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) { LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores")); } File resultsDirectory = new File(cmdLine.getOptionValue("results")); if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) { LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results")); } FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output")); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); FilenameFilter jsonFilter = new FilenameFilter() { public final Pattern JSON_PATTERN = Pattern.compile("\\.json$"); public boolean accept(File dir, String name) { return JSON_PATTERN.matcher(name).find(); } }; Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>(); LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath()); for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) { BufferedReader reader = new BufferedReader(new FileReader(scoreFile)); int count = 0; String line; while ((line = reader.readLine()) != null) { PatentScorer.ClassificationResult res = objectMapper.readValue(line, PatentScorer.ClassificationResult.class); scores.put(res.docId, res); count++; } LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath()); } Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>(); Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>(); LOGGER.info("Reading results from directory at " + resultsDirectory); // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference. JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class, DocumentSearch.SearchResult.class); List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter)); Collections.sort(resultsFiles, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); for (File resultsFile : resultsFiles) { BufferedReader reader = new BufferedReader(new FileReader(resultsFile)); CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue()); int bytesRead = reader.read(buffer); LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is " + resultsFile.length() + ")"); List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()), resultsType); LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath()); int count = 0; for (DocumentSearch.SearchResult sres : results) { for (DocumentSearch.ResultDocument resDoc : sres.getResults()) { String docId = resDoc.getDocId(); PatentScorer.ClassificationResult classificationResult = scores.get(docId); if (classificationResult == null) { LOGGER.warn("No classification result found for " + docId); } else { resDoc.setClassifierScore(classificationResult.getScore()); } } if (!synonymsToResults.containsKey(sres.getSynonym())) { synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>()); } synonymsToResults.get(sres.getSynonym()).add(sres); count++; if (count % 1000 == 0) { LOGGER.info("Processed " + count + " search result documents"); } } } Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() { @Override public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) { int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore()); if (cmp != 0) { return cmp; } cmp = o2.getScore().compareTo(o1.getScore()); return cmp; } }; for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) { DocumentSearch.SearchResult newSearchRes = null; // Merge all result documents into a single search result. for (DocumentSearch.SearchResult sr : entry.getValue()) { if (newSearchRes == null) { newSearchRes = sr; } else { newSearchRes.getResults().addAll(sr.getResults()); } } if (newSearchRes == null || newSearchRes.getResults() == null) { LOGGER.error("Search results for " + entry.getKey() + " are null."); continue; } Collections.sort(newSearchRes.getResults(), resultDocumentComparator); if (!inchisToResults.containsKey(newSearchRes.getInchi())) { inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>()); } inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes); } List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet()); Collections.sort(sortedKeys); List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size()); Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() { @Override public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) { return o1.getSynonym().compareTo(o2.getSynonym()); } }; for (String inchi : sortedKeys) { List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi); Collections.sort(res, synonymSorter); orderedResults.add(new GroupedInchiResults(inchi, res)); } objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults); outputWriter.close(); }