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:fr.inria.atlanmod.kyanos.benchmarks.XmiCreator.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);//from w w  w .  j a v a 2 s .co  m
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createFileURI(commandLine.getOptionValue(OUT));

        Class<?> inClazz = XmiCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:de.escidoc.core.admin.AdminMain.java

/**
 * Main Method, depends on args[0] which method is executed.
 * /*  ww w . jav  a 2s .  c  o  m*/
 * @param args
 *            arguments given on commandline
 * @throws NoSuchMethodException
 *             e
 * @throws InvocationTargetException
 *             e
 * @throws IllegalAccessException
 *             e
 */
public static void main(final String[] args) {
    int result = 20;

    try {
        AdminMain admin = new AdminMain();

        // call has to have at least one argument
        if (args.length > 0 && !StringUtils.isEmpty(args[0])) {
            String methodToCall = methods.get(args[0]);

            if (!StringUtils.isEmpty(methodToCall)) {
                log.info("memory (free / max. available): " + Runtime.getRuntime().freeMemory() / 1024 / 1024
                        + " MB" + " / " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB");

                Class<?>[] paramTypes = { String[].class };
                Method thisMethod = admin.getClass().getDeclaredMethod(methodToCall, paramTypes);

                thisMethod.invoke(admin, new Object[] { args });
                result = 0;
            } else {
                admin.failMessage("provided tool name: " + StringUtils.join(args, " "));
            }
        } else {
            admin.failMessage();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
    }
    System.exit(result);
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

public static void main(String[] args) {
    Common.getInstance().setAppName("awsVpnLauncher");
    FOKLogger.enableLoggingOfUncaughtExceptions();
    prefs = new Preferences(Main.class.getName());

    // enable the shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();//  w w  w. j a v  a 2s. c o  m
            }
        }
    }));

    UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> {
        if (oldVersion != null) {
            FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName()
                    + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion());
        }
    });
    List<String> argsAsList = new ArrayList<>(Arrays.asList(args));

    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockAppVersion(version);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockBuildNumber(buildnumber);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockPackaging(packaging);
            argsAsList.remove(arg);
        }
    }

    args = argsAsList.toArray(new String[0]);

    try {
        mvnRepoConfig = new Config(
                new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"),
                Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true);
        projectConfig = new Config(
                new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"),
                Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true);
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e);
    }

    try {
        installUpdates(args);
    } catch (Exception e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e);
    }

    if (args.length == 0) {
        // not enough arguments
        printHelpMessage();
        throw new NotEnoughArgumentsException();
    }

    switch (args[0].toLowerCase()) {
    case "setup":
        setup();
        break;
    case "launch":
        initAWSConnection();
        launch();
        break;
    case "terminate":
        initAWSConnection();
        terminate();
        break;
    case "config":
        // require a second arg
        if (args.length == 2) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        config(Property.valueOf(args[1]), args[2]);
        break;
    case "getconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        getConfig(Property.valueOf(args[1]));
        break;
    case "printconfig":
        printConfig();
        break;
    case "deleteconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        deleteConfig(Property.valueOf(args[1]));
        break;
    case "ssh":
        String sshInstanceId;
        if (args.length == 2) {
            // a instanceID is specified
            sshInstanceId = args[1];
        } else {
            String instanceIdsPrefValue = prefs.getPreference("instanceIDs", "");
            if (instanceIdsPrefValue.equals("")) {
                throw new NotEnoughArgumentsException(
                        "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter.");
            }

            List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";"));
            if (instanceIds.size() == 1) {
                // exactly one instance found
                sshInstanceId = instanceIds.get(0);
            } else {
                FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:");

                for (String instanceId : instanceIds) {
                    FOKLogger.severe(Main.class.getName(), instanceId);
                }
                throw new NotEnoughArgumentsException(
                        "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter.");
            }
        }

        initAWSConnection();
        ssh(sshInstanceId);
        break;
    default:
        printHelpMessage();
    }
}

From source file:com.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {//from  w ww.  j  ava  2  s.com
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}

From source file:io.adeptj.runtime.core.Launcher.java

/**
 * Entry point for initializing the AdeptJ Runtime.
 * <p>//from  w  ww . j a  v a  2 s.c om
 * It does the following tasks in order.
 * <p>
 * 1. Initializes the Logback logging framework.
 * 2. Does the deployment to embedded UNDERTOW.
 * 3. Starts the OSGi Framework.
 * 4. Starts the Undertow server.
 * 5. Registers the runtime ShutdownHook.
 *
 * @param args command line arguments for the Launcher.
 */
public static void main(String[] args) {
    Thread.currentThread().setName("AdeptJ Launcher");
    long startTime = System.nanoTime();
    LogbackInitializer.init();
    Logger logger = LoggerFactory.getLogger(Launcher.class);
    try {
        pauseForDebug();
        logger.info("JRE: [{}], Version: [{}]", JAVA_RUNTIME_NAME, JAVA_RUNTIME_VERSION);
        Map<String, String> commands = parseArgs(args);
        Lifecycle lifecycle = new Server();
        lifecycle.start();
        Runtime.getRuntime().addShutdownHook(new ShutdownHook(lifecycle, SERVER_STOP_THREAD_NAME));
        launchBrowser(commands);
        logger.info("AdeptJ Runtime initialized in [{}] ms!!", Times.elapsedMillis(startTime));
    } catch (Throwable th) { // NOSONAR
        logger.error("Exception while initializing AdeptJ Runtime!!", th);
        shutdownJvm(th);
    }
}

