List of usage examples for java.lang Runtime getRuntime
public static Runtime getRuntime()
From source file:org.echocat.nodoodle.server.Main.java
public static void main(String[] args) { final File log4jConfig = new File(System.getProperty("log4j.configuration", "../config/log4j.xml")); if (log4jConfig.isFile()) { try {//from www . j a v a2 s.co m final FileReader reader = new FileReader(log4jConfig); try { final DOMConfigurator domConfigurator = new DOMConfigurator(); domConfigurator.doConfigure(reader, getLoggerRepository()); } finally { IOUtils.closeQuietly(reader); } } catch (Exception e) { throw new RuntimeException("Could not configure log4j with " + log4jConfig + ".", e); } } final String applicationName = getApplicationName(); //System.setSecurityManager(new ServerSecurityManager()); LOG.info("Starting " + applicationName + "..."); final File config = new File( System.getProperty(Main.class.getPackage().getName() + ".config", "../config/nodoodleServer.xml")); final AbstractApplicationContext applicationContext = new FileSystemXmlApplicationContext(config.getPath()); LOG.info("Starting " + applicationName + "... DONE!"); Runtime.getRuntime().addShutdownHook(new Thread("destroyer") { @Override public void run() { LOG.info("Stopping " + applicationName + "..."); applicationContext.stop(); LOG.info("Stopping " + applicationName + "... DONE!"); } }); }
From source file:ca.uqac.info.trace.TraceGenerator.java
public static void main(String[] args) { // Parse command line arguments Options options = setupOptions();//w w w.j a v a 2 s . c o m CommandLine c_line = setupCommandLine(args, options); int verbosity = 0, max_events = 1000000; if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } String generator_name = "simplerandom"; if (c_line.hasOption("g")) { generator_name = c_line.getOptionValue("generator"); } long time_per_msg = 1000; if (c_line.hasOption("i")) { time_per_msg = Integer.parseInt(c_line.getOptionValue("i")); } if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (c_line.hasOption("e")) { max_events = Integer.parseInt(c_line.getOptionValue("e")); } String feeder_params = ""; if (c_line.hasOption("parameters")) { feeder_params = c_line.getOptionValue("parameters"); } MessageFeeder mf = instantiateFeeder(generator_name, feeder_params); if (mf == null) { System.err.println("Unrecognized feeder name"); System.exit(ERR_ARGUMENTS); } // Trap Ctrl-C to send EOT before shutting down Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { char EOT = 4; System.out.print(EOT); } }); for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) { long time_begin = System.nanoTime(); String message = mf.next(); StringBuilder out = new StringBuilder(); out.append(message); System.out.print(out.toString()); long time_end = System.nanoTime(); long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f); if (duration > 0) { try { Thread.sleep(duration); } catch (InterruptedException e) { } } if (verbosity > 0) { System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg); } } }
From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java
public static void main(final String[] args) throws Exception { printRuntimeInfo();/*ww w. j ava 2 s . co m*/ final long start = System.currentTimeMillis(); LOG.info("To run in test mode set system parameter {}=true", BaukEngineConfigurationConstants.IDEMPOTENT_FEED_PROCESSING_PARAM_NAME); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); final BaukConfiguration conf = findConfiguration(); if (conf != null) { ConfigurationProperties.setBaukProperties(conf.getProperties()); final ConfigurationValidator configValidator = new ConfigurationValidator(conf); try { configValidator.validate(); } catch (final Exception exc) { BaukUtil.logEngineMessageSync("Error while validating configuration: " + exc.getMessage()); LOG.error("", exc); System.exit(-1); } remotingHandler = new RemotingServer(); remotingHandler.start(); createProcessingRoutes(conf); final boolean throughputTestingMode = ConfigurationProperties .getSystemProperty(BaukEngineConfigurationConstants.THROUGHPUT_TESTING_MODE_PARAM_NAME, false); if (throughputTestingMode) { BaukUtil.logEngineMessageSync( "ENGINE IS RUNNING IN THROUGHPUT TESTING MODE! ONE INPUT FEED FILE PER THREAD WILL BE CACHED AND PROCESSED REPEATEDLY!!!"); } instanceStartTime = System.currentTimeMillis(); final boolean isMultiInstance = ConfigurationProperties.isConfiguredPartitionedMultipleInstances(); if (isMultiInstance) { final int totalPartitionsCount = ConfigurationProperties.getSystemProperty( BaukEngineConfigurationConstants.MULTI_INSTANCE_PARTITION_COUNT_PARAM_NAME, -1); final String myUniqueIdentifier = ConfigurationProperties.getBaukInstanceIdentifier(); BaukUtil.logEngineMessageSync("Configured to run in multi-instance mode of " + totalPartitionsCount + " instances in total. My unique identifier is " + myUniqueIdentifier); } BaukUtil.logEngineMessageSync("Finished initialization! Started counting uptime"); startProcessing(); final long total = System.currentTimeMillis() - start; final long totalSec = total / 1000; final boolean detectBaukInstances = ConfigurationProperties .getSystemProperty(BaukEngineConfigurationConstants.DETECT_OTHER_BAUK_INSTANCES, false); if (detectBaukInstances) { final int numberOfInstances = HazelcastCacheInstanceManager.getNumberOfBaukInstances(); BaukUtil.logEngineMessage( "Total number of detected running engine instances is " + numberOfInstances); } BaukUtil.logEngineMessage("Engine started successfully in " + total + "ms (" + totalSec + " seconds). Waiting for feed files...\n\n"); } else { LOG.error( "Unable to find valid configuration file! Check your startup scripts and make sure system property {} points to valid feed configuration file. Aborting!", CONFIG_FILE_PROP_NAME); BaukUtil.logEngineMessage( "Unable to find valid configuration file! Check your startup scripts and make sure system property " + CONFIG_FILE_PROP_NAME + " points to valid feed configuration file. Aborting!"); System.exit(-1); } // sleep forever while (!BaukUtil.shutdownStarted()) { Thread.sleep(10000); } }
From source file:fr.ericlab.mabed.app.Main.java
public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); Configuration configuration = new Configuration(); Corpus corpus = new Corpus(configuration); System.out.println("MABED: Mention-Anomaly-Based Event Detection"); if (args.length == 0 || args[0].equals("-help")) { System.out.println("For more information on how to run MABED, see the README.txt file"); } else {//from ww w .j a va 2 s . com if (args[0].equals("-run")) { try { if (configuration.numberOfThreads > 1) { System.out.println("Running the parallelized implementation with " + configuration.numberOfThreads + " threads (this computer has " + Runtime.getRuntime().availableProcessors() + " available threads)"); } else { System.out.println("Running the centralized implementation"); } corpus.loadCorpus(configuration.numberOfThreads > 1); String output = "MABED: Mention-Anomaly-Based Event Detection\n" + corpus.output + "\n"; System.out.println("-------------------------\n" + Util.getDate() + " MABED is running\n-------------------------"); output += "-------------------------\n" + Util.getDate() + " MABED is running\n-------------------------\n"; System.out.println(Util.getDate() + " Reading parameters:\n - k = " + configuration.k + ", p = " + configuration.p + ", theta = " + configuration.theta + ", sigma = " + configuration.sigma); MABED mabed = new MABED(); if (configuration.numberOfThreads > 1) { output += mabed.applyParallelized(corpus, configuration); } else { output += mabed.applyCentralized(corpus, configuration); } System.out.println( "--------------------\n" + Util.getDate() + " MABED ended\n--------------------"); output += "--------------------\n" + Util.getDate() + " MABED ended\n--------------------\n"; File outputDir = new File("output"); if (!outputDir.isDirectory()) { outputDir.mkdir(); } File textFile = new File("output/MABED.tex"); FileUtils.writeStringToFile(textFile, mabed.events.toLatex(corpus), false); textFile = new File("output/MABED.log"); FileUtils.writeStringToFile(textFile, output, false); mabed.events.printLatex(corpus); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("Unknown option '" + args[0] + "'\nType 'java -jar MABED.jar -help' for more information on how to run MABED"); } } }
From source file:com.apipulse.bastion.Main.java
public static void main(String[] args) throws IOException, ClassNotFoundException { log.info("Bastion starting. Loading chains"); final File dir = new File("etc/chains"); final LinkedList<ActorRef> chains = new LinkedList<ActorRef>(); for (File file : dir.listFiles()) { if (!file.getName().startsWith(".") && file.getName().endsWith(".yaml")) { log.info("Loading chain: " + file.getName()); ChainConfig config = new ChainConfig(IOUtils.toString(new FileReader(file))); ActorRef ref = BastionActors.getInstance().initChain(config.getName(), Class.forName(config.getQualifiedClass())); Iterator<StageConfig> iterator = config.getStages().iterator(); while (iterator.hasNext()) ref.tell(iterator.next(), null); chains.add(ref);//www.j a v a 2s. co m } } SpringApplication app = new SpringApplication(); HashSet<Object> objects = new HashSet<Object>(); objects.add(ApiController.class); final ConfigurableApplicationContext context = app.run(ApiController.class, args); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { log.info("Bastion shutting down"); Iterator<ActorRef> iterator = chains.iterator(); while (iterator.hasNext()) iterator.next().tell(new StopMessage(), null); Thread.sleep(2000); context.stop(); log.info("Bastion shutdown complete"); } catch (Exception e) { } } }); }
From source file:com.itmanwuiso.checksums.FileDuplicateChecker.java
public static void main(String[] args) { sync = new Object(); tasks = 0L;//from w w w. ja v a2s . c om if (!setSettings(args)) { System.exit(-1); } int cores = Runtime.getRuntime().availableProcessors(); cores = cores + 1; prepare(cores, storageFile); run(); }
From source file:org.sourcepit.docker.watcher.Main.java
public static void main(String[] args) throws IOException { final HttpClientFactory clientFactory = new HttpClientFactory() { @Override//from w w w .j a v a 2s . c o m public CloseableHttpClient createHttpClient() { return HttpClients.createDefault(); } }; final String dockerDaemonUri = "http://192.168.56.101:2375"; final String consulAgentUri = "http://192.168.56.101:8500"; final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>(); final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(), consulAgentUri); final Thread containerStateDispatcher = new Thread("Consul Forwarder") { @Override public void run() { while (true) { try { consulForwarder.forward(queue.take()); } catch (InterruptedException e) { break; } catch (Exception e) { LOG.error("Error while forwarding Docker container state to Consul.", e); } } } }; containerStateDispatcher.start(); final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) { @Override protected void handle(List<JsonObject> containerState) { queue.add(containerState); } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { watcher.stop(); while (containerStateDispatcher.isAlive()) { containerStateDispatcher.interrupt(); try { Thread.sleep(100L); } catch (InterruptedException e) { } } } }); watcher.start(); }
From source file:davmail.DavGateway.java
/** * Start the gateway, listen on specified smtp and pop3 ports * * @param args command line parameter config file path *///www .j a v a 2 s.c o m public static void main(String[] args) { if (args.length >= 1) { Settings.setConfigFilePath(args[0]); } Settings.load(); DavGatewayTray.init(); start(); // server mode: all threads are daemon threads, do not let main stop if (Settings.getBooleanProperty("davmail.server")) { Runtime.getRuntime().addShutdownHook(new Thread("Shutdown") { @Override public void run() { DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_INTERRUPTED")); DavGateway.stop(); stopped = true; } }); try { while (!stopped) { Thread.sleep(1000); } } catch (InterruptedException e) { DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_INTERRUPTED")); stop(); DavGatewayTray.debug(new BundleMessage("LOG_GATEWAY_STOP")); } } }
From source file:com.twitter.distributedlog.messaging.ConsoleProxyRRMultiWriter.java
public static void main(String[] args) throws Exception { if (2 != args.length) { System.out.println(HELP); return;//ww w .j av a2s . 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, ','); RRMultiWriter<Integer, String> writer = new RRMultiWriter(streamNameList, client); // Setup Terminal Terminal terminal = Terminal.setupTerminal(); ConsoleReader reader = new ConsoleReader(); String line; while ((line = reader.readLine(PROMPT_MESSAGE)) != null) { writer.write(line).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 } }); } client.close(); }
From source file:com.ok2c.lightmtp.examples.LocalMailServerTransportExample.java
public static void main(final String[] args) throws Exception { File workingDir = new File("."); IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); final MailServerTransport mta = new LocalMailServerTransport(workingDir, config); InetSocketAddress sockaddress = new InetSocketAddress("localhost", 2525); InetAddressRange iprange = new InetAddressRange(InetAddress.getByName("127.0.0.0"), 8); mta.start(new DefaultIdGenerator(), new MyRemoteAddressValidator(iprange), new MyEnvelopValidator(), new MyDeliveryHandler()); mta.listen(sockaddress);// ww w . j a va2s . c o m System.out.println("LMTP server listening on " + sockaddress); Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread() { @Override public void run() { try { mta.shutdown(); } catch (IOException ex) { mta.forceShutdown(); } } }); }