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.oberasoftware.robo.container.ServiceContainer.java

public static void main(String[] args) {
    LOG.info("Starting Robot Service Application container");

    SpringApplication springApplication = new SpringApplication(ServiceContainer.class);
    ConfigurableApplicationContext context = springApplication.run(args);

    Robot robot = new SpringAwareRobotBuilder("max", context).motionEngine(RoboPlusMotionEngine.class,
            //                        new RoboPlusClassPathResource("/bio_prm_humanoidtypea_en.mtn")
            new JsonMotionResource("/basic-animations.json"))
            //"/dev/ttyACM0
            //"/dev/tty.usbmodem1411
            .servoDriver(DynamixelServoDriver.class,
                    ImmutableMap.<String, String>builder()
                            .put(DynamixelServoDriver.PORT, "/dev/tty.usbmodem1431").build())
            .sensor(new ServoSensor("Test", "6"), ServoSensorDriver.class)
            .sensor(new ServoSensor("Hand", "5"), ServoSensorDriver.class)
            .sensor(new ServoSensor("HandYaw", "2"), ServoSensorDriver.class)
            .sensor(new ServoSensor("Walk", "17"), ServoSensorDriver.class)
            .sensor(new ServoSensor("WalkDirection", "13"), ServoSensorDriver.class)
            //                .sensor(new DistanceSensor("distance", "A0"), ADS1115Driver.class)
            //                .sensor(new GyroSensor("gyro", adsDriver.getPort("A2"), adsDriver.getPort("A3"), new AnalogToPercentageConverter()))
            .remote(RemoteCloudDriver.class).build();

    RobotEventHandler eventHandler = new RobotEventHandler(robot);
    robot.listen(eventHandler);/*from   ww  w .java 2  s. c  om*/

    //        robot.getMotionEngine().runMotion("ArmInit");

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOG.info("Killing the robot gracefully on shutdown");
        robot.shutdown();
    }));
}

From source file:copi.ScalaEntryPoint.java

public static void main(String[] args) {
    /*/* ww w. ja v a  2s .  co  m*/
       * Set lwjgl library path so that LWJGL finds the natives depending on
       * the OS.
       */
    File libDir = new File(path);

    if (!libDir.exists()) {
        // create native lib folder 
        libDir.mkdir();

        // retrieve os type
        String osName = System.getProperty("os.name");

        // try to determine if the system is 64 bit  
        boolean is64bit = false;
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }

        // construct name of native lib file 
        String natLibLWJGL = "";
        if (osName.startsWith("Windows")) {
            natLibLWJGL += "lwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".dll";
        } else if (osName.startsWith("Linux")) {
            natLibLWJGL += "liblwjgl";
            if (is64bit)
                natLibLWJGL += "64";
            natLibLWJGL += ".so";
        } else if (osName.startsWith("Mac OS X")) {
            natLibLWJGL += "liblwjgl";
            natLibLWJGL += ".jnilib";
        } else {
            System.out.println("Unsupported OS: " + osName + ". Exiting.");
            System.exit(-1);
        }

        // try to establish an input stream on the native lib inside the jar
        InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL);
        if (fis == null) {
            System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR.");
            System.exit(-1);
        }

        // establish an output stream on the target file 
        File fOut = new File(path + "/" + natLibLWJGL);
        try (FileOutputStream fos = new FileOutputStream(fOut)) {
            // create file at destination if not already existing
            if (!fOut.exists())
                fOut.createNewFile();

            // making buffer for copy operation 
            byte[] buffer = new byte[1024];
            int readBytes;

            // Open output stream and copy data between source file in JAR and the temporary file
            try {
                while ((readBytes = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, readBytes);
                }
            } finally {
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

        // register shutdown hook
        JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
        Runtime.getRuntime().addShutdownHook(jvmShutdownHook);

    }

    // set lwjgl native library path
    System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath());

    // start COPI
    System.out.println("Starting COPI ...");
    (new SICApplicationLogic()).render();
}

