List of usage examples for java.io File canRead
public boolean canRead()
From source file:iaj.linkit.App.java
/** * Application entry method.//from w w w. j ava 2 s.c om * * @param args Command line arguments. */ public static void main(final String[] args) { final Configuration config = new Configuration(); final CmdLineParser parser = new CmdLineParser(config); try { parser.parseArgument(args); final File f = (config.getPaths().size() > 0) ? new File(config.getPaths().get(0)).getCanonicalFile() : new File(DIR_CURRENT).getCanonicalFile(); if (!f.exists()) { System.err.println("No such path: " + f.getCanonicalFile()); System.exit(1); } else if (!f.canRead()) { System.err.println("Can't read path."); System.exit(1); } else if (f.isDirectory()) { handleFiles(config.isRecursive(), f.listFiles()); } else { handleFiles(config.isRecursive(), f); } } catch (IOException e) { e.printStackTrace(); System.exit(1); } catch (final CmdLineException e) { System.err.println(e.getMessage()); System.err.println("lu [options...] [paths...]"); //$NON-NLS-1$ parser.printUsage(System.err); System.exit(1); } }
From source file:TaskManager.java
public static void main(String[] args) { String configFileName = "tasks.conf"; if (args.length == 1) { configFileName = args[0];/* w w w . ja v a 2 s. com*/ } File configFile = new File(configFileName); if (!configFile.exists() || !configFile.canRead()) { System.err.println("Can't read config file '" + configFileName + "'"); System.exit(1); } FileReader configReader = null; try { configReader = new FileReader(configFile); } catch (FileNotFoundException fnfX) { } Tasks taskList = new Tasks(configReader); try { configReader.close(); } catch (IOException ioX) { } TaskManager ex = new TaskManager(taskList); }
From source file:ca.uqac.info.trace.conversion.TraceConverter.java
/** * Main program loop/*from www . jav a 2s .c o m*/ * @param args Command-line arguments */ @SuppressWarnings("static-access") public static void main(String[] args) { // Default values String input_format = "xml", output_format = "smv"; String input_filename = "trace.xml", output_filename = ""; //String event_tag_name = "Event"; // Define and process command line arguments Options options = new Options(); HelpFormatter help_formatter = new HelpFormatter(); Option opt; options.addOption("h", "help", false, "Show help"); opt = OptionBuilder.withArgName("format").hasArg() .withDescription("Input format for trace. Accepted values are csv, xml.").create("i"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("format").hasArg().withDescription( "Output format for trace. Accepted values are javamop, json, monpoly, smv, sql, xml. Default: smv") .create("t"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename. Default: trace.xml") .create("f"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Output filename").create("o"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("name").hasArg().withDescription("Event tag name. Default: Event") .create("e"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("formula").hasArg().withDescription("Formula to translate").create("s"); opt.setRequired(false); options.addOption(opt); CommandLine c_line = parseCommandLine(options, args); if (c_line.hasOption("h")) { help_formatter.printHelp(app_name, options); System.exit(0); } input_filename = c_line.getOptionValue("f"); if (c_line.hasOption("o")) output_filename = c_line.getOptionValue("o"); /*if (c_line.hasOption("e")) event_tag_name = c_line.getOptionValue("e");*/ // Determine the input format if (!c_line.hasOption("i")) { // Guess output format by filename extension input_format = getExtension(input_filename); } if (c_line.hasOption("i")) { // The "t" parameter overrides the filename extension input_format = c_line.getOptionValue("i"); } // Determine which trace reader to initialize TraceReader reader = initializeReader(input_format); if (reader == null) { System.err.println("ERROR: Unrecognized input format"); System.exit(1); } // Instantiate the proper trace reader and checks that the trace exists //reader.setEventTagName(event_tag_name); File in_f = new File(input_filename); if (!in_f.exists()) { System.err.println("ERROR: Input file not found"); System.exit(1); } if (!in_f.canRead()) { System.err.println("ERROR: Input file is not readable"); System.exit(1); } // Determine the output format if (!c_line.hasOption("o") && !c_line.hasOption("t")) { System.err.println("ERROR: At least one of output filename and output format must be given"); System.exit(1); } if (c_line.hasOption("o")) { // Guess output format by filename extension output_filename = c_line.getOptionValue("o"); output_format = getExtension(output_filename); } if (c_line.hasOption("t")) { // The "t" parameter overrides the filename extension output_format = c_line.getOptionValue("t"); } // Determine which translator to initialize Translator trans = initializeTranslator(output_format); if (trans == null) { System.err.println("ERROR: Unrecognized output format"); System.exit(1); } // Translate the trace into the output format EventTrace trace = null; try { trace = reader.parseEventTrace(new FileInputStream(in_f)); } catch (FileNotFoundException ex) { ex.printStackTrace(); System.exit(1); } assert trace != null; trans.setTrace(trace); String out_trace = trans.translateTrace(); if (output_filename.isEmpty()) System.out.println(out_trace); else writeToFile(output_filename, out_trace); // Check if there is a formula to translate if (c_line.hasOption("s")) { String formula = c_line.getOptionValue("s"); try { Operator o = Operator.parseFromString(formula); trans.setFormula(o); System.out.println(trans.translateFormula()); } catch (Operator.ParseException e) { System.err.println("ERROR: parsing input formula"); System.exit(1); } } }
From source file:edu.ucdenver.ccp.nlp.ae.dict_util.OboToDictionary.java
public static void main(String args[]) { BasicConfigurator.configure();//from www. j a v a 2 s . com if (args.length < 2) { usage(); } else { try { File oboFile = new File(args[0]); File outputFile = new File(args[1]); String namespaceName = ""; if (args.length > 2) { namespaceName = args[2]; } if (!oboFile.canRead()) { System.out.println("can't read input file;" + oboFile.getAbsolutePath()); usage(); System.exit(-2); } if (outputFile.exists() && !outputFile.canWrite()) { System.out.println("can't write output file;" + outputFile.getAbsolutePath()); usage(); System.exit(-3); } logger.warn("running with: " + oboFile.getAbsolutePath()); OboToDictionary converter = null; if (namespaceName != null && namespaceName.length() > 0) { Set<String> namespaceSet = new TreeSet<String>(); namespaceSet.add(namespaceName); converter = new OboToDictionary(true, SynonymType.EXACT_ONLY, namespaceSet); } else { converter = new OboToDictionary(); } converter.convert(oboFile, outputFile); } catch (Exception e) { System.out.println("error:" + e); e.printStackTrace(); System.exit(-1); } } }
From source file:net.schweerelos.parrot.CombinedParrotApp.java
/** * @param args/* w ww .j a va 2 s. c o m*/ */ @SuppressWarnings("static-access") public static void main(String[] args) { CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("help") .withDescription("Shows usage information and quits the program").create("h")); options.addOption( OptionBuilder.withLongOpt("datafile").withDescription("The file with instances to use (required)") .hasArg().withArgName("file").isRequired().create("f")); options.addOption(OptionBuilder.withLongOpt("properties") .withDescription("Properties file to use. Default: " + System.getProperty("user.home") + File.separator + ".digital-parrot" + File.separator + "parrot.properties") .hasArg().withArgName("prop").create("p")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { // this is only executed when all required options are present _and_ the help option is specified! printHelp(options); return; } String datafile = line.getOptionValue("f"); if (!datafile.startsWith("file:") || !datafile.startsWith("http:")) { datafile = "file:" + datafile; } String propertiesPath = System.getProperty("user.home") + File.separator + ".digital-parrot" + File.separator + "parrot.properties"; if (line.hasOption("p")) { propertiesPath = line.getOptionValue("p"); } final Properties properties = new Properties(); File propertiesFile = new File(propertiesPath); if (propertiesFile.exists() && propertiesFile.canRead()) { try { properties.load(new FileReader(propertiesFile)); } catch (FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } catch (IOException e) { e.printStackTrace(System.err); System.exit(1); } } final String url = datafile; // we need a "final" var for the anonymous class SwingUtilities.invokeLater(new Runnable() { public void run() { CombinedParrotApp inst = null; try { inst = new CombinedParrotApp(properties); inst.loadModel(url); } catch (Exception e) { JOptionPane.showMessageDialog(null, "There has been an error while starting the program.\nThe program will exit now.", APP_TITLE + " Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(System.err); System.exit(1); } if (inst != null) { inst.setLocationRelativeTo(null); inst.setVisible(true); } } }); } catch (ParseException exp) { printHelp(options); } }
From source file:com.ibm.jaql.MiniCluster.java
/** * @param args/*from w w w . j a va 2 s. c o m*/ */ public static void main(String[] args) throws IOException { String clusterHome = System.getProperty("hadoop.minicluster.dir"); if (clusterHome == null) { clusterHome = "./minicluster"; System.setProperty("hadoop.minicluster.dir", clusterHome); } LOG.info("hadoop.minicluster.dir=" + clusterHome); File clusterFile = new File(clusterHome); if (!clusterFile.exists()) { clusterFile.mkdirs(); } if (!clusterFile.isDirectory()) { throw new IOException("minicluster home directory must be a directory: " + clusterHome); } if (!clusterFile.canRead() || !clusterFile.canWrite()) { throw new IOException("minicluster home directory must be readable and writable: " + clusterHome); } String logDir = System.getProperty("hadoop.log.dir"); if (logDir == null) { logDir = clusterHome + File.separator + "logs"; System.setProperty("hadoop.log.dir", logDir); } File logFile = new File(logDir); if (!logFile.exists()) { logFile.mkdirs(); } String confDir = System.getProperty("hadoop.conf.override"); if (confDir == null) { confDir = clusterHome + File.separator + "conf"; System.setProperty("hadoop.conf.override", confDir); } File confFile = new File(confDir); if (!confFile.exists()) { confFile.mkdirs(); } System.out.println("starting minicluster in " + clusterHome); MiniCluster mc = new MiniCluster(args); // To find the ports in the // hdfs: search for: Web-server up at: localhost:#### // mapred: search for: mapred.JobTracker: JobTracker webserver: #### Configuration conf = mc.getConf(); System.out.println("fs.default.name: " + conf.get("fs.default.name")); System.out.println("dfs.http.address: " + conf.get("dfs.http.address")); System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address")); boolean waitForInterrupt; try { System.out.println("press enter to end minicluster (or eof to run forever)..."); waitForInterrupt = System.in.read() < 0; // wait for any input or eof } catch (Exception e) { // something odd happened. Just shutdown. LOG.error("error reading from stdin", e); waitForInterrupt = false; } // eof means that we will wait for a kill signal while (waitForInterrupt) { System.out.println("minicluster is running until interrupted..."); try { Thread.sleep(60 * 60 * 1000); } catch (InterruptedException e) { waitForInterrupt = false; } } System.out.println("shutting down minicluster..."); try { mc.tearDown(); } catch (Exception e) { LOG.error("error while shutting down minicluster", e); } }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
public static void main(String[] args) { try {/*w w w.jav a 2 s. co m*/ Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); File home = args.length > 0 ? new File(args[0]) : new File("."); Protocol.registerProtocol("easyhttps", easyhttps); File submitFile = new File(home, ".submit"); File submitUserFile = new File(home, ".submitUser"); File submitIgnoreFile = new File(home, ".submitIgnore"); File cvsIgnoreFile = new File(home, ".cvsignore"); if (!submitFile.canRead()) { System.out.println("Must perform submit from a directory containing a \".submit\" file"); System.out.println("No such file found at " + submitFile.getCanonicalPath()); System.exit(1); } Properties p = new Properties(); p.load(new FileInputStream(submitFile)); String submitURL = p.getProperty("submitURL"); if (submitURL == null) { System.out.println(".submit file does not contain a submitURL"); System.exit(1); } String courseName = p.getProperty("courseName"); String courseKey = p.getProperty("courseKey"); String semester = p.getProperty("semester"); String projectNumber = p.getProperty("projectNumber"); String authenticationType = p.getProperty("authentication.type"); String baseURL = p.getProperty("baseURL"); System.out.println("Submitting contents of " + home.getCanonicalPath()); System.out.println(" as project " + projectNumber + " for course " + courseName); FilesToIgnore ignorePatterns = new FilesToIgnore(); addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns); addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns); FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern()); Collection<File> files = find.getAllFiles(); boolean createdSubmitUser = false; Properties userProps = new Properties(); if (submitUserFile.canRead()) { userProps.load(new FileInputStream(submitUserFile)); } if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null || userProps.getProperty("oneTimePassword") == null) { System.out.println(); System.out.println( "We need to authenticate you and create a .submitUser file so you can submit your project"); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); createdSubmitUser = true; userProps.load(new FileInputStream(submitUserFile)); } MultipartPostMethod filePost = createFilePost(p, find, files, userProps); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); int status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); if (status == 500 && !createdSubmitUser) { System.out.println("Let's try reauthenticating you"); System.out.println(); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); userProps.load(new FileInputStream(submitUserFile)); filePost = createFilePost(p, find, files, userProps); client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); } if (status != HttpStatus.SC_OK) { System.out.println("Status code: " + status); System.exit(1); } System.out.println("Submission accepted"); } catch (Exception e) { System.out.println(); System.out.println("An Error has occured during submission!"); System.out.println(); System.out.println("[DETAILS]"); System.out.println(e.getMessage()); e.printStackTrace(System.out); System.out.println(); } }
From source file:com.bericotech.clavin.index.IndexDirectoryBuilder.java
/** * Turns a GeoNames gazetteer file into a Lucene index, and adds * some supplementary gazetteer records at the end. * * @param args not used/*from w w w.j av a 2 s. c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { Options options = getOptions(); CommandLine cmd = null; CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException pe) { LOG.error(pe.getMessage()); printHelp(options); System.exit(-1); } if (cmd.hasOption(HELP_OPTION)) { printHelp(options); System.exit(0); } String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY); String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION); if (gazetteerPaths == null || gazetteerPaths.length == 0) { gazetteerPaths = DEFAULT_GAZETTEER_FILES; } boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION); boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION); File idir = new File(indexPath); // if the index directory exists, delete it if we are replacing, otherwise // exit gracefully if (idir.exists()) { if (replaceIndex) { LOG.info("Replacing index: {}", idir.getAbsolutePath()); FileUtils.deleteDirectory(idir); } else { LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath()); System.exit(-1); } } List<File> gazetteerFiles = new ArrayList<File>(); for (String gp : gazetteerPaths) { File gf = new File(gp); if (gf.isFile() && gf.canRead()) { gazetteerFiles.add(gf); } else { LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath()); } } if (gazetteerFiles.isEmpty()) { LOG.error("No Gazetteer files found."); System.exit(-1); } String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION); File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null; if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) { LOG.error("Unable to read alternate names file: {}", altNamesPath); System.exit(-1); } new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile); }
From source file:at.co.malli.relpm.RelPM.java
/** * @param args the command line arguments */// ww w.j a va 2 s . c o 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:eu.ensure.aging.AgingSimulator.java
public static void main(String[] args) { Options options = new Options(); options.addOption("n", "flip-bit-in-name", true, "Flip bit in first byte of name of first file"); options.addOption("u", "flip-bit-in-uname", true, "Flip bit in first byte of username of first file"); options.addOption("c", "update-checksum", true, "Update header checksum (after prior bit flips)"); Properties properties = new Properties(); CommandLineParser parser = new PosixParser(); try {// w ww.j ava 2 s .c o m CommandLine line = parser.parse(options, args); // if (line.hasOption("flip-bit-in-name")) { properties.put("flip-bit-in-name", line.getOptionValue("flip-bit-in-name")); } else { // On by default (if not explicitly de-activated above) properties.put("flip-bit-in-name", "true"); } // if (line.hasOption("flip-bit-in-uname")) { properties.put("flip-bit-in-uname", line.getOptionValue("flip-bit-in-uname")); } else { properties.put("flip-bit-in-uname", "false"); } // if (line.hasOption("update-checksum")) { properties.put("update-checksum", line.getOptionValue("update-checksum")); } else { properties.put("update-checksum", "false"); } String[] fileArgs = line.getArgs(); if (fileArgs.length < 1) { printHelp(options, System.err); System.exit(1); } String srcPath = fileArgs[0]; File srcAIP = new File(srcPath); if (!srcAIP.exists()) { String info = "The source path does not locate a file: " + srcPath; System.err.println(info); System.exit(1); } if (srcAIP.isDirectory()) { String info = "The source path locates a directory, not a file: " + srcPath; System.err.println(info); System.exit(1); } if (!srcAIP.canRead()) { String info = "Cannot read source file: " + srcPath; System.err.println(info); System.exit(1); } boolean doReplace = false; File destAIP = null; if (fileArgs.length > 1) { String destPath = fileArgs[1]; destAIP = new File(destPath); if (destAIP.exists()) { String info = "The destination path locates an existing file: " + destPath; System.err.println(info); System.exit(1); } } else { doReplace = true; try { destAIP = File.createTempFile("tmp-aged-aip-", ".tar"); } catch (IOException ioe) { String info = "Failed to create temporary file: "; info += ioe.getMessage(); System.err.println(info); System.exit(1); } } String info = "Age simulation\n"; info += " Reading from " + srcAIP.getName() + "\n"; if (doReplace) { info += " and replacing it's content"; } else { info += " Writing to " + destAIP.getName(); } System.out.println(info); // InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(srcAIP)); os = new BufferedOutputStream(new FileOutputStream(destAIP)); simulateAging(srcAIP.getName(), is, os, properties); } catch (FileNotFoundException fnfe) { info = "Could not locate file: " + fnfe.getMessage(); System.err.println(info); } finally { try { if (null != os) os.close(); if (null != is) is.close(); } catch (IOException ignore) { } } // if (doReplace) { File renamedOriginal = new File(srcAIP.getName() + "-backup"); srcAIP.renameTo(renamedOriginal); ReadableByteChannel rbc = null; WritableByteChannel wbc = null; try { rbc = Channels.newChannel(new FileInputStream(destAIP)); wbc = Channels.newChannel(new FileOutputStream(srcAIP)); FileIO.fastChannelCopy(rbc, wbc); } catch (FileNotFoundException fnfe) { info = "Could not locate temporary output file: " + fnfe.getMessage(); System.err.println(info); } catch (IOException ioe) { info = "Could not copy temporary output file over original AIP: " + ioe.getMessage(); System.err.println(info); } finally { try { if (null != wbc) wbc.close(); if (null != rbc) rbc.close(); destAIP.delete(); } catch (IOException ignore) { } } } } catch (ParseException pe) { String info = "Failed to parse command line: " + pe.getMessage(); System.err.println(info); printHelp(options, System.err); System.exit(1); } }