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.boulmier.machinelearning.jobexecutor.JobExecutor.java

public static void main(String[] args) throws ParseException, IOException, InterruptedException {
    Options options = defineOptions();/*from ww w .  j av  a2  s  .  co  m*/
    sysMon = new JavaSysMon();
    InetAddress vmscheduler_ip, mongodb_ip = null;
    Integer vmscheduler_port = null, mongodb_port = null;
    CommandLineParser parser = new BasicParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)) {
            vmscheduler_port = Integer.valueOf(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD));
        }
        mongodb_port = (int) (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                ? cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                : JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_PORT);
        mongodb_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGMONGOIPFIELD));

        vmscheduler_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGIPFIELD));

        decryptKey = cmd.getOptionValue("decrypt-key");

        debugState = cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGDEBUGFIELD);

        logger = LoggerFactory.getLogger();
        logger.info("Attempt to connect on master @" + vmscheduler_ip + ":" + vmscheduler_port);

        new RequestConsumer().start();

    } catch (MissingOptionException moe) {
        logger.error(moe.getMissingOptions() + " are missing");
        HelpFormatter help = new HelpFormatter();
        help.printHelp(JobExecutor.class.getSimpleName(), options);

    } catch (UnknownHostException ex) {
        logger.error(ex.getMessage());
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("JobExeutor is shutting down");
            }
        });
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryThrownExceptions.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 . ja v  a2s .c om*/
    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 = NeoEMFGraphQueryThrownExceptions.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();
            EList<TypeAccess> list = ASE2015JavaQueries.getThrownExceptions(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:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFMapQueryInvisibleMethodDeclarations.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 a2s.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(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_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(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING);
        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();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getInvisibleMethodDeclarations(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:herddb.server.ServerMain.java

public static void main(String... args) {
    try {//from   w w  w .  j  ava2 s  . c  om
        LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION());
        Properties configuration = new Properties();

        boolean configFileFromParameter = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                File configFile = new File(args[i]).getAbsoluteFile();
                LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
                configFileFromParameter = true;
            } else if (arg.equals("--use-env")) {
                System.getenv().forEach((key, value) -> {
                    System.out.println("Considering env as system property " + key + " -> " + value);
                    System.setProperty(key, value);
                });
            } else if (arg.startsWith("-D")) {
                int equals = arg.indexOf('=');
                if (equals > 0) {
                    String key = arg.substring(2, equals);
                    String value = arg.substring(equals + 1);
                    System.setProperty(key, value);
                }
            }
        }
        if (!configFileFromParameter) {
            File configFile = new File("conf/server.properties").getAbsoluteFile();
            LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
            if (configFile.isFile()) {
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
            }
        }

        System.getProperties().forEach((k, v) -> {
            String key = k + "";
            if (!key.startsWith("java") && !key.startsWith("user")) {
                configuration.put(k, v);
            }
        });

        LogManager.getLogManager().readConfiguration();

        Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") {

            @Override
            public void run() {
                System.out.println("Ctrl-C trapped. Shutting down");
                ServerMain _brokerMain = runningInstance;
                if (_brokerMain != null) {
                    _brokerMain.close();
                }
            }

        });
        runningInstance = new ServerMain(configuration);
        runningInstance.start();

        runningInstance.join();

    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:at.tuwien.ifs.somtoolbox.models.GrowingSOM.java

/**
 * Method for stand-alone execution of map training. Options are:<br/>
 * <ul>/* ww  w  .j a  v a2  s.c o m*/
 * <li>-h toggles HTML output</li>
 * <li>-l name of class implementing the labeling algorithm</li>
 * <li>-n number of labels to generate</li>
 * <li>-w name of weight vector file in case of training an already trained map</li>
 * <li>-m name of map description file in case of training an already trained map</li>
 * <li>--noDWM switch to not write the data winner mapping file</li>
 * <li>properties name of properties file, mandatory</li>
 * </ul>
 * 
 * @param args the execution arguments as stated above.
 */
