Example usage for java.lang Runtime getRuntime

List of usage examples for java.lang Runtime getRuntime

Introduction

In this page you can find the example usage for java.lang Runtime getRuntime.

Prototype

public static Runtime getRuntime() 

Source Link

Document

Returns the runtime object associated with the current Java application.

Usage

From source file:com.arpnetworking.clusteraggregator.Main.java

/**
 * Entry point.//ww w . ja v a 2  s . co m
 *
 * @param args command line arguments
 */
public static void main(final String[] args) {
    Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
        LOGGER.error().setMessage("Unhandled exception!").setThrowable(throwable).log();
    });

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
        LOGGER.error().setMessage("Unhandled exception!").setThrowable(throwable).log();
    });

    LOGGER.info().setMessage("Launching cluster-aggregator").log();

    Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD);

    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }

    LOGGER.debug().setMessage("Loading configuration from file").addData("file", args[0]).log();

    Optional<DynamicConfiguration> configuration = Optional.absent();
    Optional<Configurator<Main, ClusterAggregatorConfiguration>> configurator = Optional.absent();
    try {
        final File configurationFile = new File(args[0]);
        configurator = Optional.of(new Configurator<>(Main::new, ClusterAggregatorConfiguration.class));
        final ObjectMapper objectMapper = ClusterAggregatorConfiguration.createObjectMapper();
        configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
                .addSourceBuilder(new JsonNodeFileSource.Builder().setObjectMapper(objectMapper)
                        .setFile(configurationFile))
                .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
                .addListener(configurator.get()).build());

        configuration.get().launch();

        // Wait for application shutdown
        SHUTDOWN_SEMAPHORE.acquire();
    } catch (final InterruptedException e) {
        throw Throwables.propagate(e);
    } finally {
        if (configurator.isPresent()) {
            configurator.get().shutdown();
        }
        if (configuration.isPresent()) {
            configuration.get().shutdown();
        }
        // Notify the shutdown that we're done
        SHUTDOWN_SEMAPHORE.release();
    }
}

From source file:com.mebigfatguy.roomstore.RoomStore.java

public static void main(String[] args) {
    Options options = createOptions();/*from w  w w.  jav  a 2  s. c  o  m*/

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmdLine = parser.parse(options, args);
        String nickname = cmdLine.getOptionValue(NICK_NAME);
        String server = cmdLine.getOptionValue(IRCSERVER);
        String[] channels = cmdLine.getOptionValues(CHANNELS);
        String[] endPoints = cmdLine.getOptionValues(ENDPOINTS);
        String rf = cmdLine.getOptionValue(RF);

        if ((endPoints == null) || (endPoints.length == 0)) {
            endPoints = new String[] { "127.0.0.1" };
        }

        int replicationFactor;
        try {
            replicationFactor = Integer.parseInt(rf);
        } catch (Exception e) {
            replicationFactor = 1;
        }

        final IRCConnector connector = new IRCConnector(nickname, server, channels);

        Cluster cluster = new Cluster.Builder().addContactPoints(endPoints).build();
        final Session session = cluster.connect();

        CassandraWriter writer = new CassandraWriter(session, replicationFactor);
        connector.setWriter(writer);

        connector.startRecording();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                connector.stopRecording();
                session.close();
            }
        }));

    } catch (ParseException pe) {
        System.out.println("Parse Error on command line options:");
        System.out.println(commandLineRepresentation(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roomstore", options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.callidusrobotics.irc.NaNoBot.java

public static void main(final String[] args)
        throws FileNotFoundException, IOException, NickAlreadyInUseException, IrcException {
    if (args.length > 0 && "--version".equals(args[0])) {
        System.out.println("NaNoBot version: " + getImplementationVersion());
        System.exit(0);//from w  ww .j  ava 2  s  . c  om
    }

    final String fileName = args.length > 0 ? args[0] : "./NaNoBot.properties";
    final Properties properties = new Properties();
    properties.load(new FileInputStream(new File(fileName)));

    final NaNoBot naNoBot = new NaNoBot(properties);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            naNoBot.shutdown();
        }
    });

    naNoBot.run();
}

