Example usage for java.nio.file Paths get

List of usage examples for java.nio.file Paths get

Introduction

In this page you can find the example usage for java.nio.file Paths get.

Prototype

public static Path get(URI uri) 

Source Link

Document

Converts the given URI to a Path object.

Usage

From source file:com.amazon.kinesis.streaming.agent.Agent.java

public static void main(String[] args) throws Exception {
    AgentOptions opts = AgentOptions.parse(args);
    String configFile = opts.getConfigFile();
    AgentConfiguration config = tryReadConfigurationFile(Paths.get(opts.getConfigFile()));
    Path logFile = opts.getLogFile() != null ? Paths.get(opts.getLogFile())
            : (config != null ? config.logFile() : null);
    String logLevel = opts.getLogLevel() != null ? opts.getLogLevel()
            : (config != null ? config.logLevel() : null);
    int logMaxBackupFileIndex = (config != null ? config.logMaxBackupIndex() : -1);
    long logMaxFileSize = (config != null ? config.logMaxFileSize() : -1L);
    Logging.initialize(logFile, logLevel, logMaxBackupFileIndex, logMaxFileSize);
    final Logger logger = Logging.getLogger(Agent.class);

    // Install an unhandled exception hook
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from   w  w w  .ja  v  a  2s.c om
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof OutOfMemoryError) {
                // This prevents the JVM from hanging in case of an OOME
                dontShutdownOnExit = true;
            }
            String msg = "FATAL: Thread " + t.getName() + " threw an unrecoverable error. Aborting application";
            try {
                try { // We don't know if logging is still working
                    logger.error(msg, e);
                } finally {
                    System.err.println(msg);
                    e.printStackTrace();
                }
            } finally {
                System.exit(1);
            }
        }
    });

    try {
        logger.info("Reading configuration from file: {}", configFile);
        if (config == null) {
            config = readConfigurationFile(Paths.get(opts.getConfigFile()));
        }
        // Initialize and start the agent
        AgentContext agentContext = new AgentContext(config);
        if (agentContext.flows().isEmpty()) {
            throw new ConfigurationException("There are no flows configured in configuration file.");
        }
        final Agent agent = new Agent(agentContext);

        // Make sure everything terminates cleanly when process is killed
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (!dontShutdownOnExit && agent.isRunning()) {
                    agent.stopAsync();
                    agent.awaitTerminated();
                }
            }
        });

        agent.startAsync();
        agent.awaitRunning();
        agent.awaitTerminated();
    } catch (Exception e) {
        logger.error("Unhandled error.", e);
        System.err.println("Unhandled error.");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.bekwam.resignator.commands.SignCommand.java

public static void main(String[] args) throws Exception {
    SignCommand cmd = new SignCommand();
    cmd.signJAR(Paths.get("C:\\Users\\carl_000\\.resignator\\myoutputjar.jar"),
            Paths.get("C:\\Users\\carl_000\\git\\resignator-repos-1\\resignator\\mykeystore3"), "ab987c",
            "business3", "ab987c", s -> System.out.println(s));
}

From source file:CountLetter.java

public static void main(String[] args) throws IOException {

    if (args.length != 1 || args[0].length() != 1)
        usage();//w  ww  .  ja va  2  s. co  m

    char lookFor = args[0].charAt(0);
    Path file = Paths.get("xanadu.txt");
    int count = new CountLetter(lookFor, file).count();
    System.out.format("File '%s' has %d instances of letter '%c'.%n", file, count, lookFor);
}

From source file:com.google.infrastructuredmap.MapAndMarkdownExtractorMain.java

public static void main(String[] args) throws IOException, ParseException {

    Options options = new Options();
    options.addOption(ARG_KML, true, "path to KML input");
    options.addOption(ARG_MARKDOWN, true, "path to Markdown input");
    options.addOption(ARG_JSON_OUTPUT, true, "path to write json output");
    options.addOption(ARG_JSONP, true, "JSONP template to wrap output JSON data");

    CommandLineParser parser = new DefaultParser();
    CommandLine cli = parser.parse(options, args);

    // Extract map features from the input KML.
    MapData data = null;//w ww  . ja v  a2s .  c  o m
    try (InputStream in = openStream(cli.getOptionValue(ARG_KML))) {
        Kml kml = Kml.unmarshal(in);
        data = MapDataExtractor.extractMapData(kml);
    }

    // Extract project features from the input Markdown.
    Map<String, List<ProjectReference>> references = MarkdownReferenceExtractor
            .extractReferences(Paths.get(cli.getOptionValue(ARG_MARKDOWN)));
    for (MapFeature feature : data.features) {
        List<ProjectReference> referencesForId = references.get(feature.id);
        if (referencesForId == null) {
            throw new IllegalStateException("Unknown project reference: " + feature.id);
        }
        feature.projects = referencesForId;
    }

    // Write the resulting data to the output path.
    Gson gson = new Gson();
    try (FileWriter out = new FileWriter(cli.getOptionValue(ARG_JSON_OUTPUT))) {
        String json = gson.toJson(data);
        if (cli.hasOption(ARG_JSONP)) {
            json = String.format(cli.getOptionValue(ARG_JSONP), json);
        }
        out.write(json);
    }
}

From source file:controllers.oer.NtToEs.java

public static void main(String... args) throws ElasticsearchException, FileNotFoundException, IOException {
    if (args.length != 1 && args.length != 2) {
        System.out.println("Pass the root directory to crawl. "
                + "Will recursively gather all content from *.nt "
                + "files with identical names, convert these to " + "compact JSON-LD and index it in ES. "
                + "If a second argument is passed it is processed " + "as a TSV file that maps file names (w/o "
                + "extensions) to IDs to be used for ES. Else the " + "file names (w/o extensions) are used.");
        args = new String[] { "../oer-data/tmp", "../oer-data/src/main/resources/internalId2uuid.tsv" };
        System.out.println("Using defaults: " + Arrays.asList(args));
    }//from w w w  .  j ava2s.  co m
    if (args.length == 2)
        initMap(args[1]);
    TripleCrawler crawler = new TripleCrawler();
    Files.walkFileTree(Paths.get(args[0]), crawler);
    createIndex(config(), INDEX);
    process(crawler.data);
}

From source file:org.wte4j.examples.showcase.server.hsql.ShowCaseDbInitializer.java

public static void main(String... args) {
    ShowCaseDbInitializer initializer = new ShowCaseDbInitializer(new StaticApplicationContext());
    boolean overide = false;
    if (args.length == 2) {
        overide = Boolean.parseBoolean(args[1]);
    }/*from   w w w.j a v  a 2s  .  c om*/
    HsqlServerBean hsqlServerBean = initializer.createDatabase(Paths.get(args[0]), overide);
    hsqlServerBean.startDatabase();
}

From source file:com.booktrack.vader.Main.java

/**
 * main entry point and demo case for Vader
 * @param args the arguments - explained below in the code
 * @throws Exception anything goes wrong - except
 *//* w  w w .j  av  a  2s  .  c  o m*/
public static void main(String[] args) throws Exception {

    // create Options object for command line parsing
    Options options = new Options();
    options.addOption("file", true, "input text-file (-file) to read and analyse using Vader");

    CommandLineParser cmdParser = new DefaultParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = cmdParser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        logger.error("invalid command line: " + exp.getMessage());
        System.exit(0);
    }

    // get the command line argument -file
    String inputFile = line.getOptionValue("file");
    if (inputFile == null) {
        help(options);
        System.exit(0);
    }
    if (!new File(inputFile).exists()) {
        logger.error("file does not exist: " + inputFile);
        System.exit(0);
    }

    // example use of the classes
    // read the entire input file
    String fileText = new String(Files.readAllBytes(Paths.get(inputFile)));

    // setup Vader
    Vader vader = new Vader();
    vader.init(); // load vader

    // setup nlp processor
    VaderNLP vaderNLP = new VaderNLP();
    vaderNLP.init(); // load open-nlp

    // parse the text into a set of sentences
    List<List<Token>> sentenceList = vaderNLP.parse(fileText);

    // apply vader analysis to each sentence
    for (List<Token> sentence : sentenceList) {
        VScore vaderScore = vader.analyseSentence(sentence);
        logger.info("sentence:" + Token.tokenListToString(sentence));
        logger.info("Vader score:" + vaderScore.toString());
    }

}