From source file:com.linkedin.pinot.server.starter.SingleNodeServerStarter.java

public static void main(String[] args) throws Exception {
    //Process Command Line to get config and port
    processCommandLineArgs(args);/*ww  w  .jav a  2s.c  o m*/

    LOGGER.info("Trying to create a new ServerInstance!");
    _serverInstance = new ServerInstance();
    LOGGER.info("Trying to initial ServerInstance!");
    _serverInstance.init(_serverConf, new MetricsRegistry());
    LOGGER.info("Trying to start ServerInstance!");
    _serverInstance.start();

    LOGGER.info("Adding ShutdownHook!");
    final ShutdownHook shutdownHook = new ShutdownHook(_serverInstance);
    Runtime.getRuntime().addShutdownHook(shutdownHook);
}

From source file:com.l2jserver.model.template.SkillTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("data/templates");
    final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class);
    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);

    System.out.println("Generating template XML files...");
    c.generateSchema(new SchemaOutputResolver() {
        @Override/*from  w  w  w  .  j  a va 2 s.  c  om*/
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
            return new StreamResult(new File(target, suggestedFileName));
        }
    });

    try {
        final Unmarshaller u = c.createUnmarshaller();
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill");
        m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd");

        Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" },
                true);
        for (final File legacyFile : files) {
            LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile);
            for (final LegacySkill legacySkill : list.skills) {
                SkillTemplate t = fillSkill(legacySkill);
                final File file = new File(target, "skill/" + t.id.getID()
                        + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml");
                templates.add(t);

                try {
                    m.marshal(t, getXMLSerializer(new FileOutputStream(file)));
                } catch (MarshalException e) {
                    System.err.println(
                            "Could not generate XML template file for " + t.getName() + " - " + t.getID());
                    file.delete();
                }
            }
        }

        System.out.println("Generated " + templates.size() + " templates");

        System.gc();
        System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));
        System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));
        System.out.println("Used: " + FileUtils.byteCountToDisplaySize(
                Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
    } finally {
        conn.close();
    }
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *///from  ww  w  .j ava 2 s. c  o  m
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:de.cosmocode.palava.core.Main.java

/**
 * Application entry point.//ww  w  . jav  a2  s  .  c om
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    AsciiArt.print();

    final Main main;

    try {
        main = new Main(args);
        /* CHECKSTYLE:OFF */
    } catch (RuntimeException e) {
        /* CHECKSTYLE:ON */
        LOG.error("configuration error", e);
        printToStdErr(e);
        System.exit(1);
        throw e;
    }

    main.start();

    LOG.debug("Adding shutdown hook");
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            main.stop();
            synchronized (main) {
                main.notify();
            }
        }

    }));

    main.waitIfNecessary();
    System.exit(0);
}

From source file:org.sonews.Application.java