From source file:playground.app.Application.java

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

    HttpHandler httpHandler = createHttpHandler();

    HttpServer server = new TomcatHttpServer();
    server.setPort(8080);//from ww w.j  av  a2  s . c  o m
    server.setHandler(httpHandler);
    server.afterPropertiesSet();
    server.start();

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

From source file:edu.cmu.cs.lti.ark.fn.identification.training.AlphabetCreationThreaded.java

/**
 * Parses commandline args, then creates a new {@link #AlphabetCreationThreaded} with them
 * and calls {@link #createAlphabet}/*from w w  w  .j  ava 2s . c  om*/
 *
 * @param args commandline arguments. see {@link #AlphabetCreationThreaded}
 *             for details.
 */
public static void main(String[] args)
        throws IOException, ClassNotFoundException, ExecutionException, InterruptedException {
    final FNModelOptions options = new FNModelOptions(args);

    LogManager.getLogManager().reset();
    final FileHandler fileHandler = new FileHandler(options.logOutputFile.get(), true);
    fileHandler.setFormatter(new SimpleFormatter());
    logger.addHandler(fileHandler);

    final int startIndex = options.startIndex.get();
    final int endIndex = options.endIndex.get();
    logger.info("Start:" + startIndex + " end:" + endIndex);
    final RequiredDataForFrameIdentification r = SerializedObjects.readObject(options.fnIdReqDataFile.get());

    final int minimumCount = options.minimumCount.present() ? options.minimumCount.get()
            : DEFAULT_MINIMUM_FEATURE_COUNT;
    final int numThreads = options.numThreads.present() ? options.numThreads.get()
            : Runtime.getRuntime().availableProcessors();
    final File alphabetDir = new File(options.modelFile.get());
    final String featureExtractorType = options.idFeatureExtractorType.present()
            ? options.idFeatureExtractorType.get()
            : "basic";
    final IdFeatureExtractor featureExtractor = IdFeatureExtractor.fromName(featureExtractorType);
    final AlphabetCreationThreaded events = new AlphabetCreationThreaded(options.trainFrameElementFile.get(),
            options.trainParseFile.get(), r.getFrameMap().keySet(), featureExtractor, startIndex, endIndex,
            numThreads);
    final Multiset<String> unconjoinedFeatures = events.createAlphabet();
    final File alphabetFile = new File(alphabetDir, ALPHABET_FILENAME);
    events.conjoinAndWriteAlphabet(unconjoinedFeatures, minimumCount, alphabetFile);
}

From source file:eu.interedition.collatex.http.Server.java

public static void main(String... args) {
    try {//  w  w w.  j a va 2 s  .c om
        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);
        if (commandLine.hasOption("h")) {
            new HelpFormatter().printHelp("collatex-server [<options> ...]\n", OPTIONS);
            return;
        }

        final Collator collator = new Collator(Integer.parseInt(commandLine.getOptionValue("mpc", "2")),
                Integer.parseInt(commandLine.getOptionValue("mcs", "0")),
                commandLine.getOptionValue("dot", null));
        final String staticPath = System.getProperty("collatex.static.path", "");
        final HttpHandler httpHandler = staticPath.isEmpty()
                ? new CLStaticHttpHandler(Server.class.getClassLoader(), "/static/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                }
                : new StaticHttpHandler(staticPath.replaceAll("/+$", "") + "/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                };

        final NetworkListener httpListener = new NetworkListener("http", "0.0.0.0",
                Integer.parseInt(commandLine.getOptionValue("p", "7369")));

        final CompressionConfig compressionConfig = httpListener.getCompressionConfig();
        compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
        compressionConfig.setCompressionMinSize(860); // http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
        compressionConfig.setCompressableMimeTypes("application/javascript", "application/json",
                "application/xml", "text/css", "text/html", "text/javascript", "text/plain", "text/xml");

        final HttpServer httpServer = new HttpServer();
        httpServer.addListener(httpListener);
        httpServer.getServerConfiguration().addHttpHandler(httpHandler,
                commandLine.getOptionValue("cp", "").replaceAll("/+$", "") + "/*");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("Stopping HTTP server");
            }
            httpServer.shutdown();
        }));

        httpServer.start();

        Thread.sleep(Long.MAX_VALUE);
    } catch (Throwable t) {
        LOG.log(Level.SEVERE, "Error while parsing command line", t);
        System.exit(1);
    }
}

From source file:ai.grakn.engine.GraknEngineServer.java

public static void main(String[] args) {
    GraknEngineConfig prop = GraknEngineConfig.create();
    // Start Engine
    GraknEngineServer server = start(prop);

    // close GraknEngineServer on SIGTERM
    Thread closeThread = new Thread(server::close, "GraknEngineServer-shutdown");
    Runtime.getRuntime().addShutdownHook(closeThread);
}

From source file:com.twitter.distributedlog.messaging.ConsoleProxyPartitionedMultiWriter.java

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;/* w w  w .j a va  2 s.co 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, ',');
    PartitionedWriter<Integer, String> partitionedWriter = new PartitionedWriter<Integer, String>(
            streamNameList, new IntPartitioner(), client);

    // Setup Terminal
    Terminal terminal = Terminal.setupTerminal();
    ConsoleReader reader = new ConsoleReader();
    String line;
    while ((line = reader.readLine(PROMPT_MESSAGE)) != null) {
        String[] parts = StringUtils.split(line, ':');
        if (parts.length != 2) {
            System.out.println("Invalid input. Needs 'KEY:VALUE'");
            continue;
        }
        int key;
        try {
            key = Integer.parseInt(parts[0]);
        } catch (NumberFormatException nfe) {
            System.out.println("Invalid input. Needs 'KEY:VALUE'");
            continue;
        }
        String value = parts[1];

        partitionedWriter.write(key, value).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();
}