From source file:at.co.malli.relpm.RelPM.java

/**
 * @param args the command line arguments
 *///  w w w .ja  v a 2s . 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:daylightchart.Main.java

/**
 * Main window.//from  w  w  w  . j av  a  2  s.c  o  m
 *
 * @param args
 *        Arguments
 */
public static void main(final String[] args) {

    CommandLineUtility.setLogLevel(args);

    // Parse command line
    final CommandLineParser parser = new CommandLineParser();
    parser.addOption(new BooleanOption(Option.NO_SHORT_FORM, OPTION_SLIMUI));
    parser.addOption(new StringOption(Option.NO_SHORT_FORM, OPTION_PREFERENCES, null));
    parser.addOption(new StringOption(Option.NO_SHORT_FORM, OPTION_LOCATION, null));
    parser.parse(args);
    boolean slimUi = parser.getBooleanOptionValue(OPTION_SLIMUI);
    final String preferencesDirectory = parser.getStringOptionValue(OPTION_PREFERENCES);
    final String locationString = parser.getStringOptionValue(OPTION_LOCATION);
    Location location = null;
    if (locationString != null) {
        try {
            location = LocationsListParser.parseLocation(locationString);
        } catch (final ParserException e) {
            location = null;
        }
    }

    if (StringUtils.isNotBlank(preferencesDirectory)) {
        UserPreferences.initialize(Paths.get(preferencesDirectory));
    }

    // Set UI look and feel
    try {
        PlasticLookAndFeel.setPlasticTheme(new LightGray());
        UIManager.setLookAndFeel(new PlasticLookAndFeel());
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Cannot set look and feel");
    }

    final Options options = UserPreferences.optionsFile().getData();
    if (!slimUi) {
        slimUi = options.isSlimUi();
    }
    options.setSlimUi(slimUi);
    UserPreferences.optionsFile().save(options);
    new DaylightChartGui(location, slimUi).setVisible(true);

}

From source file:eu.itesla_project.online.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {//w ww . j a  v  a 2s.c  o  m
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        String mode = line.getOptionValue("m");
        Path tmpDir = Paths.get(line.getOptionValue("t"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("s"));
        String statisticsDbName = line.getOptionValue("d");
        int coresPerRank = Integer.parseInt(line.getOptionValue("n"));
        Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool();
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName);
            try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                    mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                OnlineConfig config = OnlineConfig.load();
                try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager,
                        scheduledExecutorService, executorService, true)) {
                    switch (mode) {
                    case "ui":
                        System.out.println("LocalOnlineApplication created");
                        System.out.println("Waiting till shutdown");
                        // indefinitely wait for JMX commands
                        //TimeUnit.DAYS.sleep(Integer.MAX_VALUE);
                        synchronized (application) {
                            try {
                                application.wait();
                            } catch (InterruptedException ex) {
                            }

                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid mode " + mode);
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
            executorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}