List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:com.acmutv.ontoqa.GrammalexMain.java
/** * The app main method, executed when the program is launched. * @param args The command line arguments. * @throws IllegalAccessException // ww w .j av a2s .c o m * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException { //CliService.handleArguments(args); RuntimeManager.registerShutdownHooks(new ShutdownHook()); try { Path path = FileSystems.getDefault().getPath("data/lexicon").toAbsolutePath(); String currentDirectory = path.toString(); final JFileChooser fc = new JFileChooser(currentDirectory); int returnVal = fc.showOpenDialog(null); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); if (returnVal == JFileChooser.OPEN_DIALOG) { File file = fc.getSelectedFile(); System.out.println("File Select: " + file.getName() + "\n\n"); List<LexicalEntry> lEntries = LexiconUsage.getLexicalEntries(file.getAbsolutePath(), "", LexiconFormat.RDFXML); Grammar grammar = SerializeSltag.getAllElementarySltag(lEntries); SerializeSltag.writeGrammarOnFile(grammar, fileJson); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(0); }
From source file:org.wor.drawca.DrawCAMain.java
/** * Main function which start drawing the cellular automata. * * @param args Command line arguments.//from ww w . j a va2 s. c o m */ public static void main(final String[] args) { final Logger log = Logger.getGlobal(); LogManager.getLogManager().reset(); Options options = new Options(); boolean hasArgs = true; // TODO: show defaults in option description options.addOption("h", "help", !hasArgs, "Show this help message"); options.addOption("pci", "perclickiteration", !hasArgs, "Generate one line per mouse click"); options.addOption("v", "verbose", hasArgs, "Verbosity level [-1,7]"); options.addOption("r", "rule", hasArgs, "Rule number to use 0-255"); options.addOption("wh", "windowheigth", hasArgs, "Draw window height"); options.addOption("ww", "windowwidth", hasArgs, "Draw window width"); options.addOption("x", "xscalefactor", hasArgs, "X Scale factor"); options.addOption("y", "yscalefactor", hasArgs, "Y scale factor"); options.addOption("f", "initline", hasArgs, "File name with Initial line."); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); showHelp(options); return; } // Options without an argument if (cmd.hasOption("h")) { showHelp(options); return; } final boolean perClickIteration = cmd.hasOption("pci"); // Options with an argument final int verbosityLevel = Integer.parseInt(cmd.getOptionValue('v', "0")); final int rule = Integer.parseInt(cmd.getOptionValue('r', "110")); final int windowHeigth = Integer.parseInt(cmd.getOptionValue("wh", "300")); final int windowWidth = Integer.parseInt(cmd.getOptionValue("ww", "400")); final float xScaleFactor = Float.parseFloat(cmd.getOptionValue('x', "2.0")); final float yScaleFactor = Float.parseFloat(cmd.getOptionValue('y', "2.0")); final String initLineFile = cmd.getOptionValue('f', ""); final Level logLevel = VERBOSITY_MAP.get(verbosityLevel); log.setLevel(logLevel); // Set log handler Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(logLevel); log.addHandler(consoleHandler); log.info("Log level set to: " + log.getLevel()); // Read initial line from a file String initLine = ""; if (initLineFile.length() > 0) { Path initLineFilePath = FileSystems.getDefault().getPath(initLineFile); try { // Should be string of ones and zeros only initLine = new String(Files.readAllBytes(initLineFilePath), "UTF-8"); } catch (IOException e) { System.err.format("IOException: %s\n", e); return; } } SwingUtilities.invokeLater(new RunGUI(windowWidth, windowHeigth, xScaleFactor, yScaleFactor, rule, initLine, perClickIteration)); }
From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java
/** * @param args// w w w . j a va 2 s . co m */ public static void main(String[] args) { // process command-line options Options options = new Options(); options.addOption("n", "noaddr", false, "do not do any address matching (for testing)"); options.addOption("i", "info", false, "create and populate address information table"); options.addOption("h", "help", false, "this message"); // database connection options.addOption("s", "server", true, "database server to connect to"); options.addOption("d", "database", true, "OSM database name"); options.addOption("u", "user", true, "OSM database user name"); options.addOption("p", "pass", true, "OSM database password"); // logging options options.addOption("l", "logdir", true, "log file directory (default './logs')"); options.addOption("e", "loglevel", true, "log level (default 'FINEST')"); // automatically generate the help statement HelpFormatter help_formatter = new HelpFormatter(); // database URI for connection String dburi = null; // Information message for help screen String info_msg = "IzbirkomExtractor [options] <html_directory>"; try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h') || cmd.getArgs().length != 1) { help_formatter.printHelp(info_msg, options); System.exit(1); } /* prohibit n and i together */ if (cmd.hasOption('n') && cmd.hasOption('i')) { System.err.println("Options 'n' and 'i' cannot be used together."); System.exit(1); } /* require database arguments without -n */ if (cmd.hasOption('n') && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) { System.err.println("Options 'n' and does not need any databse parameters."); System.exit(1); } /* require all 4 database options to be used together */ if (!cmd.hasOption('n') && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) { System.err.println( "For database access all of the following arguments have to be specified: server, database, user, pass"); System.exit(1); } /* useful variables */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm"); String dateString = formatter.format(new Date()); /* setup logging */ File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs"); FileUtils.forceMkdir(logdir); File log_file_name = new File( logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log"); FileHandler log_file = new FileHandler(log_file_name.getPath()); /* create "latest" link to currently created log file */ Path latest_log_link = Paths.get(logdir + "/latest"); Files.deleteIfExists(latest_log_link); Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName())); log_file.setFormatter(new SimpleFormatter()); LogManager.getLogManager().reset(); // prevents logging to console logger.addHandler(log_file); logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST); // open directory with HTML files and create file list File dir = new File(cmd.getArgs()[0]); if (!dir.isDirectory()) { System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting"); System.exit(1); } PathMatcher pmatcher = FileSystems.getDefault() .getPathMatcher("glob:? * ?*.html"); ArrayList<File> html_files = new ArrayList<>(); for (Path file : Files.newDirectoryStream(dir.toPath())) if (pmatcher.matches(file.getFileName())) html_files.add(file.toFile()); if (html_files.size() == 0) { System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting"); System.exit(1); } // create csvResultSink FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv"); OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8"); ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#')); // Connect to DB and osmAddressMatcher AddressMatcher osmAddressMatcher; DBSink dbSink = null; DBInfoSink dbInfoSink = null; if (cmd.hasOption('n')) { osmAddressMatcher = new DummyAddressMatcher(); } else { dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d'); Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'), cmd.getOptionValue('p')); osmAddressMatcher = new OsmAddressMatcher(con); dbSink = new DBSink(con); if (cmd.hasOption('i')) dbInfoSink = new DBInfoSink(con); } /* create resultsinks */ SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor(); sm.addResultSink(csvResultSink); if (dbSink != null) { sm.addResultSink(dbSink); if (dbInfoSink != null) sm.addResultSink(dbInfoSink); } // create tableExtractor TableExtractor te = new TableExtractor(osmAddressMatcher, sm); // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters // iterate through files logger.info("Start processing " + html_files.size() + " files in " + dir); for (int i = 0; i < html_files.size(); i++) { System.err.println("Parsing #" + i + ": " + html_files.get(i)); te.processHTMLfile(html_files.get(i)); } System.err.println("Processed " + html_files.size() + " HTML files"); logger.info("Finished processing " + html_files.size() + " files in " + dir); } catch (ParseException e1) { System.err.println("Failed to parse CLI: " + e1.getMessage()); help_formatter.printHelp(info_msg, options); System.exit(1); } catch (IOException e) { System.err.println("I/O Exception: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.println("Database '" + dburi + "': " + e.getMessage()); System.exit(1); } catch (ResultSinkException e) { System.err.println("Failed to initialize ResultSink: " + e.getMessage()); System.exit(1); } catch (TableExtractorException e) { System.err.println("Failed to initialize Table Extractor: " + e.getMessage()); System.exit(1); } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) { System.err.println("Something really odd happened: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:io.github.alechenninger.monarch.Main.java
public static void main(String[] args) throws ParseException, IOException { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setPrettyFlow(true);/*w w w. j a va 2 s. c om*/ dumperOptions.setIndent(2); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(dumperOptions); new Main(new Monarch(), yaml, System.getProperty("user.home") + "/.monarch/config.yaml", FileSystems.getDefault(), new MonarchParsers.Default(yaml)).run(args); }
From source file:org.polago.deployconf.DeployConfRunner.java
/** * Main entry point.//w w w .j ava2 s. co m * * @param args the runtime program arguments */ public static void main(String[] args) { Options options = new Options(); Option help = new Option("h", "help", false, "Display usage information"); options.addOption(help); Option version = new Option("v", "version", false, "Display version information and exit"); options.addOption(version); Option interactive = new Option("i", "interactive", false, "Run in interactive mode"); options.addOption(interactive); Option forceInteractive = new Option("I", "force-interactive", false, "Run in interactive mode and configure all tasks"); options.addOption(forceInteractive); Option quiet = new Option("q", "quiet", false, "Suppress most messages"); options.addOption(quiet); Option debug = new Option("d", "debug", false, "Print Debug Information"); options.addOption(debug); boolean debugEnabled = false; Option repoDir = new Option("r", "repo", true, "Repository directory to use for storing deployment configs"); options.addOption(repoDir); Option configFile = new Option("f", "deployment-config-file", true, "File to use for storing the deployment config"); options.addOption(configFile); Option templatePath = new Option("t", "deployment-template-path", true, "Path to use for locating the deployment template in the " + "<INPUT> file. Default is '" + DEFAULT_TEMPLATE_PATH + "'"); options.addOption(templatePath); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); ProjectProperties projectProperties = getProjectProperties(); if (cmd.hasOption(version.getOpt())) { System.out.print(projectProperties.getName()); System.out.print(" version "); System.out.println(projectProperties.getVersion()); System.out.println(projectProperties.getCopyrightMessage()); System.exit(0); } if (cmd.hasOption(help.getOpt())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(projectProperties.getName() + " [OPTION]... <INPUT> <OUTPUT>", projectProperties.getHelpHeader(), options, ""); System.exit(0); } if (cmd.hasOption(debug.getOpt())) { logger.info("Activating Debug Logging"); debugEnabled = true; setLogConfig("logback-debug.xml"); } else if (cmd.hasOption(quiet.getOpt())) { setLogConfig("logback-quiet.xml"); } RunMode mode = RunMode.NON_INTERACTIVE; if (cmd.hasOption(forceInteractive.getOpt())) { mode = RunMode.FORCE_INTERACTIVE; } else if (cmd.hasOption(interactive.getOpt())) { mode = RunMode.INTERACTIVE; } DeployConfRunner instance = new DeployConfRunner(mode); String envRepoDir = instance.getRepositoryDirectoryFromEnvironment(); if (cmd.hasOption(repoDir.getOpt())) { String rd = cmd.getOptionValue(repoDir.getOpt()); logger.debug("Using repository directory: {}", rd); instance.setRepositoryDirectory(rd); } else if (envRepoDir != null) { logger.debug("Using repository directory from environment {}: {}", ENV_DEPLOYCONF_REPO, envRepoDir); instance.setRepositoryDirectory(envRepoDir); } else { String rd = getDefaultRepository(); instance.setRepositoryDirectory(rd); logger.debug("Using default repository directory: {}", rd); } Path repo = FileSystems.getDefault().getPath(instance.getRepositoryDirectory()); if (!Files.exists(repo)) { Files.createDirectories(repo); } else if (!Files.isDirectory(repo)) { logger.error("Specified repository is not a directory: {}", repo); System.exit(1); } instance.setGroupManager( new FileSystemConfigGroupManager(Paths.get(instance.getRepositoryDirectory()))); if (cmd.hasOption(configFile.getOpt())) { String f = cmd.getOptionValue(configFile.getOpt()); logger.debug("Using explicit deployment file: {}", f); instance.setDeploymentConfigPath(FileSystems.getDefault().getPath(f)); } if (cmd.hasOption(templatePath.getOpt())) { String path = cmd.getOptionValue(templatePath.getOpt()); logger.debug("Using deployment template path: {}", path); instance.setDeploymentTemplatePath(path); } List<String> argList = cmd.getArgList(); if (argList.size() != 2) { System.out.println("usage: " + projectProperties.getName() + " <INPUT> <OUTPUT>"); System.exit(1); } System.exit(instance.run(argList.get(0), argList.get(1))); } catch (ParseException e) { logger.error("Command Line Parse Error: " + e.getMessage(), e); System.exit(1); } catch (Exception e) { String msg = "Internal Error: " + e.toString(); if (!debugEnabled) { msg += "\n(use the -d option to print stacktraces)"; } logger.error(msg, e); System.exit(2); } }
From source file:pl.setblack.airomem.core.disk.PersistenceDiskHelper.java
/** * Check if save of given name exists./* w ww. j ava 2 s . co m*/ */ public static boolean exists(String name) { final Path path = FileSystems.getDefault().getPath(STORAGE_FOLDER, name); return Files.exists(path); }
From source file:com.siniatech.siniautils.file.PathHelper.java
static public Path createFileWithContents(String pathString, String contents) throws IOException { Path path = FileSystems.getDefault().getPath(pathString); if (exists(path)) { throw new IOException("File " + pathString + " already exists."); } else {/* w ww . j a v a 2s .c o m*/ createFile(path); } try (BufferedWriter out = newBufferedWriter(path, Charset.defaultCharset())) { out.write(contents); return path; } }
From source file:Test.java
private static void setGroupPrincipal(Path path, String userName, String groupName) throws Exception { System.out.println("Setting owner for " + path.getFileName()); PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); PosixFileAttributes attributes = view.readAttributes(); System.out.println("Old Group: " + attributes.group().getName()); System.out.println("Old Owner: " + attributes.owner().getName()); UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(userName); GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(groupName); view.setGroup(groupPrincipal);//from w w w.j av a2 s . c o m view.setOwner(userPrincipal); attributes = view.readAttributes(); System.out.println("New Group: " + attributes.group().getName()); System.out.println("New Owner: " + attributes.owner().getName()); }
From source file:pl.setblack.airomem.core.disk.PersistenceDiskHelper.java
public static void delete(String name) { if (exists(name)) { final Path path = FileSystems.getDefault().getPath(STORAGE_FOLDER, name); Politician.beatAroundTheBush(() -> { FileUtils.deleteDirectory(path.toFile()); });/*from w ww. jav a 2 s . c o m*/ } }
From source file:uk.co.modularaudio.util.io.IOUtils.java
public static void writeUTF8(final String filePath, final String content) throws IOException { Files.write(FileSystems.getDefault().getPath(filePath), content.getBytes(StandardCharsets.UTF_8)); }