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:org.jfree.chart.demo.PerformanceTest1.java

public static void main(String args[]) {
    ArrayList<Double> arraylist = new ArrayList<Double>();
    for (int i = 0; i < 4000; i++)
        arraylist.add(new Double(Math.random()));

    int j = 0;/*www .ja v a2  s  .c  o m*/
    for (int k = 0; k < 20000; k++) {
        long l = System.currentTimeMillis();
        for (int i1 = 0; i1 < 0xf4240; i1++)
            j += i1;

        long l1 = System.currentTimeMillis();
        System.out.println(k + " --> " + (l1 - l) + " (" + Runtime.getRuntime().freeMemory() + " / "
                + Runtime.getRuntime().totalMemory() + ")");
    }

}

From source file:io.kodokojo.monitor.Launcher.java

public static void main(String[] args) {

    Injector propertyInjector = Guice.createInjector(new CommonsPropertyModule(args), new PropertyModule());
    MicroServiceConfig microServiceConfig = propertyInjector.getInstance(MicroServiceConfig.class);
    LOGGER.info("Starting Kodo Kojo {}.", microServiceConfig.name());
    Injector commonsServicesInjector = propertyInjector.createChildInjector(new UtilityServiceModule(),
            new EventBusModule(), new DatabaseModule(), new SecurityModule(), new CommonsHealthCheckModule());

    Injector marathonInjector = null;/*  w w w  .j a  va  2s.c  om*/
    OrchestratorConfig orchestratorConfig = propertyInjector.getInstance(OrchestratorConfig.class);
    if (MOCK.equals(orchestratorConfig.orchestrator())) {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup() {
                return new BrickStateLookup() {

                    private int cpt = 0;

                    @Override
                    public Set<BrickStateEvent> lookup() {
                        return Collections.singleton(generateBrickStateEvent());
                    }

                    public BrickStateEvent generateBrickStateEvent() {
                        BrickStateEvent.State[] states = BrickStateEvent.State.values();
                        int index = RandomUtils.nextInt(states.length);
                        BrickStateEvent.State state = states[index];

                        return new BrickStateEvent("1234", "build-A", BrickType.CI.name(), "jenkins", state,
                                "1.65Z3.1");
                    }
                };
            }
        });
    } else {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup(MarathonConfig marathonConfig,
                    ProjectFetcher projectFectcher, BrickFactory brickFactory, BrickUrlFactory brickUrlFactory,
                    OkHttpClient httpClient) {
                return new MarathonBrickStateLookup(marathonConfig, projectFectcher, brickFactory,
                        brickUrlFactory, httpClient);
            }

        });
    }

    Injector servicesInjector = marathonInjector.createChildInjector(new ServiceModule());

    ApplicationLifeCycleManager applicationLifeCycleManager = servicesInjector
            .getInstance(ApplicationLifeCycleManager.class);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            super.run();
            LOGGER.info("Stopping services.");
            applicationLifeCycleManager.stop();
            LOGGER.info("All services stopped.");
        }
    });

    EventBus eventBus = servicesInjector.getInstance(EventBus.class);
    eventBus.connect();
    //  Init repository.
    BrickStateLookup brickStateLookup = servicesInjector.getInstance(BrickStateLookup.class);
    BrickStateEventRepository repository = servicesInjector.getInstance(BrickStateEventRepository.class);
    Set<BrickStateEvent> brickStateEvents = brickStateLookup.lookup();
    repository.compareAndUpdate(brickStateEvents);

    HttpHealthCheckEndpoint httpHealthCheckEndpoint = servicesInjector
            .getInstance(HttpHealthCheckEndpoint.class);
    httpHealthCheckEndpoint.start();

    ActorSystem actorSystem = servicesInjector.getInstance(ActorSystem.class);
    ActorRef actorRef = servicesInjector.getInstance(ActorRef.class);
    actorSystem.scheduler().schedule(Duration.Zero(), Duration.create(1, TimeUnit.MINUTES), actorRef, "Tick",
            actorSystem.dispatcher(), ActorRef.noSender());
    LOGGER.info("Kodo Kojo {} started.", microServiceConfig.name());

}

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;//from  www  .  ja va 2 s. c  om
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}