From source file:playground.Application.java

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

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("playground");
    DispatcherHandler dispatcherHandler = new DispatcherHandler();
    dispatcherHandler.setApplicationContext(context);

    HttpServer server = new ReactorHttpServer();
    server.setPort(8080);/*from  w  w  w  .  j ava2  s .com*/
    server.setHandler(dispatcherHandler);
    server.afterPropertiesSet();
    server.start();

    CompletableFuture<Void> stop = new CompletableFuture<>();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        stop.complete(null);
    }));

    synchronized (stop) {
        stop.wait();
    }

}

From source file:com.edduarte.argus.Main.java

public static void main(String[] args) {

    installUncaughtExceptionHandler();/*w w  w  . ja v a  2  s  . c  o m*/

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("t", "threads", true, "Number of threads to be used "
            + "for computation and indexing processes. Defaults to the number " + "of available cores.");

    options.addOption("p", "port", true, "Core server port. Defaults to 9000.");

    options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost.");

    options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017.");

    options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity.");

    options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering.");

    options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants).");

    options.addOption("h", "help", false, "Shows this help prompt.");

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments. "
                + "Write -h or --help to show the list of available commands.");
        logger.error(ex.getMessage(), ex);
        return;
    }

    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar argus-core.jar", options);
        return;
    }

    int maxThreads = Runtime.getRuntime().availableProcessors() - 1;
    maxThreads = maxThreads > 0 ? maxThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        maxThreads = Integer.parseInt(threadsText);
        if (maxThreads <= 0 || maxThreads > 32) {
            logger.error("Invalid number of threads. Must be a number between 1 and 32.");
            return;
        }
    }

    int port = 9000;
    if (commandLine.hasOption('p')) {
        String portString = commandLine.getOptionValue('p');
        port = Integer.parseInt(portString);
    }

    String dbHost = "localhost";
    if (commandLine.hasOption("dbh")) {
        dbHost = commandLine.getOptionValue("dbh");
    }

    int dbPort = 27017;
    if (commandLine.hasOption("dbp")) {
        String portString = commandLine.getOptionValue("dbp");
        dbPort = Integer.parseInt(portString);
    }

    boolean isIgnoringCase = true;
    if (commandLine.hasOption("case")) {
        isIgnoringCase = false;
    }

    boolean isStoppingEnabled = false;
    if (commandLine.hasOption("stop")) {
        isStoppingEnabled = true;
    }

    boolean isStemmingEnabled = false;
    if (commandLine.hasOption("stem")) {
        isStemmingEnabled = true;
    }

    try {
        Context context = Context.getInstance();
        context.setIgnoreCase(isIgnoringCase);
        context.setStopwordsEnabled(isStoppingEnabled);
        context.setStemmingEnabled(isStemmingEnabled);
        context.start(port, maxThreads, dbHost, dbPort);

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
        System.exit(1);
    }
}

From source file:com.edduarte.vokter.Main.java

