List of usage examples for java.io File exists
public boolean exists()
From source file:com.meltmedia.rodimus.RodimusCli.java
public static void main(String... args) { try {//from w w w.ja v a 2 s .c om final Cli<RodimusInterface> cli = CliFactory.createCli(RodimusInterface.class); final RodimusInterface options = cli.parseArguments(args); // if help was requested, then display the help message and exit. if (options.isHelp()) { System.out.println(cli.getHelpMessage()); return; } final boolean verbose = options.isVerbose(); if (options.getFiles() == null || options.getFiles().size() < 1) { System.out.println(cli.getHelpMessage()); return; } // get the input file. File inputFile = options.getFiles().get(0); // get the output file. File outputDir = null; if (options.getFiles().size() > 1) { outputDir = options.getFiles().get(1); } else { outputDir = new File(inputFile.getName().replaceFirst("\\.[^.]+\\Z", "")); } if (outputDir.exists() && !outputDir.isDirectory()) { throw new Exception(outputDir + " is not a directory."); } outputDir.mkdirs(); transformDocument(inputFile, outputDir, verbose); } catch (Exception e) { e.printStackTrace(System.err); } }
From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java
/** * Runs the server. Needed args: -w --workspace the workspace * /*from w w w . j a v a 2 s.c o m*/ * @param args */ public static void main(String[] args) { CommandLine comLine = processCommandLineOptions(args); assert comLine != null; try { starttime = System.currentTimeMillis(); String portnumber = comLine.getOptionValue("p"); String workspacePath; if (comLine.hasOption("r")) { TwoDVisualizer.PRINT_ROLE_NAMES = true; } if (comLine.hasOption("w")) { workspacePath = comLine.getOptionValue("w"); } else { File workspace = new File(System.getProperty("java.io.tmpdir") + File.separator + "tgraphbrowser"); if (!workspace.exists()) { if (!workspace.mkdir()) { logger.info("The temp folder " + workspace.getAbsolutePath() + " could not be created."); } } workspace = new File(workspace.getAbsoluteFile() + File.separator + "workspace"); if (!workspace.exists()) { if (!workspace.mkdir()) { logger.info( "The default workspace " + workspace.getAbsolutePath() + " could not be created."); } } workspacePath = workspace.getAbsolutePath(); } new TGraphBrowserServer(portnumber == null ? DEFAULT_PORT : Integer.parseInt(portnumber), workspacePath, comLine.getOptionValue("m"), comLine.getOptionValue("s")).start(); if (comLine.getOptionValue("ic") != null) { TabularVisualizer.NUMBER_OF_INCIDENCES_PER_PAGE = Math .max(Integer.parseInt(comLine.getOptionValue("ic")), 1); } if (comLine.hasOption("d")) { StateRepository.dot = comLine.getOptionValue("d"); } else { System.out.println("The 2D-Visualization is disabled because parameter -d is not set."); } String timeout = comLine.getOptionValue("t"); String checkIntervall = comLine.getOptionValue("i"); new DeleteUnusedStates(timeout == null ? 600 : Integer.parseInt(timeout), checkIntervall == null ? 60 : Integer.parseInt(checkIntervall)).start(); if (comLine.hasOption("td")) { TwoDVisualizer.SECONDS_TO_WAIT_FOR_DOT = Integer.parseInt(comLine.getOptionValue("td")); } } catch (IOException e) { System.out.println(e); } }
From source file:PKCS12Import.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1);/*from w w w .jav a 2 s . c o m*/ } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println("Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println("Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); System.out.print("Enter input keystore passphrase: "); char[] inphrase = readPassphrase(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = readPassphrase(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String) eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.close(); }
From source file:com.github.s4ke.moar.cli.Main.java
public static void main(String[] args) throws ParseException, IOException { // create Options object Options options = new Options(); options.addOption("rf", true, "file containing the regexes to test against (multiple regexes are separated by one empty line)"); options.addOption("r", true, "regex to test against"); options.addOption("mf", true, "file/folder to read the MOA from"); options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)"); options.addOption("sf", true, "file to read the input string(s) from"); options.addOption("s", true, "string to test the MOA/Regex against"); options.addOption("m", false, "multiline matching mode (search in string for regex)"); options.addOption("ls", false, "treat every line of the input string file as one string"); options.addOption("t", false, "trim lines if -ls is set"); options.addOption("d", false, "only do determinism check"); options.addOption("help", false, "prints this dialog"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("moar-cli", options); return;/*from www.j a v a 2 s . c o m*/ } List<String> patternNames = new ArrayList<>(); List<MoaPattern> patterns = new ArrayList<>(); List<String> stringsToCheck = new ArrayList<>(); if (cmd.hasOption("r")) { String regexStr = cmd.getOptionValue("r"); try { patterns.add(MoaPattern.compile(regexStr)); patternNames.add(regexStr); } catch (Exception e) { System.out.println(e.getMessage()); } } if (cmd.hasOption("rf")) { String fileName = cmd.getOptionValue("rf"); List<String> regexFileContents = readFileContents(new File(fileName)); int emptyLineCountAfterRegex = 0; StringBuilder regexStr = new StringBuilder(); for (String line : regexFileContents) { if (emptyLineCountAfterRegex >= 1) { if (regexStr.length() > 0) { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } regexStr.setLength(0); emptyLineCountAfterRegex = 0; } if (line.trim().equals("")) { if (regexStr.length() > 0) { ++emptyLineCountAfterRegex; } } else { regexStr.append(line); } } if (regexStr.length() > 0) { try { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } catch (Exception e) { System.out.println(e.getMessage()); return; } regexStr.setLength(0); } } if (cmd.hasOption("mf")) { String fileName = cmd.getOptionValue("mf"); File file = new File(fileName); if (file.isDirectory()) { System.out.println(fileName + " is a directory, using all *.moar files as patterns"); File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar")); for (File moar : moarFiles) { String jsonString = readWholeFile(moar); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(moar.getAbsolutePath()); } } else { System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)"); String jsonString = readWholeFile(file); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(fileName); } } if (cmd.hasOption("s")) { String str = cmd.getOptionValue("s"); stringsToCheck.add(str); } if (cmd.hasOption("sf")) { boolean treatLineAsString = cmd.hasOption("ls"); boolean trim = cmd.hasOption("t"); String fileName = cmd.getOptionValue("sf"); StringBuilder stringBuilder = new StringBuilder(); boolean firstLine = true; for (String str : readFileContents(new File(fileName))) { if (treatLineAsString) { if (trim) { str = str.trim(); if (str.length() == 0) { continue; } } stringsToCheck.add(str); } else { if (!firstLine) { stringBuilder.append("\n"); } if (firstLine) { firstLine = false; } stringBuilder.append(str); } } if (!treatLineAsString) { stringsToCheck.add(stringBuilder.toString()); } } if (cmd.hasOption("d")) { //at this point we have already built the Patterns //so just give the user a short note. System.out.println("All Regexes seem to be deterministic."); return; } if (patterns.size() == 0) { System.out.println("no patterns to check"); return; } if (cmd.hasOption("mo")) { String folder = cmd.getOptionValue("mo"); File folderFile = new File(folder); if (!folderFile.exists()) { System.out.println(folder + " does not exist. creating..."); if (!folderFile.mkdirs()) { System.out.println("folder " + folder + " could not be created"); } } int cnt = 0; for (MoaPattern pattern : patterns) { String patternAsJSON = MoarJSONSerializer.toJSON(pattern); try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) { writer.write(patternAsJSON); } } System.out.println("stored " + cnt + " patterns in " + folder); } if (stringsToCheck.size() == 0) { System.out.println("no strings to check"); return; } boolean multiline = cmd.hasOption("m"); for (String string : stringsToCheck) { int curPattern = 0; for (MoaPattern pattern : patterns) { MoaMatcher matcher = pattern.matcher(string); if (!multiline) { if (matcher.matches()) { System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\""); } else { System.out.println( "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\""); } } else { StringBuilder buffer = new StringBuilder(string); int additionalCharsPerMatch = ("<match>" + "</match>").length(); int matchCount = 0; while (matcher.nextMatch()) { buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch, matcher.getEnd() + matchCount * additionalCharsPerMatch, "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>"); ++matchCount; } System.out.println(buffer.toString()); } } ++curPattern; } }
From source file:com.zarkonnen.longan.Main.java
public static void main(String[] args) throws IOException { // Use Apache Commons CLI (packaged into the Jar) to parse command line options. Options options = new Options(); Option helpO = OptionBuilder.withDescription("print help").create("h"); Option versionO = OptionBuilder.withDescription("print version").create("v"); Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg() .withArgName("file").create("o"); Option formatO = OptionBuilder .withDescription("output format: one of plaintext (default) and visualize (debug output in png)") .hasArg().withArgName("format").withLongOpt("format").create(); Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads " + "command line strings one per line exactly as above. If no output file is " + "specified, returns a line containing the number of output lines before the " + "output. If there is an error, returns a single line with the error message. " + "Shut down server by sending \"quit\".").withLongOpt("server").create(); Option openCLO = OptionBuilder .withDescription(//from ww w . j av a 2s. c o m "enables use of the graphics card to " + "support the OCR system. Defaults to true.") .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create(); options.addOption(helpO); options.addOption(versionO); options.addOption(outputO); options.addOption(formatO); options.addOption(serverO); options.addOption(openCLO); CommandLineParser clp = new GnuParser(); try { CommandLine line = clp.parse(options, args); if (line.hasOption("h")) { new HelpFormatter().printHelp(INVOCATION, options); System.exit(0); } if (line.hasOption("v")) { System.out.println(Longan.VERSION); System.exit(0); } boolean enableOpenCL = true; if (line.hasOption("enable-opencl")) { enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true") || line.getOptionValue("enable-opencl").equals("1"); } if (line.hasOption("server")) { Longan longan = Longan.getDefaultImplementation(enableOpenCL); BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in)); while (true) { String input = inputR.readLine(); if (input.trim().equals("quit")) { return; } String[] args2 = splitInput(input); Options o2 = new Options(); o2.addOption(outputO); o2.addOption(formatO); try { line = clp.parse(o2, args2); File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.out.println("You must specify an output file for non-plaintext output."); continue; } if (line.getArgList().isEmpty()) { System.out.println("Please specify an input image."); continue; } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image at a time"); continue; } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.out.println("The input image does not exist."); continue; } try { Result result = longan.process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.println(numNewlines(txt) + 1); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(result, fos); } finally { fos.close(); } } } catch (Exception e) { System.out.println("Processing error: " + exception(e)); } } catch (ParseException e) { System.out.println("Input not recognized: " + exception(e)); } } // End server loop } else { // Single invocation File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.err.println("You must specify an output file for non-plaintext output."); System.exit(1); } if (line.getArgList().isEmpty()) { System.err.println("Please specify an input image."); new HelpFormatter().printHelp(INVOCATION, options); System.exit(1); } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image only. To process multiple " + "images, use server mode."); System.exit(1); } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.err.println("The input image does not exist."); System.exit(1); } try { Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(format.convert(result), fos); } finally { fos.close(); } } } catch (Exception e) { System.err.println("Processing error: " + exception(e)); System.exit(1); } } } catch (ParseException e) { System.err.println("Parsing command line input failed: " + exception(e)); System.exit(1); } }
From source file:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java
public static void main(String[] args) { JahiaLogAnalyzer jahiaLogAnalyzer = new JahiaLogAnalyzerImpl(); File inputFile = null; if (args != null && args.length > 0) { inputFile = new File(args[0]); if (inputFile.exists()) { log.info("Analyzing logs in " + inputFile + "..."); } else {/* w w w.ja v a 2 s.co m*/ inputFile = null; } } else { initUI(); } jahiaLogAnalyzer.start(inputFile, null); }
From source file:act.installer.UniprotInstaller.java
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, CompoundNotFoundException { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//www .ja v a 2s .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(UniprotInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(UniprotInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH)); String dbName = cl.getOptionValue(OPTION_DB_NAME); if (!uniprotFile.exists()) { String msg = String.format("Uniprot file path is null"); LOGGER.error(msg); throw new RuntimeException(msg); } else { MongoDB db = new MongoDB("localhost", 27017, dbName); DBIterator iter = db.getDbIteratorOverOrgs(); Iterator<Organism> orgIterator = new Iterator<Organism>() { @Override public boolean hasNext() { boolean hasNext = iter.hasNext(); if (!hasNext) iter.close(); return hasNext; } @Override public Organism next() { DBObject o = iter.next(); return db.convertDBObjectToOrg(o); } }; OrgMinimalPrefixGenerator prefixGenerator = new OrgMinimalPrefixGenerator(orgIterator); Map<String, String> minimalPrefixMapping = prefixGenerator.getMinimalPrefixMapping(); UniprotInstaller installer = new UniprotInstaller(uniprotFile, db, minimalPrefixMapping); installer.init(); } }
From source file:TaskManager.java
public static void main(String[] args) { String configFileName = "tasks.conf"; if (args.length == 1) { configFileName = args[0];//from ww w. j ava 2 s .c o m } 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:com.act.utils.parser.GenbankInterpreter.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 . jav a 2s .c om } 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(GenbankInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(GenbankInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File genbankFile = new File(cl.getOptionValue(OPTION_GENBANK_PATH)); String seq_type = cl.getOptionValue(OPTION_SEQ_TYPE); if (!genbankFile.exists()) { String msg = "Genbank file path is null"; LOGGER.error(msg); throw new RuntimeException(msg); } else { GenbankInterpreter reader = new GenbankInterpreter(genbankFile, seq_type); reader.init(); reader.printSequences(); } }
From source file:com.zimbra.cs.mailbox.util.MetadataDump.java
public static void main(String[] args) { try {/*w w w .j a v a 2 s . c o m*/ CliUtil.toolSetup("WARN"); int mboxId = 0; int itemId = 0; PrintStream out = new PrintStream(System.out, true, "utf-8"); CommandLine cl = parseArgs(args); if (cl.hasOption(OPT_HELP)) { usage(null); System.exit(0); } // Get data from file. String infileName = cl.getOptionValue(OPT_FILE); if (infileName != null) { File file = new File(infileName); if (file.exists()) { String encoded = loadFromFile(file); Metadata md = new Metadata(encoded); String pretty = md.prettyPrint(); out.println(pretty); return; } else { System.err.println("File " + infileName + " does not exist"); System.exit(1); } } // Get data from input String. String encoded = cl.getOptionValue(OPT_STR); if (!StringUtil.isNullOrEmpty(encoded)) { Metadata md = new Metadata(encoded); String pretty = md.prettyPrint(); out.println(pretty); return; } // Get data from db. DbPool.startup(); DbConnection conn = null; try { boolean fromDumpster = cl.hasOption(OPT_DUMPSTER); String mboxIdStr = cl.getOptionValue(OPT_MAILBOX_ID); String itemIdStr = cl.getOptionValue(OPT_ITEM_ID); if (mboxIdStr == null || itemIdStr == null) { usage(null); System.exit(1); return; } if (mboxIdStr.matches("\\d+")) { try { mboxId = Integer.parseInt(mboxIdStr); } catch (NumberFormatException e) { System.err.println("Invalid mailbox id " + mboxIdStr); System.exit(1); } } else { conn = DbPool.getConnection(); mboxId = lookupMailboxIdFromEmail(conn, mboxIdStr); } try { itemId = Integer.parseInt(itemIdStr); } catch (NumberFormatException e) { usage(null); System.exit(1); } if (conn == null) conn = DbPool.getConnection(); doDump(conn, mboxId, itemId, fromDumpster, out); } finally { DbPool.quietClose(conn); } } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(); System.err.println(); e.printStackTrace(); System.exit(1); } }