List of usage examples for java.io File exists
public boolean exists()
From source file:com.linkedin.python.importer.ImporterCLI.java
public static void main(String[] args) throws Exception { Options options = createOptions();//w w w . j a v a 2 s.c o m CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("quite")) { Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(Level.WARN); } final File repoPath = new File(line.getOptionValue("repo")); final DependencySubstitution replacements = new DependencySubstitution(buildSubstitutionMap(line)); repoPath.mkdirs(); if (!repoPath.exists() || !repoPath.isDirectory()) { throw new RuntimeException( "Unable to continue, " + repoPath.getAbsolutePath() + " does not exist, or is not a directory"); } for (String dependency : line.getArgList()) { new DependencyDownloader(dependency, repoPath, replacements).download(); } logger.info("Execution Finished!"); }
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException//from w ww .j a va2 s .com * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }
From source file:com.act.lcms.db.io.LoadStandardIonAnalysisTableIntoDB.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 v a2s.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(LoadStandardIonAnalysisTableIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadStandardIonAnalysisTableIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File inputFile = new File(cl.getOptionValue(OPTION_FILE_PATH)); if (!inputFile.exists()) { System.err.format("Unable to find input file at %s\n", cl.getOptionValue(OPTION_FILE_PATH)); new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } try (DB db = DB.openDBFromCLI(cl)) { db.getConn().setAutoCommit(false); TSVParser parser = new TSVParser(); parser.parse(inputFile); for (Map<String, String> row : parser.getResults()) { Integer standardIonResultId = Integer.parseInt(row.get( ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.STANDARD_ION_RESULT_ID.name())); String dbValueOfMetlinIon = ExportStandardIonResultsFromDB.NULL_VALUE; StandardIonResult ionResult = StandardIonResult.getInstance().getById(db, standardIonResultId); if (ionResult.getManualOverrideId() != null) { // There is an existing manual override ion in the DB CuratedStandardMetlinIon curatedChemical = CuratedStandardMetlinIon.getBestMetlinIon(db, ionResult.getManualOverrideId()); dbValueOfMetlinIon = curatedChemical.getBestMetlinIon(); } String manualPickOfMetlinIon = row .get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name()); // If the manual metlin ion pick row is not NULL and it is not the same as the value stored in the DB, then // we need to add a new entry to the curated metlin ion table. if (!manualPickOfMetlinIon.equals(ExportStandardIonResultsFromDB.NULL_VALUE) && !manualPickOfMetlinIon.equals(dbValueOfMetlinIon)) { System.out.format("Manual override has been found, so updating the DB\n"); // A manual entry was created. if (!MS1.VALID_MS1_IONS.contains(manualPickOfMetlinIon)) { System.err.format("ERROR: found invalid chemical name: %s\n", manualPickOfMetlinIon); System.exit(-1); } String note = row.get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.NOTE.name()); CuratedStandardMetlinIon result = CuratedStandardMetlinIon.insertCuratedStandardMetlinIonIntoDB( db, LocalDateTime.now(CuratedStandardMetlinIon.utcDateTimeZone), cl.getOptionValue(OPTION_AUTHOR), manualPickOfMetlinIon, note, standardIonResultId); if (result == null) { System.err.format( "WARNING: Could not insert curated entry to the curated metlin ion table\n", manualPickOfMetlinIon); System.exit(-1); } else { StandardIonResult getIonResult = StandardIonResult.getInstance().getById(db, standardIonResultId); getIonResult.setManualOverrideId(result.getId()); if (!StandardIonResult.getInstance().update(db, getIonResult)) { System.err.format( "WARNING: Could not insert manual override id to the standard ion table\n", manualPickOfMetlinIon); System.exit(-1); } else { System.out.format( "Successfully committed updates to the standard ion table and the curated metlin ion table\n"); } } } } db.getConn().commit(); } }
From source file:com.act.lcms.db.io.LoadTSVIntoDB.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder("t").argName("type") .desc("The type of TSV data to read, options are: " + StringUtils.join(TSV_TYPE.values(), ", ")) .hasArg().required().longOpt("table-type").build()); 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 a v a 2s . c o m 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(LoadTSVIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } if (cl.hasOption("help")) { new HelpFormatter().printHelp(LoadTSVIntoDB.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(LoadTSVIntoDB.class.getCanonicalName(), opts, true); System.exit(1); } TSV_TYPE contentType = null; try { contentType = TSV_TYPE.valueOf(cl.getOptionValue("table-type")); } catch (IllegalArgumentException e) { System.err.format("Unrecognized TSV type '%s'\n", cl.getOptionValue("table-type")); new HelpFormatter().printHelp(LoadTSVIntoDB.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); TSVParser parser = new TSVParser(); parser.parse(inputFile); List<Pair<Integer, DB.OPERATION_PERFORMED>> results = null; switch (contentType) { case CURATED_CHEMICAL: results = CuratedChemical.insertOrUpdateCuratedChemicalsFromTSV(db, parser); break; case CONSTRUCT: results = ConstructEntry.insertOrUpdateCompositionMapEntriesFromTSV(db, parser); break; case CHEMICAL_OF_INTEREST: results = ChemicalOfInterest.insertOrUpdateChemicalOfInterestsFromTSV(db, parser); break; default: throw new RuntimeException(String.format("Unsupported TSV type: %s", contentType)); } 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:java2d.ps.EPSColorsExample.java
/** * Command-line interface//from w w w.j av a 2 s. com * * @param args * command-line arguments */ public static void main(final String[] args) { try { File targetDir; if (args.length >= 1) { targetDir = new File(args[0]); } else { targetDir = new File("."); } if (!targetDir.exists()) { System.err.println("Target Directory does not exist: " + targetDir); } generateEPSusingJava2D(new File(targetDir, "eps-example-colors.eps")); } catch (final Exception e) { e.printStackTrace(); } }
From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java
/** *//*from w ww .j ava 2 s .c om*/ public static void main(String argv[]) throws IOException { CommandLine cmd = null; Options options = new Options(); options.addOption("?", false, "Help for command-line"); options.addOption("n", true, "Number elts to emit"); try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, argv); } catch (ParseException pe) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(-1); } if (cmd.hasOption("?")) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(0); } int numToEmit = 100; if (cmd.hasOption("n")) { try { numToEmit = Integer.parseInt(cmd.getOptionValue("n")); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } String[] argArray = cmd.getArgs(); if (argArray.length == 0) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("GenerateRandomData", options, true); System.exit(0); } File inputSchemaFile = new File(argArray[0]).getCanonicalFile(); File outputDataFile = new File(argArray[1]).getCanonicalFile(); if (outputDataFile.exists()) { System.err.println("Output file already exists: " + outputDataFile.getCanonicalPath()); System.exit(0); } GenerateRandomData grd = new GenerateRandomData(); Schema schema = Schema.parse(inputSchemaFile); GenericDatumWriter datum = new GenericDatumWriter(schema); DataFileWriter out = new DataFileWriter(datum); out.create(schema, outputDataFile); try { for (int i = 0; i < numToEmit; i++) { out.append((GenericData.Record) grd.generateData(schema)); } } finally { out.close(); } }
From source file:com.jones_systems.Tieout.java
public static void main(String[] args) { String testFilename = null;//from w ww .j a va2 s . c o m Options options = new Options(); //options.addOption("f", "filename", true, "the file to use for the Tieout check"); Option filename = OptionBuilder.withArgName("filename").hasArg() .withDescription("the file name of the XML test file").create("filename"); options.addOption(filename); CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("filename")) { testFilename = line.getOptionValue("filename"); } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("tieout", options); System.exit(2); } } catch (ParseException exp) { } File testfile = new File(testFilename); if (!testfile.exists()) { System.err.println("Cannot find file!"); System.exit(1); } System.out.println("Starting test with file: " + testFilename); Tieout ts = new Tieout(testfile); boolean connected = ts.connectDatasources(); if (!connected) { System.err.print("Could not connect to all datasources"); System.exit(1); } ts.runTests(); }
From source file:Main.java
/** Index all text files under a directory. */ public static void main(String[] args) { String usage = "java IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "index"; String docsPath = null;//from w ww .j av a 2 s.co m boolean create = true; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { indexPath = args[i + 1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i + 1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final File docDir = new File(docsPath); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(new File(indexPath)); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_0, analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:io.anserini.search.SearchTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3")); options.addOption(/* w w w . jav a 2 s . c om*/ OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchTweets.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath()))); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile)); for (MicroblogTopic topic : topics) { Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER, topic.getQuery()); TopDocs rs = searcher.search(query, filter, numResults); RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter); RerankerCascade cascade = new RerankerCascade(context); if (cmdline.hasOption(RM3_OPTION)) { cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name)); cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } else { cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i = 0; i < docs.documents.length; i++) { String qid = topic.getId().replaceFirst("^MB0*", ""); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i], runtag)); } } reader.close(); out.close(); }
From source file:com.github.rnewson.couchdb.lucene.Main.java
/** * Run couchdb-lucene.//from w w w . ja va2 s .c om */ public static void main(String[] args) throws Exception { final HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration( Main.class.getClassLoader().getResource("couchdb-lucene.ini")); configuration.setReloadingStrategy(new FileChangedReloadingStrategy()); final File dir = new File(configuration.getString("lucene.dir", "indexes")); if (dir == null) { LOG.error("lucene.dir not set."); System.exit(1); } if (!dir.exists() && !dir.mkdir()) { LOG.error("Could not create " + dir.getCanonicalPath()); System.exit(1); } if (!dir.canRead()) { LOG.error(dir + " is not readable."); System.exit(1); } if (!dir.canWrite()) { LOG.error(dir + " is not writable."); System.exit(1); } LOG.info("Index output goes to: " + dir.getCanonicalPath()); final Server server = new Server(); final SelectChannelConnector connector = new SelectChannelConnector(); connector.setHost(configuration.getString("lucene.host", "localhost")); connector.setPort(configuration.getInt("lucene.port", 5985)); LOG.info("Accepting connections with " + connector); server.setConnectors(new Connector[] { connector }); server.setStopAtShutdown(true); server.setSendServerVersion(false); HttpClientFactory.setIni(configuration); final HttpClient httpClient = HttpClientFactory.getInstance(); final LuceneServlet servlet = new LuceneServlet(httpClient, dir, configuration); final Context context = new Context(server, "/", Context.NO_SESSIONS | Context.NO_SECURITY); context.addServlet(new ServletHolder(servlet), "/*"); context.addFilter(new FilterHolder(new GzipFilter()), "/*", Handler.DEFAULT); context.setErrorHandler(new JSONErrorHandler()); server.setHandler(context); server.start(); server.join(); }