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:de.fhg.iais.cortex.Starter.java

/**
 * Starts Cortex.//  w  w  w  .  j  a  va 2s.c  o m
 * 
 * @param args
 *        the command line arguments
 * @see #configure(ListIterator) The list of applicable command line
 *      arguments
 */
public static void main(String[] args) {
    try {
        configureLogging();
        Starter starter = new Starter(".");
        starter.start(args);
        LOG.info("Cortex services started.");

        // register a shutdown hook which makes it possible to stop the
        // services with a soft kill
        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(starter));
    } catch (RuntimeException e) {
        LOG.warn("Start of Cortex failed: " + e.getMessage());
    }
}

From source file:com.twitter.distributedlog.basic.ConsoleProxyMultiWriter.java

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;//from   w  w  w. j  a  va 2  s  .c  o  m
    }

    String finagleNameStr = args[0];
    final String streamList = args[1];

    DistributedLogClient client = DistributedLogClientBuilder.newBuilder()
            .clientId(ClientId.apply("console-proxy-writer")).name("console-proxy-writer").thriftmux(true)
            .finagleNameStr(finagleNameStr).build();
    String[] streamNameList = StringUtils.split(streamList, ',');
    DistributedLogMultiStreamWriter multiStreamWriter = DistributedLogMultiStreamWriter.newBuilder()
            .streams(Lists.newArrayList(streamNameList)).bufferSize(0).client(client).flushIntervalMs(0)
            .firstSpeculativeTimeoutMs(10000).maxSpeculativeTimeoutMs(20000).requestTimeoutMs(50000).build();

    // Setup Terminal
    Terminal terminal = Terminal.setupTerminal();
    ConsoleReader reader = new ConsoleReader();
    String line;
    while ((line = reader.readLine(PROMPT_MESSAGE)) != null) {
        multiStreamWriter.write(ByteBuffer.wrap(line.getBytes(UTF_8)))
                .addEventListener(new FutureEventListener<DLSN>() {
                    @Override
                    public void onFailure(Throwable cause) {
                        System.out.println("Encountered error on writing data");
                        cause.printStackTrace(System.err);
                        Runtime.getRuntime().exit(0);
                    }

                    @Override
                    public void onSuccess(DLSN value) {
                        // done
                    }
                });
    }

    multiStreamWriter.close();
    client.close();
}

From source file:com.machinelinking.cli.loader.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("Usage: $0 <config-file> <dump>");
        System.exit(1);//  w  w  w  . ja v  a  2  s. c o m
    }

    try {
        final File configFile = check(args[0]);
        final File dumpFile = check(args[1]);
        final Properties properties = new Properties();
        properties.load(FileUtils.openInputStream(configFile));

        final Flag[] flags = WikiPipelineFactory.getInstance().toFlags(getPropertyOrFail(properties,
                LOADER_FLAGS_PROP,
                "valid flags: " + Arrays.toString(WikiPipelineFactory.getInstance().getDefinedFlags())));
        final JSONStorageFactory jsonStorageFactory = MultiJSONStorageFactory
                .loadJSONStorageFactory(getPropertyOrFail(properties, LOADER_STORAGE_FACTORY_PROP, null));
        final String jsonStorageConfig = getPropertyOrFail(properties, LOADER_STORAGE_CONFIG_PROP, null);
        final URL prefixURL = readURL(getPropertyOrFail(properties, LOADER_PREFIX_URL_PROP,
                "expected a valid URL prefix like: http://en.wikipedia.org/"), LOADER_PREFIX_URL_PROP);

        final DefaultJSONStorageLoader[] loader = new DefaultJSONStorageLoader[1];
        final boolean[] finalReportProduced = new boolean[] { false };
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (!finalReportProduced[0] && loader[0] != null) {
                    System.err.println(
                            "Process interrupted. Partial loading report: " + loader[0].createReport());
                }
                System.err.println("Shutting down.");
            }
        }));

        final JSONStorageConfiguration storageConfig = jsonStorageFactory
                .createConfiguration(jsonStorageConfig);
        try (final JSONStorage storage = jsonStorageFactory.createStorage(storageConfig)) {
            loader[0] = new DefaultJSONStorageLoader(WikiPipelineFactory.getInstance(), flags, storage);

            final StorageLoaderReport report = loader[0].load(prefixURL,
                    FileUtil.openDecompressedInputStream(dumpFile));
            System.err.println("Loading report: " + report);
            finalReportProduced[0] = true;
        }
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *//*w w w.  ja va2 s.  co  m*/
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:ch.algotrader.event.TopicEventDumper.java

public static void main(String... args) throws Exception {

    SingleConnectionFactory jmsActiveMQFactory = new SingleConnectionFactory(
            new ActiveMQConnectionFactory("tcp://localhost:61616"));
    jmsActiveMQFactory.afterPropertiesSet();
    jmsActiveMQFactory.resetConnection();

    ActiveMQTopic topic = new ActiveMQTopic(">");

    DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer();
    messageListenerContainer.setDestination(topic);
    messageListenerContainer.setConnectionFactory(jmsActiveMQFactory);
    messageListenerContainer.setSubscriptionShared(false);
    messageListenerContainer.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER);

    messageListenerContainer.setMessageListener((MessageListener) message -> {
        try {/* w  w  w  .  j  a  v a 2  s .  c o m*/
            Destination destination = message.getJMSDestination();
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println(destination + " -> " + textMessage.getText());
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                System.out.println(destination + " -> " + new String(bytes, Charsets.UTF_8));
            }
        } catch (JMSException ex) {
            throw new UnrecoverableCoreException(ex);
        }
    });

    messageListenerContainer.initialize();
    messageListenerContainer.start();

    System.out.println("Dumping messages from all topics");

    Runtime.getRuntime().addShutdownHook(new Thread(messageListenerContainer::stop));

    Thread.sleep(Long.MAX_VALUE);
}