public static void main(String[] args) {

    installUncaughtExceptionHandler();/*from   w  w w .j a v  a2  s.c  o m*/

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("t", "threads", true, "Number of threads to be used "
            + "for computation and indexing processes. Defaults to the number " + "of available cores.");

    options.addOption("p", "port", true, "Core server port. Defaults to 9000.");

    options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost.");

    options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017.");

    options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity.");

    options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering.");

    options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants).");

    options.addOption("h", "help", false, "Shows this help prompt.");

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments. "
                + "Write -h or --help to show the list of available commands.");
        logger.error(ex.getMessage(), ex);
        return;
    }

    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar vokter-core.jar", options);
        return;
    }

    int maxThreads = Runtime.getRuntime().availableProcessors() - 1;
    maxThreads = maxThreads > 0 ? maxThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        maxThreads = Integer.parseInt(threadsText);
        if (maxThreads <= 0 || maxThreads > 32) {
            logger.error("Invalid number of threads. Must be a number between 1 and 32.");
            return;
        }
    }

    int port = 9000;
    if (commandLine.hasOption('p')) {
        String portString = commandLine.getOptionValue('p');
        port = Integer.parseInt(portString);
    }

    String dbHost = "localhost";
    if (commandLine.hasOption("dbh")) {
        dbHost = commandLine.getOptionValue("dbh");
    }

    int dbPort = 27017;
    if (commandLine.hasOption("dbp")) {
        String portString = commandLine.getOptionValue("dbp");
        dbPort = Integer.parseInt(portString);
    }

    boolean isIgnoringCase = true;
    if (commandLine.hasOption("case")) {
        isIgnoringCase = false;
    }

    boolean isStoppingEnabled = false;
    if (commandLine.hasOption("stop")) {
        isStoppingEnabled = true;
    }

    boolean isStemmingEnabled = false;
    if (commandLine.hasOption("stem")) {
        isStemmingEnabled = true;
    }

    try {
        Context context = Context.getInstance();
        context.setIgnoreCase(isIgnoringCase);
        context.setStopwordsEnabled(isStoppingEnabled);
        context.setStemmingEnabled(isStemmingEnabled);
        context.start(port, maxThreads, dbHost, dbPort);

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
        System.exit(1);
    }
}

From source file:de.saly.elasticsearch.importer.imap.IMAPImporterCl.java

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

    if (args.length < 1) {
        System.out.println("Usage: IMAPImporterC [-e] <config-file>");
        System.exit(-1);/*  ww w.j a  v a  2 s  . c o m*/
    }

    String configFile = null;
    boolean embedded = false;

    if (args.length == 1) {
        configFile = args[0];
    }

    if (args.length == 2) {

        embedded = "-e".equals(args[0]);
        configFile = args[1];
    }

    System.out.println("Config File: " + configFile);
    System.out.println("Embedded: " + embedded);

    final Thread mainThread = Thread.currentThread();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            System.out.println("Will shutdown ...");

            IMAPImporterCl.stop();

            try {
                mainThread.join();
                System.out.println("Shudown done");
            } catch (InterruptedException e) {

            }
        }
    });

    start(configFile, embedded);
}

From source file:com.serotonin.m2m2.Main.java