public static void main(String[] args) {
    InputData data = null;
    FileProperties fileProps = null;

    GrowingSOM som = null;
    SOMProperties somProps = null;
    String networkModelName = "GrowingSOM";

    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);

    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("starting" + networkModelName);

    int cpus = config.getInt("cpus", 1);
    int systemCPUs = Runtime.getRuntime().availableProcessors();
    // We do not use more CPUs than available!
    if (cpus > systemCPUs) {
        String msg = "Number of CPUs required exceeds number of CPUs available.";
        if (cpus > 2 * systemCPUs) {
            msg += "Limiting to twice the number of available processors: " + 2 * systemCPUs;
            cpus = 2 * systemCPUs;
        }
        Logger.getLogger("at.tuwien.ifs.somtoolbox").warning(msg);
    }
    GrowingLayer.setNO_CPUS(cpus);

    String propFileName = AbstractOptionFactory.getFilePath(config, "properties");
    String weightFileName = AbstractOptionFactory.getFilePath(config, "weightVectorFile");
    String mapDescFileName = AbstractOptionFactory.getFilePath(config, "mapDescriptionFile");
    String labelerName = config.getString("labeling", null);
    int numLabels = config.getInt("numberLabels", DEFAULT_LABEL_COUNT);
    boolean skipDataWinnerMapping = config.getBoolean("skipDataWinnerMapping", false);
    Labeler labeler = null;
    // TODO: use parameter for max
    int numWinners = config.getInt("numberWinners", SOMLibDataWinnerMapping.MAX_DATA_WINNERS);

    if (labelerName != null) { // if labeling then label
        try {
            labeler = AbstractLabeler.instantiate(labelerName);
            Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Instantiated labeler " + labelerName);
        } catch (Exception e) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox")
                    .severe("Could not instantiate labeler \"" + labelerName + "\".");
            System.exit(-1);
        }
    }

    if (weightFileName == null) {
        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Training a new SOM.");
    } else {
        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Further training of an already trained SOM.");
    }

    try {
        fileProps = new FileProperties(propFileName);
        somProps = new SOMProperties(propFileName);
    } catch (PropertiesException e) {
        Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage() + " Aborting.");
        System.exit(-1);
    }

    data = getInputData(fileProps);

    if (weightFileName == null) {
        som = new GrowingSOM(data.isNormalizedToUnitLength(), somProps, data);
    } else {
        try {
            som = new GrowingSOM(new SOMLibFormatInputReader(weightFileName, null, mapDescFileName));
        } catch (Exception e) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage() + " Aborting.");
            System.exit(-1);
        }
    }

    if (somProps.getDumpEvery() > 0) {
        IntermediateSOMDumper dumper = som.new IntermediateSOMDumper(fileProps);
        som.layer.setTrainingInterruptionListener(dumper, somProps.getDumpEvery());
    }

    // setting input data so it is accessible by map output
    som.setSharedInputObjects(new SharedSOMVisualisationData(null, null, null, null,
            fileProps.vectorFileName(true), fileProps.templateFileName(true), null));
    som.getSharedInputObjects().setData(SOMVisualisationData.INPUT_VECTOR, data);

    som.train(data, somProps);

    if (labelerName != null) { // if labeling then label
        labeler.label(som, data, numLabels);
    }

    try {
        SOMLibMapOutputter.write(som, fileProps.outputDirectory(), fileProps.namePrefix(false), true, somProps,
                fileProps);
    } catch (IOException e) { // TODO: create new exception type
        Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Could not open or write to output file "
                + fileProps.namePrefix(false) + ": " + e.getMessage());
        System.exit(-1);
    }
    if (!skipDataWinnerMapping) {
        numWinners = Math.min(numWinners, som.getLayer().getXSize() * som.getLayer().getYSize());
        try {
            SOMLibMapOutputter.writeDataWinnerMappingFile(som, data, numWinners, fileProps.outputDirectory(),
                    fileProps.namePrefix(false), true);
        } catch (IOException e) {
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Could not open or write to output file "
                    + fileProps.namePrefix(false) + ": " + e.getMessage());
            System.exit(-1);
        }
    } else {
        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Skipping writing data winner mapping file");
    }

    if (config.getBoolean("htmlOutput") == true) {
        try {
            new HTMLOutputter().write(som, fileProps.outputDirectory(), fileProps.namePrefix(false));
        } catch (IOException e) { // TODO: create new exception type
            Logger.getLogger("at.tuwien.ifs.somtoolbox").severe("Could not open or write to output file "
                    + fileProps.namePrefix(false) + ": " + e.getMessage());
            System.exit(-1);
        }
    }

    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("finished" + networkModelName + "("
            + som.getLayer().getGridLayout() + ", " + som.getLayer().getGridTopology() + ")");
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFMapQuerySpecificInvisibleMethodDeclarations.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 a2  s. com
    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(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_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(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING);
        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();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(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:jms.Main.java

public static void main(String[] args) throws NamingException, JMSException, FileNotFoundException,
        InterruptedException, ParseException, CloneNotSupportedException {

    Options options = createOptions();/*  ww  w .j a  v a 2s . c o m*/

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

    Histogram latencyHist = Main.metrics.histogram(name(ConsumerThread.class, "global", "consumer", "latency"));
    Meter consumerRate = Main.metrics.meter(name(ConsumerThread.class, "global", "consumer", "rate"));

    if (cmd.hasOption("c")) {
        CONFIG_FILE_PATH = cmd.getOptionValue("c");
    } else {
        CONFIG_FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/client.yaml";
    }

    TestConfiguration config = ConfigReader.parseConfig(CONFIG_FILE_PATH);
    //        System.setProperty("qpid.flow_control_wait_failure", "1500000");
    // Subscribers

    startStatReporting(config.getGlobalConfig());

    int subscriberCount = config.getTopicSubscriberConfigList().size()
            + config.getQueueSubscriberConfigList().size() + config.getDurableSubscriberConfigList().size();
    final List<Thread> threadList = new ArrayList<Thread>(subscriberCount);

    TestTopicSubscriber topicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getTopicSubscriberConfigList()) {
        topicSubscriber = new TestTopicSubscriber();
        topicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(topicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    SimpleJMSConsumer queueReceiver;
    for (SubscriberConfig subscriberConfig : config.getQueueSubscriberConfigList()) {
        queueReceiver = new TestQueueReceiver();
        queueReceiver.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(queueReceiver, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    TestDurableTopicSubscriber durableTopicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getDurableSubscriberConfigList()) {
        durableTopicSubscriber = new TestDurableTopicSubscriber();
        durableTopicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(durableTopicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    // Publishers

    TestTopicPublisher topicPublisher;
    for (PublisherConfig publisherConfig : config.getTopicPublisherList()) {
        topicPublisher = new TestTopicPublisher();
        topicPublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(topicPublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    TestQueueSender queuePublisher;
    for (PublisherConfig publisherConfig : config.getQueuePublisherConfigList()) {
        queuePublisher = new TestQueueSender();
        queuePublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(queuePublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            log.info("Shutting down test client.");
            slf4jReporter.report();
            csvGaugeReporter.report();
            reporter.report();
            if (null != jmxReporter) {
                jmxReporter.close();
            }

            if (null != csvReporter) {
                csvReporter.report();
                csvReporter.close();
            }

            for (Thread t : threadList) {
                t.interrupt();
            }
        }
    });

    // barrier. wait till all the done
    for (Thread thread : threadList) {
        thread.join();
    }

    log.info("Test Complete!");
}

From source file:net.bluehornreader.service.ServiceManager.java

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

    String webappPath = null;//ww  w .  j a  v a2 s .co  m

    if (Utils.isInJar()) {
        if (args.length != 1 || isHelp(args)) {

            System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties "
                    + "-jar bluehorn-reader-<VERSION>.one-jar.jar <PATH>/config.properties");
            System.exit(1);
        }
    } else {
        if ((args.length != 2 && args.length != 1) || isHelp(args)) {
            System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties "
                    + "net.bluehornreader.service.ServiceManager <PATH>/config.properties <PATH>/webapp");
            System.exit(1);
        }

        if (args.length == 2) {
            webappPath = args[1];
        } else {
            URL url = ServiceManager.class.getClassLoader()
                    .getResource("net/bluehornreader/model/Article.class");
            if (url != null) {
                webappPath = url.getPath().replace("target/classes/net/bluehornreader/model/Article.class", "")
                        + "src/main/webapp";
                if (new File(webappPath).isDirectory()) {
                    LOG.info("Found webapp folder at " + webappPath);
                } else {
                    webappPath = null;
                }
            }

            if (webappPath == null) {
                System.err.println(
                        "Cannot locate the webapp folder. You'll have to specify it manually, as the second parameter.");
                System.exit(1);
            }
        }
    }

    if (webappPath == null) {
        webappPath = new File(".").getCanonicalPath(); // just to have a valid folder to pass
    }

    String configFileName = args[0];
    Config.setup(configFileName);
    final ServiceManager serviceManager = new ServiceManager(webappPath);

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOG.info("***************************************************************************\n\n");
            LOG.info("Shutting down ServiceManager ...");
            serviceManager.shutdown();
        }
    }));
}