From source file:de.fhg.iais.asc.ui.MyCortexStarter.java

/**
 * Starts Cortex./*  w w w . ja v  a 2 s .  c  om*/
 * 
 * @param args
 *        the command line arguments
 * @see #configure(ListIterator) The list of applicable command line
 *      arguments
 */
public static void main(String[] args) {
    try {
        configureLogging();
        MyCortexStarter starter = new MyCortexStarter(".");
        starter.start(args);
        LOG.info("Cortex services started.");

        // register a shutdown hook which makes it possible to stop the
        // services with a soft kill
        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(starter));
    } catch (RuntimeException e) {
        LOG.warn("Start of Cortex failed: " + e.getMessage());
    }
}

From source file:com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override//from w ww  . j a  v a2 s.  c o m
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

From source file:io.amient.examples.TwitterStreamDemo.java

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

    final String bootstrapServers = args.length == 1 ? args[0] : DEFAULT_BOOTSTRAP_SERVERS;

    //1. Launch Embedded Connect Instance for ingesting twitter feed filtered on "money" into twitter topic
    ConnectEmbedded connect = createTwitterSourceConnectInstance(bootstrapServers);
    connect.start();//  w  w  w .j a v  a 2 s.c o  m

    //2. Launch Kafka Streams Topology - 
    KafkaStreams streams = createTwitterStreamsInstance(bootstrapServers);
    try {
        streams.start();
    } catch (Throwable e) {
        log.error("Stopping the application due to streams initialization error ", e);
        connect.stop();
    }

    // The Embedded Connect's shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            connect.stop();
        }
    });

    try {
        connect.awaitStop();
        log.info("Connect closed cleanly...");
    } finally {
        streams.close();
        log.info("Stream closed cleanly...");
    }
}

From source file:ee.ria.xroad.proxy.opmonitoring.OpMonitoringBufferMemoryUsage.java

/**
 * Main function./*from   www  .  ja v  a2 s .com*/
 * @param args args
 * @throws Exception if something goes wrong.
 */
public static void main(String args[]) throws Exception {

    CommandLine cmd = parseCommandLine(args);

    if (cmd.hasOption("help")) {
        usage();

        System.exit(0);
    }

    int count = cmd.getOptionValue("count") != null ? Integer.parseInt(cmd.getOptionValue("count"))
            : DEFAULT_COUNT;

    int shortStrLen = cmd.getOptionValue("short-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("short-string-length"))
            : DEFAULT_SHORT_LONG_STRING_LENGTH;

    int longStrLen = cmd.getOptionValue("long-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("long-string-length"))
            : DEFAULT_LONG_STRING_LENGTH;

    Runtime runtime = Runtime.getRuntime();

    long before = getUsedBytes(runtime);

    createBuffer(count, shortStrLen, longStrLen);

    long after = getUsedBytes(runtime);

    log.info("Records count {}, used heap {}MB", count, (after - before) / MB);
}

From source file:PlyBounder.java

public static void main(String[] args) {

    // Get the commandline arguments
    Options options = new Options();
    // Available options
    Option plyPath = OptionBuilder.withArgName("dir").hasArg()
            .withDescription("directory containing input .ply files").create("plyPath");
    Option boundingbox = OptionBuilder.withArgName("string").hasArg()
            .withDescription("bounding box in WKT notation").create("boundingbox");
    Option outputPlyFile = OptionBuilder.withArgName("file").hasArg().withDescription("output PLY file name")
            .create("outputPlyFile");
    options.addOption(plyPath);//from   ww w . j a  v a  2s .com
    options.addOption(boundingbox);
    options.addOption(outputPlyFile);

    String plydir = ".";
    String boundingboxstr = "";
    String outputfilename = "";

    CommandLineParser parser = new DefaultParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        boundingboxstr = line.getOptionValue("boundingbox");
        outputfilename = line.getOptionValue("outputPlyFile");

        if (line.hasOption("plyPath")) {
            // print the value of block-size
            plydir = line.getOptionValue("plyPath");
            System.out.println("Using plyPath=" + plydir);
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("PlyBounder", options);
        }
        //System.out.println( "plyPath=" + line.getOptionValue( "plyPath" ) );
    } catch (ParseException exp) {
        System.err.println("Error getting arguments: " + exp.getMessage());
    }

    // input directory
    // Get list of files
    File dir = new File(plydir);

    //System.out.println("Getting all files in " + dir.getCanonicalPath());
    List<File> files = (List<File>) FileUtils.listFiles(dir, new String[] { "ply", "PLY" }, false);
    for (File file : files) {
        try {
            System.out.println("file=" + file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String sometempfile = "magweg.wkt";
    String s = null;

    // Loop through .ply files in directory
    for (File file : files) {
        try {
            String cmdl[] = { "./ply-tool.py", "intersection", file.getCanonicalPath(), boundingboxstr,
                    sometempfile };
            //System.out.println("Running: " + Arrays.toString(cmdl));
            Process p = Runtime.getRuntime().exec(cmdl);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("cmdout:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // read any errors from the attempted command
            System.out.println("cmderr:\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Write new .ply file
    //ply-tool write setfile outputPlyFile
    try {
        String cmdl = "./ply-tool.py write " + sometempfile + " " + outputfilename;
        System.out.println("Running: " + cmdl);
        Process p = Runtime.getRuntime().exec(cmdl);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("cmdout:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("cmderr:\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Done
    System.out.println("Done");
}