From source file:com.yahoo.pasc.paxos.client.PaxosClient.java

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

    CommandLineParser parser = new PosixParser();
    Options options;//  ww  w . j  a  v a 2  s.  co  m

    {
        Option id = new Option("i", true, "client id");
        Option clients = new Option("c", true, "number of clients");
        Option host = new Option("l", true, "leader (hostname:port)");
        Option servers = new Option("s", true, "number of servers");
        Option quorum = new Option("q", true, "necesarry quorum at the client");
        Option port = new Option("p", true, "port used by client");
        Option buffer = new Option("b", true, "number of concurrent clients");
        Option timeout = new Option("t", true, "timeout in milliseconds");
        Option udp = new Option("u", false, "use UDP");
        Option zookeeper = new Option("z", true, "zookeeper connection string");
        Option warmup = new Option("w", true, "warmup messagges");
        Option measuring = new Option("m", true, "measuring time");
        Option request = new Option("r", true, "request size");
        Option frequency = new Option("f", true, "frequency of throughput info");
        Option anm = new Option("a", false, "use protection");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option asynSize = new Option("y", true, "size of async messages queue");

        options = new Options();
        options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port)
                .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper)
                .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm)
                .addOption(inlineThresh).addOption(asynSize);
    }

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

        String host = line.hasOption('l') ? line.getOptionValue('l')
                : "localhost:20548,localhost:20748,localhost:20778";
        String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
        int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
        int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
        int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
        int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100;
        boolean protection = line.hasOption('a');

        int threads = Runtime.getRuntime().availableProcessors() * 2;
        final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads,
                1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));

        String[] serverHosts = host.split(",");

        ServerHelloHandler shello = new ServerHelloHandler();
        ReplyHandler reply = new ReplyHandler();
        SubmitHandler submit = new SubmitHandler();
        TimeoutHandler tout = new TimeoutHandler();
        AsyncMessageHandler asyncm = new AsyncMessageHandler();
        ByeHandler bye = new ByeHandler();
        HelloHandler hello = new HelloHandler();

        Random rnd = new Random();

        for (int i = 0; i < buffer; ++i) {
            ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize);
            final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
            runtime.setState(clientState);
            runtime.addHandler(ServerHello.class, shello);
            runtime.addHandler(Reply.class, reply);
            runtime.addHandler(Submit.class, submit);
            runtime.addHandler(Timeout.class, tout);
            runtime.addHandler(AsyncMessage.class, asyncm);
            runtime.addHandler(Bye.class, bye);
            runtime.addHandler(Hello.class, hello);

            final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
                    serverHosts, clients, timeout, zkConnection, executor);

            if (line.hasOption('w'))
                handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
            if (line.hasOption('m'))
                handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
            if (line.hasOption('f'))
                handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));

            handler.start();

            Thread.sleep(rnd.nextInt(200));
        }
    } catch (Exception e) {
        System.err.println("Unexpected exception " + e);
        e.printStackTrace();

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.exit(-1);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphCreator.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);// w  ww . j a va 2 s .  c  om
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    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);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

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

    CommandLineParser parser = new PosixParser();

    try {

        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

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

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(OUT)));

        Class<?> inClazz = KyanosGraphCreator.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());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        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>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                saveOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        saveOpts.put(BlueprintsResourceOptions.STORE_OPTIONS, storeOptions);
        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");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            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:com.salaboy.rolo.server.RoloCommandServer.java

public static void main(String[] args) throws Exception {
    final Weld weld = new Weld();

    WeldContainer container = weld.initialize();

    RoloCommandServer roloCommandServer = container.instance().select(RoloCommandServer.class).get();

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("t", true, "sensors latency");
    options.addOption("ip", true, "host");
    options.addOption("port", true, "port");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String sensorLatency = cmd.getOptionValue("t");
    if (sensorLatency == null) {
        System.out.println(" The Default Latency will be used: " + defaultLatency);
    } else {/*  w ww .ja  v a 2 s .  com*/
        System.out.println(" The Latency will be set to: " + sensorLatency);
        defaultLatency = new Long(sensorLatency);
    }

    String ip = cmd.getOptionValue("ip");
    if (ip == null) {
        System.out.println(" The Default IP will be used: 127.0.0.1");
        roloCommandServer.setHost("127.0.0.1");

    } else {
        System.out.println(" The IP will be set to: " + ip);
        roloCommandServer.setHost(ip);
    }

    String port = cmd.getOptionValue("port");
    if (port == null) {
        System.out.println(" The Default Port will be used: 5445");
        roloCommandServer.setPort(5445);

    } else {
        System.out.println(" The Port will be set to: " + port);
        roloCommandServer.setPort(Integer.parseInt(port));
    }

    System.out.println("Starting Server Rolo ...");

    Thread thread = new Thread(roloCommandServer);
    thread.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            System.out.println("Shutdown Hook is running !");
            readSensors = false;
            weld.shutdown();
        }
    });

}

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252//from  w w  w .  j  a v  a2 s .  co  m
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }/*  w  w  w . j  ava  2s.  co m*/

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryGetBranchStatements.java

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

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

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

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

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

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            Set<TextElement> list = ASE2015JavaQueries.getCommentsTagContent(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.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:io.coala.eve3.Eve3Test.java

public static void main(String[] args) {
    try {/*from w w w  .  j av  a2 s  .c o  m*/
        final LocalConfig config = LocalConfig.builder().withId(agentName)
                .withProvider(Invoker.class, Eve3Invoker.class).build();
        final LocalBinder binder = Guice4LocalBinder.of(config);

        final List<URI> endpoints = binder.inject(Eve3Exposer.class).exposeAs(MyExposableService.class,
                new MyExposing());
        LOG.trace("Exposed {} at endpoints: {}", MyExposableService.class.getSimpleName(), endpoints);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.err.println("SHUTTING DOWN EVE HTTP DAEMON");
        }));

        //         Runtime.getRuntime().exit( 0 );
    } catch (final Exception e) {
        e.printStackTrace();
        System.exit(e.hashCode());
    }
}