From source file:com.yahoo.pasc.paxos.server.PaxosServer.java

/**
 * @param args//ww  w.  j a  va2 s.c o m
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IOException 
 * @throws MalformedURLException
 */
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IOException {

    CommandLineParser parser = new PosixParser();
    Options options;

    {
        Option id = new Option("i", true, "client id");
        Option port = new Option("p", true, "port used by server");
        Option buffer = new Option("b", true, "number of batched messages");
        //            Option clients      = new Option("c", true, "clients (hostname:port,...)");
        Option servers = new Option("s", true, "servers (hostname:port,...)");
        Option maxInstances = new Option("m", true, "max number of instances");
        Option anm = new Option("a", false, "protection against ANM faults");
        Option udp = new Option("u", false, "use UDP");
        Option cWindow = new Option("w", true, "congestion window");
        Option threads = new Option("t", true, "number of threads");
        Option digests = new Option("d", true, "max digests");
        Option ckPeriod = new Option("k", true, "checkpointing period");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option twoStages = new Option("2", false, "2 stages");
        Option digestQuorum = new Option("q", true, "digest quorum");
        Option leaderReplies = new Option("r", false, "leader replies");
        Option zookeeper = new Option("z", true, "zookeeper connection string");

        options = new Options();
        options.addOption(id).addOption(port).addOption(buffer).addOption(servers).addOption(threads)
                .addOption(anm).addOption(udp).addOption(maxInstances) //.addOption(leader)
                .addOption(cWindow).addOption(digests).addOption(ckPeriod).addOption(inlineThresh)
                .addOption(twoStages).addOption(digestQuorum).addOption(leaderReplies).addOption(zookeeper);
    }

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

        String serverAddresses[] = line.hasOption('s') ? line.getOptionValue('s').split(",")
                : new String[] { "10.78.36.104:20548", "10.78.36.104:20748" };
        //            String clientAddresses[] = line.hasOption('c') ? line.getOptionValue('c').split(",") : new String[] { "localhost:9000" };
        String zookeeper = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int serverId = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int batchSize = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int port = line.hasOption('p') ? Integer.parseInt(line.getOptionValue('p')) : 20548;
        int maxInstances = line.hasOption('m') ? Integer.parseInt(line.getOptionValue('m')) : 16 * 1024;
        int congestionWindow = line.hasOption('w') ? Integer.parseInt(line.getOptionValue('w')) : 1;
        int digests = line.hasOption('d') ? Integer.parseInt(line.getOptionValue('d')) : 16;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        boolean protection = line.hasOption('a');
        boolean udp = line.hasOption('u');
        boolean twoStages = line.hasOption('2');
        int quorum = serverAddresses.length / 2 + 1;
        int digestQuorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : quorum;
        int threads = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t'))
                : Runtime.getRuntime().availableProcessors() * 2 + 1;

        if (batchSize <= 0) {
            throw new RuntimeException("BatchSize must be greater than 0");
        }

        PaxosState state = new PaxosState(maxInstances, batchSize, serverId, quorum, digestQuorum,
                serverAddresses.length, congestionWindow, digests);
        if (line.hasOption('k'))
            state.setCheckpointPeriod(Integer.parseInt(line.getOptionValue('k')));
        if (line.hasOption('r'))
            state.setLeaderReplies(true);
        state.setRequestThreshold(inlineThreshold);

        if (!protection) {
            System.out.println("PANM disabled!");
        }

        final PascRuntime<PaxosState> runtime = new PascRuntime<PaxosState>(protection);
        runtime.setState(state);
        runtime.addHandler(Accept.class, new AcceptorAccept());
        runtime.addHandler(Prepare.class, new AcceptorPrepare());
        runtime.addHandler(Accepted.class, new Learner());
        runtime.addHandler(Prepared.class, new ProposerPrepared());
        runtime.addHandler(Request.class, new ProposerRequest());
        runtime.addHandler(InlineRequest.class, new ProposerRequest());
        runtime.addHandler(Digest.class, new DigestHandler());
        runtime.addHandler(PreReply.class, new LearnerPreReply());
        runtime.addHandler(Leader.class, new LeadershipHandler());

        if (udp) {
            new UdpServer(runtime, serverAddresses, null, port, threads, serverId).run();
        } else {
            new TcpServer(runtime, new EmptyStateMachine(), null, zookeeper, serverAddresses, port, threads,
                    serverId, twoStages).run();
        }
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.err.println("Unexpected exception: " + e);
        e.printStackTrace();

        System.exit(-1);
    }
}

From source file:com.salaboy.rolo.hardware.test.HardwareTestCommandServer.java

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

    WeldContainer container = weld.initialize();

    HardwareTestCommandServer roloCommandServer = container.instance().select(HardwareTestCommandServer.class)
            .get();//from  w w  w  .j  a  v a2 s  .  c  om

    // 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 {
        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 Rolo ...");

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

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

}