/**
 * The main entrypoint./*from   ww w  .  j  a  v a 2  s.co m*/
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    System.out.println(VERSION);
    Thread.currentThread().setName("Mainthread");

    // Command line arguments
    boolean async = false;
    boolean feed = false; // Enable feeding?
    boolean purger = false; // Enable message purging?
    int port = -1;

    for (int n = 0; n < args.length; n++) {
        switch (args[n]) {
        case "-async": {
            async = true;
            break;
        }
        case "-c":
        case "-config": {
            Config.inst().set(Config.LEVEL_CLI, Config.CONFIGFILE, args[++n]);
            System.out.println("Using config file " + args[n]);
            break;
        }
        case "-C":
        case "-context": {
            // FIXME: Additional context files
            n++;
            break;
        }
        case "-dumpjdbcdriver": {
            System.out.println("Available JDBC drivers:");
            Enumeration<Driver> drvs = DriverManager.getDrivers();
            while (drvs.hasMoreElements()) {
                System.out.println(drvs.nextElement());
            }
            return;
        }
        case "-feed": {
            feed = true;
            break;
        }
        case "-h":
        case "-help": {
            printArguments();
            return;
        }
        case "-p": {
            port = Integer.parseInt(args[++n]);
            break;
        }
        case "-plugin-storage": {
            System.out.println("Warning: -plugin-storage is not implemented!");
            break;
        }
        case "-purger": {
            purger = true;
            break;
        }
        case "-v":
        case "-version":
            // Simply return as the version info is already printed above
            return;
        }
    }

    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    context = new FileSystemXmlApplicationContext(new String[] { "sonews.xml" }, context);

    // Enable storage backend
    StorageProvider sprov = context.getBean("storageProvider", StorageProvider.class);
    StorageManager.enableProvider(sprov);

    ChannelLineBuffers.allocateDirect();

    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    // Start the listening daemon
    if (port <= 0) {
        port = Config.inst().get(Config.PORT, 119);
    }

    NNTPDaemon daemon = context.getBean(NNTPDaemon.class);
    daemon.setPort(port);
    daemon.start();

    // Start Connections purger thread...
    Connections.getInstance().start();

    // Start feeds
    if (feed) {
        FeedManager.startFeeding();
    }

    if (purger) {
        Purger purgerDaemon = new Purger();
        purgerDaemon.start();
    }

    // Wait for main thread to exit (setDaemon(false))
    daemon.join();
}

From source file:edu.cmu.cs.lti.ark.fn.identification.latentmodel.TrainBatchModelDerThreaded.java

public static void main(String[] args) throws Exception {
    final FNModelOptions options = new FNModelOptions(args);
    LogManager.getLogManager().reset();
    final FileHandler fh = new FileHandler(options.logOutputFile.get(), true);
    fh.setFormatter(new SimpleFormatter());
    logger.addHandler(fh);//from w w w. java2  s . c  o m

    final String restartFile = options.restartFile.get();
    final int numThreads = options.numThreads.present() ? options.numThreads.get()
            : Runtime.getRuntime().availableProcessors();
    final TrainBatchModelDerThreaded tbm = new TrainBatchModelDerThreaded(options.alphabetFile.get(),
            options.eventsFile.get(), options.modelFile.get(), options.reg.get(), options.lambda.get(),
            restartFile.equals("null") ? Optional.<String>absent() : Optional.of(restartFile), numThreads);
    tbm.trainModel();
}

From source file:com.sina.dip.twill.HelloWorldClassDependent.java

