List of usage examples for java.io File exists
public boolean exists()
From source file:act.installer.reachablesexplorer.PatentFinder.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(Loader.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); String host = cl.getOptionValue(OPTION_DB_HOST, DEFAULT_HOST); Integer port = Integer.parseInt(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_PORT.toString())); String targetDB = cl.getOptionValue(OPTION_TARGET_DB, DEFAULT_TARGET_DATABASE); String collection = cl.getOptionValue(OPTION_TARGET_REACHABLES_COLLECTION, DEFAULT_TARGET_COLLECTION); LOGGER.info("Connecting to %s:%d/%s, using collection %s", host, port, targetDB, collection); Loader loader = new Loader(host, port, UNUSED_SOURCE_DB, targetDB, collection, UNUSED_SEQUENCES_COLLECTION, UNUSED_ASSETS_DIR);/* w w w . j av a 2 s . c o m*/ File indexesTopDir = new File(cl.getOptionValue(OPTION_PATENT_INDEX_DIR, DEFAULT_PATENT_INDEX_LOCATION)); if (!indexesTopDir.exists() || !indexesTopDir.isDirectory()) { cliUtil.failWithMessage("Index top-level directory at %s is not a directory", indexesTopDir.getAbsolutePath()); } LOGGER.info("Using index top level dir: %s", indexesTopDir.getAbsolutePath()); PatentFinder finder = new PatentFinder(); try (Searcher searcher = Searcher.Factory.getInstance().build(indexesTopDir)) { finder.run(loader, searcher); } }
From source file:com.linkedin.helix.examples.ExampleProcess.java
public static void main(String[] args) throws Exception { String zkConnectString = "localhost:2181"; String clusterName = "storage-integration-cluster"; String instanceName = "localhost_8905"; String file = null;/*from w ww.j a v a 2 s. co m*/ String stateModelValue = "MasterSlave"; int delay = 0; boolean skipZeroArgs = true;// false is for dev testing if (!skipZeroArgs || args.length > 0) { CommandLine cmd = processCommandLineArgs(args); zkConnectString = cmd.getOptionValue(zkServer); clusterName = cmd.getOptionValue(cluster); String host = cmd.getOptionValue(hostAddress); String portString = cmd.getOptionValue(hostPort); int port = Integer.parseInt(portString); instanceName = host + "_" + port; file = cmd.getOptionValue(configFile); if (file != null) { File f = new File(file); if (!f.exists()) { System.err.println("static config file doesn't exist"); System.exit(1); } } stateModelValue = cmd.getOptionValue(stateModel); if (cmd.hasOption(transDelay)) { try { delay = Integer.parseInt(cmd.getOptionValue(transDelay)); if (delay < 0) { throw new Exception("delay must be positive"); } } catch (Exception e) { e.printStackTrace(); delay = 0; } } } // Espresso_driver.py will consume this System.out.println("Starting Process with ZK:" + zkConnectString); ExampleProcess process = new ExampleProcess(zkConnectString, clusterName, instanceName, file, stateModelValue, delay); process.start(); Thread.currentThread().join(); }
From source file:image.writer.ImageWriterExample2.java
/** * Command-line interface// www. j a va2s . com * @param args command-line arguments */ public static void main(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); } File outputFile = new File(targetDir, "eps-example2.tif"); ImageWriterExample2 app = new ImageWriterExample2(); app.generateBitmapUsingJava2D(outputFile, "image/tiff"); System.out.println("File written: " + outputFile.getCanonicalPath()); } catch (Exception e) { e.printStackTrace(); } }
From source file:cc.twittertools.search.local.RunQueries.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(//from ww w. jav a 2 s . c o m 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)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); 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(RunQueries.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); } boolean verbose = cmdline.hasOption(VERBOSE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation)); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } QueryParser p = new QueryParser(Version.LUCENE_43, StatusField.TEXT.name, IndexStatuses.ANALYZER); TrecTopicSet topics = TrecTopicSet.fromFile(new File(topicsFile)); for (TrecTopic topic : topics) { Query query = p.parse(topic.getQuery()); Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); TopDocs rs = searcher.search(query, filter, numResults); int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%s Q0 %s %d %f %s", topic.getId(), hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } } reader.close(); out.close(); }
From source file:de.petendi.ethereum.secure.proxy.Application.java
public static void main(String[] args) { try {//from w ww . ja v a 2 s. c o m cmdLineResult = new CmdLineResult(); cmdLineResult.parseArguments(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); System.out.println("Usage:"); cmdLineResult.printExample(); System.exit(-1); return; } File workingDirectory = new File(System.getProperty("user.home")); if (cmdLineResult.getWorkingDirectory().length() > 0) { workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile(); } ArgumentList argumentList = new ArgumentList(); argumentList.setWorkingDirectory(workingDirectory); File certificate = new File(workingDirectory, "seccoco-secured/cert.p12"); if (certificate.exists()) { char[] passwd = null; if (cmdLineResult.getPassword() != null) { System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!"); passwd = cmdLineResult.getPassword().toCharArray(); } else { Console console = System.console(); if (console != null) { passwd = console.readPassword("[%s]", "Enter application password:"); } else { System.out.print("No suitable console found for entering password"); System.exit(-1); } } argumentList.setTokenPassword(passwd); } try { SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList); seccoco = seccocoFactory.create(); } catch (InitializationException e) { System.out.println(e.getMessage()); System.exit(-1); } try { System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl()); URL url = new URL(cmdLineResult.getUrl()); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); String additionalHeaders = cmdLineResult.getAdditionalHeaders(); if (additionalHeaders != null) { StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ","); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":"); headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken()); } } settings = new Settings(cmdLineResult.isExposeWhisper(), headers); jsonRpcHttpClient = new JsonRpcHttpClient(url); jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener()); jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers); if (cmdLineResult.isExposeWhisper()) { jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers); } System.out.println("Connection succeeded"); } catch (Throwable e) { System.out.println("Connection failed: " + e.getMessage()); System.exit(-1); } SpringApplication app = new SpringApplication(Application.class); app.setBanner(new Banner() { @Override public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) { //send the Spring Boot banner to /dev/null } }); app.run(new String[] {}); }
From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java
public static void main(String[] args) { CommandLine cl = null;// w ww. jav a 2 s. c o m try { final CommandLineParser parser = new GnuParser(); cl = parser.parse(_options, args); } catch (ParseException e) { _log.error("Invalid arguments: " + e.getMessage()); reportInvalidArguments(); } final String[] directoryArgs = cl.getArgs(); if (directoryArgs.length != 2) { reportInvalidArguments(); } final File sourceDirectory = new File(directoryArgs[0]); if (!sourceDirectory.exists()) { _log.error(sourceDirectory.getPath() + " does not exist"); System.exit(1); } if (!sourceDirectory.isDirectory()) { _log.error(sourceDirectory.getPath() + " is not a directory"); System.exit(1); } final URI sourceDirectoryURI = sourceDirectory.toURI(); final File outputDirectory = new File(directoryArgs[1]); if (outputDirectory.exists() && !sourceDirectory.isDirectory()) { _log.error(outputDirectory.getPath() + " is not a directory"); System.exit(1); } final boolean isAvroMode = cl.hasOption('a'); final String predicateExpression = cl.getOptionValue('e'); final Predicate predicate = PredicateExpressionParser.parse(predicateExpression); final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null); int exitCode = 0; for (File sourceFile : sourceFiles) { try { final ValidationOptions val = new ValidationOptions(); val.setAvroUnionMode(isAvroMode); final SchemaParser schemaParser = new SchemaParser(); schemaParser.setValidationOptions(val); schemaParser.parse(new FileInputStream(sourceFile)); if (schemaParser.hasError()) { _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder()); exitCode = 1; continue; } final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0); if (!(originalSchema instanceof NamedDataSchema)) { _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema"); exitCode = 1; continue; } final SchemaParser filterParser = new SchemaParser(); filterParser.setValidationOptions(val); final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema, predicate, filterParser); if (filterParser.hasError()) { _log.error("Error applying predicate: " + filterParser.errorMessageBuilder()); exitCode = 1; continue; } final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath(); final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath; final File outputFile = new File(outputFilePath); final File outputFileParent = outputFile.getParentFile(); outputFileParent.mkdirs(); if (!outputFileParent.exists()) { _log.error("Unable to write filtered schema to " + outputFileParent.getPath()); exitCode = 1; continue; } FileOutputStream fout = new FileOutputStream(outputFile); String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED); fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET)); fout.close(); } catch (IOException e) { _log.error(e.getMessage()); exitCode = 1; } } System.exit(exitCode); }
From source file:FileDemo.java
public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); System.out.println("File Name: " + f1.getName()); System.out.println("Path: " + f1.getPath()); System.out.println("Abs Path: " + f1.getAbsolutePath()); System.out.println("Parent: " + f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: " + f1.lastModified()); System.out.println("File size: " + f1.length() + " Bytes"); }
From source file:de.fraunhofer.iosb.ilt.stc.Copier.java
/** * @param args the command line arguments * @throws de.fraunhofer.iosb.ilt.sta.ServiceFailureException * @throws java.net.URISyntaxException//from w ww. j a v a 2 s . co m * @throws java.net.MalformedURLException */ public static void main(String[] args) throws ServiceFailureException, URISyntaxException, MalformedURLException, IOException { String configFileName = "configuration.json"; if (args.length > 0) { configFileName = args[0]; } File configFile = new File(configFileName); if (configFile.isFile() && configFile.exists()) { Copier copier = new Copier(configFile); copier.start(); } else { LOGGER.info("No configuration found, generating sample."); JsonElement sampleConfig = new Copier().getConfigEditor(null, null).getConfig(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String configString = gson.toJson(sampleConfig); FileUtils.writeStringToFile(configFile, configString, "UTF-8"); LOGGER.info("Sample configuration written to {}.", configFile); } }
From source file:lunarion.cluster.quickstart.ExampleProcess.java
public static void main(String[] args) throws Exception { String zkConnectString = "localhost:2181"; String clusterName = "storage-integration-cluster"; String instanceName = "localhost_8905"; String file = null;/* w ww.j a v a2 s . co m*/ String stateModelValue = "MasterSlave"; int delay = 0; boolean skipZeroArgs = true;// false is for dev testing if (!skipZeroArgs || args.length > 0) { CommandLine cmd = processCommandLineArgs(args); zkConnectString = cmd.getOptionValue(zkServer); clusterName = cmd.getOptionValue(cluster); String host = cmd.getOptionValue(hostAddress); String portString = cmd.getOptionValue(hostPort); int port = Integer.parseInt(portString); instanceName = host + "_" + port; file = cmd.getOptionValue(configFile); if (file != null) { File f = new File(file); if (!f.exists()) { System.err.println("static config file doesn't exist"); System.exit(1); } } stateModelValue = cmd.getOptionValue(stateModel); if (cmd.hasOption(transDelay)) { try { delay = Integer.parseInt(cmd.getOptionValue(transDelay)); if (delay < 0) { throw new Exception("delay must be positive"); } } catch (Exception e) { e.printStackTrace(); delay = 0; } } } // Espresso_driver.py will consume this System.out.println("Starting Process with ZK:" + zkConnectString); ExampleProcess process = new ExampleProcess(zkConnectString, clusterName, instanceName, file, stateModelValue, delay); process.start(); Runtime.getRuntime().addShutdownHook(new HelixManagerShutdownHook(process.getManager())); Thread.currentThread().join(); }
From source file:D20140128.ApacheXMLGraphicsTest.EPSColorsExample.java
/** * Command-line interface/*from w w w. j a v a2 s. c o m*/ * * @param args command-line arguments */ public static void main(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 (Exception e) { e.printStackTrace(); } }