/**
 *
 * @param args//from  w  w w.jav a 2  s. co m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Providers.add(ICoreLicense.class, new CoreLicenseDefinition());

    Common.MA_HOME = System.getProperty("ma.home");
    Common.M2M2_HOME = Common.MA_HOME;

    new File(Common.MA_HOME, "RESTART").delete();

    Common.envProps = new ReloadingProperties("env");

    openZipFiles();
    ClassLoader moduleClassLoader = loadModules();

    Lifecycle lifecycle = new Lifecycle();
    Providers.add(ILifecycle.class, lifecycle);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ((ILifecycle) Providers.get(ILifecycle.class)).terminate();
        }
    });
    try {
        lifecycle.initialize(moduleClassLoader);
        if ((!GraphicsEnvironment.isHeadless()) && (Desktop.isDesktopSupported())
                && (Common.envProps.getBoolean("web.openBrowserOnStartup"))) {
            Desktop.getDesktop().browse(new URI(new StringBuilder().append("http://localhost:")
                    .append(Common.envProps.getInt("web.port", 8088)).toString()));
        }
    } catch (Exception e) {
        LOG.error("Error during initialization", e);
        lifecycle.terminate();
    }
}

From source file:at.ac.tuwien.dsg.comot.m.adapter.Main.java

public static void main(String[] args) {

    Options options = createOptions();//  w w w  .j a v  a 2  s.  co m

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("mh") && cmd.hasOption("ih") && cmd.hasOption("ip")) {

            Integer infoPort = null;

            try {
                infoPort = new Integer(cmd.getOptionValue("ip"));
            } catch (NumberFormatException e) {
                LOG.warn("infoPort must be a number");
                showHelp(options);
            }

            AppContextAdapter.setBrokerHost(cmd.getOptionValue("mh"));
            AppContextAdapter.setInfoHost(cmd.getOptionValue("ih"));
            AppContextAdapter.setInfoPort(infoPort);

            context = new AnnotationConfigApplicationContext(AppContextAdapter.class);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if (context != null) {
                        context.close();
                    }
                }
            });

            if (cmd.hasOption("m") || cmd.hasOption("r") || cmd.hasOption("s")) {

                Manager manager = context.getBean(EpsAdapterManager.class);
                String serviceId = getServiceInstanceId();
                String participantId = context.getBean(InfoClient.class).getOsuInstanceByServiceId(serviceId)
                        .getId();

                if (cmd.hasOption("m")) {

                    Monitoring processor = context.getBean(Monitoring.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("r")) {

                    Control processor = context.getBean(Control.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("s")) {

                    Deployment processor = context.getBean(Deployment.class);
                    manager.start(participantId, processor);
                }

            } else {
                LOG.warn("No adapter type specified");
                showHelp(options);
            }
        } else {
            LOG.warn("Required parameters were not specified.");
            showHelp(options);
        }
    } catch (Exception e) {
        LOG.error("{}", e);
        showHelp(options);
    }
}

From source file:com.clicktravel.cheddar.server.rest.application.RestApplication.java

/**
 * Starts the RestServer to listen on the given port and address combination
 *
 * @param args String arguments, {@code [context [service-port [status-port [bind-address] ] ] ]} where
 *            <ul>/*from   w w w .  j  a  v  a2  s  .c o m*/
 *            <li>{@code context} - Name of application, defaults to {@code UNKNOWN}</li>
 *            <li>{@code service-port} - Port number for REST service endpoints, defaults to {@code 8080}</li>
 *            <li>{@code status-port} - Port number for REST status endpoints ({@code /status} and
 *            {@code /status/healthCheck}), defaults to {@code service-port + 100}</li>
 *            <li>{@code bind-address} - Local IP address to bind server to, defaults to {@code 0.0.0.0}</li>
 *            </ul>
 *
 * @throws Exception
 */
public static void main(final String... args) {
    final String context = args.length > 0 ? args[0] : "UNKNOWN";
    final int servicePort = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    final int statusPort = args.length > 2 ? Integer.parseInt(args[2]) : servicePort + 100;
    final String bindAddress = args.length > 3 ? args[3] : "0.0.0.0";
    MDC.put("context", context);
    MDC.put("hostId", System.getProperty("host.id", "UNKNOWN"));
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    final Logger logger = LoggerFactory.getLogger(RestApplication.class);
    try {
        logger.info("Java process starting");
        logger.debug(String.format("java.version:[%s] java.vendor:[%s]", System.getProperty("java.version"),
                System.getProperty("java.vendor")));
        @SuppressWarnings("resource")
        final ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        logger.debug("Finished getting ApplicationContext");
        final ApplicationLifecycleController applicationLifecycleController = applicationContext
                .getBean(ApplicationLifecycleController.class);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("Shutdown hook invoked - Commencing graceful termination of Java process");
            applicationLifecycleController.shutdownApplication();
            logger.info("Java process terminating");
        }));
        applicationLifecycleController.startApplication(servicePort, statusPort, bindAddress);
        Thread.currentThread().join();
    } catch (final InterruptedException e) {
        logger.info("Java process interrupted");
        System.exit(1);
    } catch (final Exception e) {
        logger.error("Error starting Java process", e);
        System.exit(1);
    }
}