public static void main(String[] args) {
    String zkStr = "localhost:2181";

    YarnConfiguration yarnConfiguration = new YarnConfiguration();

    final TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfiguration, zkStr);

    twillRunner.start();/*from  w w w . ja v a2s .co  m*/

    String yarnClasspath = yarnConfiguration.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
            "/usr/lib/hadoop/*,/usr/lib/hadoop-0.20-mapreduce/*,/usr/lib/hadoop-hdfs/*,/usr/lib/hadoop-mapreduce/*,/usr/lib/hadoop-yarn/*");

    List<String> applicationClassPaths = Lists.newArrayList();

    Iterables.addAll(applicationClassPaths, Splitter.on(",").split(yarnClasspath));

    final TwillController controller = twillRunner.prepare(new HelloWorldApplication())
            .withApplicationClassPaths(applicationClassPaths)
            .withBundlerClassAcceptor(new HadoopClassExcluder()).start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                Futures.getUnchecked(controller.terminate());
            } finally {
                twillRunner.stop();
            }
        }
    });

    try {
        controller.awaitTerminated();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

From source file:fredboat.FredBoat.java

public static void main(String[] args)
        throws LoginException, IllegalArgumentException, InterruptedException, IOException, UnirestException {
    Runtime.getRuntime().addShutdownHook(new Thread(ON_SHUTDOWN));

    log.info("\n\n" + "  ______            _ ____              _   \n"
            + " |  ____|          | |  _ \\            | |  \n"
            + " | |__ _ __ ___  __| | |_) | ___   __ _| |_ \n"
            + " |  __| '__/ _ \\/ _` |  _ < / _ \\ / _` | __|\n"
            + " | |  | | |  __/ (_| | |_) | (_) | (_| | |_ \n"
            + " |_|  |_|  \\___|\\__,_|____/ \\___/ \\__,_|\\__|\n\n");

    I18n.start();/*from  w ww . ja  v a 2  s.  c o m*/

    //Attach log adapter
    SimpleLog.addListener(new SimpleLogToSLF4JAdapter());

    //Make JDA not print to console, we have Logback for that
    SimpleLog.LEVEL = SimpleLog.Level.OFF;

    int scope;
    try {
        scope = Integer.parseInt(args[0]);
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) {
        log.info("Invalid scope, defaulting to scopes 0x111");
        scope = 0x111;
    }

    log.info("Starting with scopes:" + "\n\tMain: " + ((scope & 0x100) == 0x100) + "\n\tMusic: "
            + ((scope & 0x010) == 0x010) + "\n\tSelf: " + ((scope & 0x001) == 0x001));

    log.info("JDA version:\t" + JDAInfo.VERSION);

    Config.loadDefaultConfig(scope);

    try {
        API.start();
    } catch (Exception e) {
        log.info("Failed to ignite Spark, FredBoat API unavailable", e);
    }
    try {
        if (!Config.CONFIG.getJdbcUrl().equals("") && !Config.CONFIG.getOauthSecret().equals("")) {
            DatabaseManager.startup(Config.CONFIG.getJdbcUrl(), null, Config.CONFIG.getHikariPoolSize());
            OAuthManager.start(Config.CONFIG.getBotToken(), Config.CONFIG.getOauthSecret());
        } else {
            log.warn("No JDBC URL and/or secret found, skipped database connection and OAuth2 client");
            log.warn("Falling back to internal SQLite db");
            DatabaseManager.startup("jdbc:sqlite:fredboat.db", "org.hibernate.dialect.SQLiteDialect",
                    Config.CONFIG.getHikariPoolSize());
        }
    } catch (Exception e) {
        log.info("Failed to start DatabaseManager and OAuth2 client", e);
    }

    //Initialise event listeners
    listenerBot = new EventListenerBoat();
    listenerSelf = new EventListenerSelf();

    //Commands
    if (Config.CONFIG.getDistribution() == DistributionEnum.DEVELOPMENT
            || Config.CONFIG.getDistribution() == DistributionEnum.MAIN)
        MainCommandInitializer.initCommands();

    if (Config.CONFIG.getDistribution() == DistributionEnum.DEVELOPMENT
            || Config.CONFIG.getDistribution() == DistributionEnum.MUSIC
            || Config.CONFIG.getDistribution() == DistributionEnum.PATRON)
        MusicCommandInitializer.initCommands();

    log.info("Loaded commands, registry size is " + CommandRegistry.getSize());

    //Check MAL creds
    executor.submit(FredBoat::hasValidMALLogin);

    //Check imgur creds
    executor.submit(FredBoat::hasValidImgurCredentials);

    //Initialise JCA
    executor.submit(FredBoat::loadJCA);

    /* Init JDA */

    if ((Config.CONFIG.getScope() & 0x110) != 0) {
        initBotShards(listenerBot);
    }

    if ((Config.CONFIG.getScope() & 0x001) != 0) {
        log.error("Selfbot support has been removed.");
        //fbClient = new FredBoatClient();
    }

    if (Config.CONFIG.getDistribution() == DistributionEnum.MUSIC && Config.CONFIG.getCarbonKey() != null) {
        CarbonitexAgent carbonitexAgent = new CarbonitexAgent(Config.CONFIG.getCarbonKey());
        carbonitexAgent.setDaemon(true);
        carbonitexAgent.start();
    }

    ShardWatchdogAgent shardWatchdogAgent = new ShardWatchdogAgent();
    shardWatchdogAgent.setDaemon(true);
    shardWatchdogAgent.start();
}