List of usage examples for java.io File exists
public boolean exists()
From source file:org.eclipse.swt.snippets.SnippetLauncher.java
public static void main(String[] args) { File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR; boolean hasSource = sourceDir.exists(); int count = 500; if (hasSource) { File[] files = sourceDir.listFiles(); if (files.length > 0) count = files.length;/*from w w w. j a v a2 s . com*/ } for (int i = 1; i < count; i++) { if (SnippetsConfig.isPrintingSnippet(i)) continue; // avoid printing to printer String className = "Snippet" + i; Class<?> clazz = null; try { clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className); } catch (ClassNotFoundException e) { } if (clazz != null) { System.out.println("\n" + clazz.getName()); if (hasSource) { File sourceFile = new File(sourceDir, className + ".java"); try (FileReader reader = new FileReader(sourceFile);) { char[] buffer = new char[(int) sourceFile.length()]; reader.read(buffer); String source = String.valueOf(buffer); int start = source.indexOf("package"); start = source.indexOf("/*", start); int end = source.indexOf("* For a list of all"); System.out.println(source.substring(start, end - 3)); boolean skip = false; String platform = SWT.getPlatform(); if (source.contains("PocketPC")) { platform = "PocketPC"; skip = true; } else if (source.contains("OpenGL")) { platform = "OpenGL"; skip = true; } else if (source.contains("JavaXPCOM")) { platform = "JavaXPCOM"; skip = true; } else { String[] platforms = { "win32", "gtk" }; for (int p = 0; p < platforms.length; p++) { if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) { platform = platforms[p]; skip = true; break; } } } if (skip) { System.out.println("...skipping " + platform + " example..."); continue; } } catch (Exception e) { } } Method method = null; String[] param = SnippetsConfig.getSnippetArguments(i); try { method = clazz.getMethod("main", param.getClass()); } catch (NoSuchMethodException e) { System.out.println(" Did not find main(String [])"); } if (method != null) { try { method.invoke(clazz, new Object[] { param }); } catch (IllegalAccessException e) { System.out.println(" Failed to launch (illegal access)"); } catch (IllegalArgumentException e) { System.out.println(" Failed to launch (illegal argument to main)"); } catch (InvocationTargetException e) { System.out.println(" Exception in Snippet: " + e.getTargetException()); } } } } }
From source file:com.act.utils.parser.UniprotInterpreter.java
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, CompoundNotFoundException { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from www . ja v a 2 s .c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH)); if (!uniprotFile.exists()) { String msg = "Uniprot file path is null"; LOGGER.error(msg); throw new RuntimeException(msg); } else { UniprotInterpreter reader = new UniprotInterpreter(uniprotFile); reader.init(); } }
From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java
public static void main(String[] args) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml"); Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }/*from w w w. ja v a2 s .c om*/ commandList.append(cmd.toString()); } options.addOption(Option // .builder("c") // .longOpt("config") // .desc("The configuration file to use") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("d") // .longOpt("debug") // .desc("Logs more details") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndegoMqttAdapter.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } if (cmds.hasOption("d")) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml"); } String configFileName = cmds.getOptionValue('c'); File configFile = new File(configFileName); if (!configFile.exists()) { System.err.println(String.format("The specified config file (%s) does not exist", configFileName)); System.err.println(); System.exit(2); return; } Properties properties = new Properties(); try (InputStream in = new FileInputStream(configFile)) { properties.load(in); } catch (IOException ex) { System.err.println(ex.getMessage()); System.err.println(String.format("Was not able to load the properties file (%s)", configFileName)); System.err.println(); } MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration(); config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url")); config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username")); config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password")); config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection")); config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id")); config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username")); config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password")); config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root")); config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms"))); MqttIndegoAdapter adapter = new MqttIndegoAdapter(config); adapter.startup(); }
From source file:at.co.malli.relpm.RelPM.java
/** * @param args the command line arguments *//*from w w w . j a va 2 s. co m*/ public static void main(String[] args) { //<editor-fold defaultstate="collapsed" desc=" Create config & log directory "> String userHome = System.getProperty("user.home"); File relPm = new File(userHome + "/.RelPM"); if (!relPm.exists()) { boolean worked = relPm.mkdir(); if (!worked) { ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory " + relPm.getAbsolutePath() + " to store user-settings and logs")); System.exit(-1); } } File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created... if (!userConfig.exists()) { try { URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml"); FileUtils.copyURLToFile(resource, userConfig); } catch (IOException ex) { ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage())); System.exit(-1); } } if (!userConfig.canWrite() || !userConfig.canRead()) { ExceptionDisplayer.showErrorMessage(new Exception( "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings")); System.exit(-1); } if (System.getProperty("os.name").toLowerCase().contains("win")) { Path relPmPath = Paths.get(relPm.toURI()); try { Files.setAttribute(relPmPath, "dos:hidden", true); } catch (IOException ex) { ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath() + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage())); System.exit(-1); } } //</editor-fold> logger.trace("Environment setup sucessfull"); //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code "> try { String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel"); UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels(); boolean found = false; for (UIManager.LookAndFeelInfo info : installed) { if (info.getClassName().equals(wantedLookAndFeel)) found = true; } if (found) UIManager.setLookAndFeel(wantedLookAndFeel); else UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (InstantiationException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (IllegalAccessException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue "> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainGUI().setVisible(true); } }); //</editor-fold> }
From source file:org.kuali.student.git.importer.GitImporterMain.java
/** * @param args/* ww w . jav a 2 s .co m*/ */ public static void main(final String[] args) { if (args.length != 8 && args.length != 9) { log.error( "USAGE: <svn dump file> <git repository> <veto.log> <skipped-copy-from.log> <blob.log> <gc enabled> <svn repo base url> <repo uuid> [<git command path>]"); log.error("\t<veto.log> : which paths were veto's as not being a valid branch"); log.error("\t<skipped-copy-from.log> : which copy-from-paths were skipped"); log.error("\t<blob.log> : issues related to blobs (typically directory copy related)"); log.error("\t<gc enabled> : set to 1 (true ever 500 revs) or 0 (false) to disable"); log.error("\t<svn repo base url> : the svn repo base url to use in the git-svn-id"); log.error( "\t<repo uuid> : The svn repository uuid to use in the git-svn-id.\n\tIt you are importing from a clone use this to set the field to the real repositories uuid."); log.error("\t<git command path> : the path to a native git to use for gc's which occur every 500 revs"); System.exit(-1); } try { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "GitImporterMain-applicationContext.xml"); applicationContext.registerShutdownHook(); SvnDumpFilter filter = applicationContext.getBean(SvnDumpFilter.class); BranchDetector branchDetector = applicationContext.getBean("branchDetector", BranchDetector.class); // final MergeDetectorData detectorData = applicationContext // .getBean(MergeDetectorData.class); File dumpFile = new File(args[0]); if (!dumpFile.exists()) { throw new FileNotFoundException(args[0] + " path not found"); } File gitRepository = new File(args[1]).getAbsoluteFile(); if (!gitRepository.getParentFile().exists()) throw new FileNotFoundException(args[1] + "path not found"); final PrintWriter vetoLog = new PrintWriter(args[2]); final PrintWriter copyFromSkippedLog = new PrintWriter(args[3]); final PrintWriter blobLog = new PrintWriter(args[4]); boolean gcEnabled = true; final boolean printGitSvnIds = true; // not optional anymore String repositoryBaseUrl = null; String repositoryUUID = null; if (args[5].trim().equals("0")) gcEnabled = false; repositoryBaseUrl = args[6].trim(); repositoryUUID = args[7].trim(); String nativeGitCommandPath = null; if (args.length == 9) nativeGitCommandPath = args[8].trim(); final Repository repo = GitRepositoryUtils.buildFileRepository(gitRepository, false); // extract any known branches from the repository BZip2CompressorInputStream compressedInputStream = new BZip2CompressorInputStream( new FileInputStream(dumpFile)); filter.parseDumpFile(compressedInputStream, new GitImporterParseOptions(repo, vetoLog, copyFromSkippedLog, blobLog, printGitSvnIds, repositoryBaseUrl, repositoryUUID, branchDetector, gcEnabled, nativeGitCommandPath)); vetoLog.close(); copyFromSkippedLog.close(); blobLog.close(); compressedInputStream.close(); } catch (Exception e) { log.error("Processing failed", e); } }
From source file:cc.twittertools.search.api.TrecSearchThriftServer.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION)); options.addOption(//from w w w . j av a 2 s .c o m OptionBuilder.withArgName("index").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg() .withDescription("max number of threads in thread pool").create(MAX_THREADS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing access tokens").create(CREDENTIALS_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(HELP_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(TrecSearchThriftServer.class.getName(), options); System.exit(-1); } int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)) : DEFAULT_PORT; int maxThreads = cmdline.hasOption(MAX_THREADS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MAX_THREADS_OPTION)) : DEFAULT_MAX_THREADS; File index = new File(cmdline.getOptionValue(INDEX_OPTION)); Map<String, String> credentials = null; if (cmdline.hasOption(CREDENTIALS_OPTION)) { credentials = Maps.newHashMap(); File cfile = new File(cmdline.getOptionValue(CREDENTIALS_OPTION)); if (!cfile.exists()) { System.err.println("Error: " + cfile + " does not exist!"); System.exit(-1); } for (String s : Files.readLines(cfile, Charsets.UTF_8)) { try { String[] arr = s.split(":"); credentials.put(arr[0], arr[1]); } catch (Exception e) { // Catch any exceptions from parsing file contain access tokens System.err.println("Error reading access tokens from " + cfile + "!"); System.exit(-1); } } } if (!index.exists()) { System.err.println("Error: " + index + " does not exist!"); System.exit(-1); } TServerSocket serverSocket = new TServerSocket(port); TrecSearch.Processor<TrecSearch.Iface> searchProcessor = new TrecSearch.Processor<TrecSearch.Iface>( new TrecSearchHandler(index, credentials)); TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverSocket); serverArgs.maxWorkerThreads(maxThreads); TServer thriftServer = new TThreadPoolServer( serverArgs.processor(searchProcessor).protocolFactory(new TBinaryProtocol.Factory())); thriftServer.serve(); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step9AgreementCollector.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // /home/user-ukp/research/data/dip/wp1-documents/step3-filled-raw-html File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs();// www .j a va 2s . c om } computeObservedAgreement(inputDir, outputDir); }
From source file:de.berber.kindle.annotator.Main.java
/** * Main function of PDFAnnotator. For command line parameters see the {@see * Options} class./*from w w w .j a va 2 s . c o m*/ * * @param args * List of command line parameters. */ public static void main(String[] args) { final CompositeConfiguration cc = new CompositeConfiguration(); try { // configure logging final PatternLayout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c: %m%n"); final ConsoleAppender consoleAppender = new ConsoleAppender(layout); Logger.getRootLogger().addAppender(consoleAppender); Logger.getRootLogger().setLevel(Level.WARN); // read commandline final Options options = new Options(); final CmdLineParser parser = new CmdLineParser(options); parser.setUsageWidth(80); try { // parse the arguments. parser.parseArgument(args); if (options.help) { parser.printUsage(System.err); return; } } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("Usage:"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -jar <jar> " + parser.printExample(ExampleMode.ALL)); return; } // read default configuration file final URL defaultURL = PDFAnnotator.class.getClassLoader() .getResource("de/berber/kindle/annotator/PDFAnnotator.default"); // read config file specified at the command line if (options.config != null) { final File configFile = new File(options.config); if (!configFile.exists() || !configFile.canRead()) { LOG.error("Specified configuration file does not exist."); } else { cc.addConfiguration(new PropertiesConfiguration(configFile)); } } cc.addConfiguration(new PropertiesConfiguration(defaultURL)); final WorkingList model = new WorkingList(); final WorkQueue queue = new WorkQueue(cc, model); AbstractMain view = null; if (options.noGUI) { view = new BatchMain(options, model); } else { view = new MainWindow(options, model); } view.run(); if (options.noGUI) { queue.stop(); } } catch (Exception ex) { LOG.error("Error while executing Kindle Annotator. Please report a bug."); ex.printStackTrace(); } }
From source file:jeplus.util.LineEnds.java
public static void main(String[] args) { String LN = "\r\n"; // create the parser CommandLineParser parser = new GnuParser(); Options options = getCommandLineOptions(); CommandLine commandline = null;/*from w ww . j a v a 2 s .c om*/ HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(80); try { // parse the command line arguments commandline = parser.parse(options, args); if (commandline.hasOption("help")) { // automatically generate the help statement formatter.printHelp("java -cp jEPlusNet.jar jeplusplus.util.LineEnds [OPTIONS]", options); System.exit(-1); } // Set log4j configuration if (commandline.hasOption("log")) { PropertyConfigurator.configure(commandline.getOptionValue("log")); } else { PropertyConfigurator.configure("log4j.cfg"); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); // automatically generate the help statement formatter.printHelp("java -Xmx500m -jar JESS_Client.jar [OPTIONS]", options); System.exit(-1); } if (commandline.hasOption("style")) { if (commandline.getOptionValue("style").startsWith("L")) { LN = "\n"; } } if (commandline.hasOption("file")) { File file = new File(commandline.getOptionValue("file")); if (file.exists()) { if (file.isDirectory()) { File[] listOfFiles = file.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { convertFile(listOfFiles[i], LN); } } } else { convertFile(file, LN); } } } }
From source file:com.nubits.nubot.launch.MainLaunch.java
/** * Start the NuBot. start if config is valid and other instance is running * * @param args a list of valid arguments *//*from www. java2 s .co m*/ public static void main(String args[]) { Global.sessionPath = "logs" + "/" + Settings.SESSION_LOG + System.currentTimeMillis(); MDC.put("session", Global.sessionPath); LOG.info("defined session path " + Global.sessionPath); CommandLine cli = parseArgs(args); boolean runGUI = false; String configFile; boolean defaultCfg = false; if (cli.hasOption(CLIOptions.GUI)) { runGUI = true; LOG.info("Running " + Settings.APP_NAME + " with GUI"); if (!cli.hasOption(CLIOptions.CFG)) { LOG.info("Setting default config file location :" + Settings.DEFAULT_CONFIG_FILE_PATH); //Cancel any previously existing file, if any File f = new File(Settings.DEFAULT_CONFIG_FILE_PATH); if (f.exists() && !f.isDirectory()) { LOG.warn("Detected a non-empty configuration file, resetting it to default. " + "Printing existing file content, for reference:\n" + FilesystemUtils.readFromFile(Settings.DEFAULT_CONFIG_FILE_PATH)); FilesystemUtils.deleteFile(Settings.DEFAULT_CONFIG_FILE_PATH); } //Create a default file SaveOptions.optionsReset(Settings.DEFAULT_CONFIG_FILE_PATH); defaultCfg = true; } } if (cli.hasOption(CLIOptions.CFG) || defaultCfg) { if (defaultCfg) { configFile = Settings.DEFAULT_CONFIG_FILE_PATH; } else { configFile = cli.getOptionValue(CLIOptions.CFG); } if (runGUI) { SessionManager.setConfigGlobal(configFile, true); try { UiServer.startUIserver(configFile, defaultCfg); Global.createShutDownHook(); } catch (Exception e) { LOG.error("error setting up UI server " + e); } } else { LOG.info("Run NuBot from CLI"); //set global config SessionManager.setConfigGlobal(configFile, false); sessionLOG.debug("launch bot"); try { SessionManager.setModeStarting(); SessionManager.launchBot(Global.options); Global.createShutDownHook(); } catch (NuBotRunException e) { exitWithNotice("could not launch bot " + e); } } } else { exitWithNotice("Missing " + CLIOptions.CFG + ". run nubot with \n" + CLIOptions.USAGE_STRING); } }