Example usage for java.lang RuntimeException RuntimeException

List of usage examples for java.lang RuntimeException RuntimeException

Introduction

In this page you can find the example usage for java.lang RuntimeException RuntimeException.

Prototype

public RuntimeException(Throwable cause) 

Source Link

Document

Constructs a new runtime exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.github.besherman.fingerprint.Main.java

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

    options.addOption(OptionBuilder.withDescription("creates a fingerprint file for the directory").hasArg()
            .withArgName("dir").create('c'));

    options.addOption(OptionBuilder.withDescription("shows a diff between two fingerprint files")
            .withArgName("left-file> <right-file").hasArgs(2).create('d'));

    options.addOption(OptionBuilder.withDescription("shows a diff between a fingerprint and a directory")
            .withArgName("fingerprint> <dir").hasArgs(2).create('t'));

    options.addOption(OptionBuilder.withDescription("shows duplicates in a directory").withArgName("dir")
            .hasArgs(1).create('u'));

    options.addOption(/*  w w w .ja  v  a  2 s . com*/
            OptionBuilder.withDescription("output to file").withArgName("output-file").hasArg().create('o'));

    PosixParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint-dir", options, true);
        System.exit(7);
    }

    if (cmd.hasOption('c')) {
        Path root = Paths.get(cmd.getOptionValue('c'));

        if (!Files.isDirectory(root)) {
            System.err.println("root is not a directory");
            System.exit(7);
        }

        OutputStream out = System.out;

        if (cmd.hasOption('o')) {
            Path p = Paths.get(cmd.getOptionValue('o'));
            out = Files.newOutputStream(p);
        }

        Fingerprint fp = new Fingerprint(root, "");
        fp.write(out);

    } else if (cmd.hasOption('d')) {
        String[] ar = cmd.getOptionValues('d');
        Path leftFingerprintFile = Paths.get(ar[0]), rightFingerprintFile = Paths.get(ar[1]);
        if (!Files.isRegularFile(leftFingerprintFile)) {
            System.out.printf("%s is not a file%n", leftFingerprintFile);
            System.exit(7);
        }
        if (!Files.isRegularFile(rightFingerprintFile)) {
            System.out.printf("%s is not a file%n", rightFingerprintFile);
            System.exit(7);
        }

        Fingerprint left, right;
        try (InputStream input = Files.newInputStream(leftFingerprintFile)) {
            left = new Fingerprint(input);
        }

        try (InputStream input = Files.newInputStream(rightFingerprintFile)) {
            right = new Fingerprint(input);
        }

        Diff diff = new Diff(left, right);

        // TODO: if we have redirected output
        diff.print(System.out);
    } else if (cmd.hasOption('t')) {
        throw new RuntimeException("Not yet implemented");
    } else if (cmd.hasOption('u')) {
        Path root = Paths.get(cmd.getOptionValue('u'));
        Fingerprint fp = new Fingerprint(root, "");
        Map<String, FilePrint> map = new HashMap<>();
        fp.stream().forEach(f -> {
            if (map.containsKey(f.getHash())) {
                System.out.println("  " + map.get(f.getHash()).getPath());
                System.out.println("= " + f.getPath());
                System.out.println("");
            } else {
                map.put(f.getHash(), f);
            }
        });
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingd", options, true);
    }
}

From source file:com.oltpbenchmark.multitenancy.MuTeBench.java

/**
 * @param args/*from   w ww.  j a v  a  2 s .co m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String duration = null;
    String scenarioFile = null;

    // -------------------------------------------------------------------
    // INITIALIZE LOGGING
    // -------------------------------------------------------------------
    String log4jPath = System.getProperty("log4j.configuration");
    if (log4jPath != null) {
        org.apache.log4j.PropertyConfigurator.configure(log4jPath);
    } else {
        throw new RuntimeException("Missing log4j.properties file");
    }

    // -------------------------------------------------------------------
    // PARSE COMMAND LINE PARAMETERS
    // -------------------------------------------------------------------
    CommandLineParser parser = new PosixParser();
    XMLConfiguration pluginConfig = null;
    try {
        pluginConfig = new XMLConfiguration("config/plugin.xml");
    } catch (ConfigurationException e1) {
        LOG.info("Plugin configuration file config/plugin.xml is missing");
        e1.printStackTrace();
    }
    pluginConfig.setExpressionEngine(new XPathExpressionEngine());
    Options options = new Options();
    options.addOption("s", "scenario", true, "[required] Workload scenario file");
    options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation");
    options.addOption("r", "runtime", true,
            "maximum runtime  (no events will be started after finishing runtime)");
    options.addOption("v", "verbose", false, "Display Messages");
    options.addOption("g", "gui", false, "Show controlling GUI");
    options.addOption("h", "help", false, "Print this help");
    options.addOption("o", "output", true, "Output file (default System.out)");
    options.addOption("b", "baseline", true, "Output files of previous baseline run");
    options.addOption(null, "histograms", false, "Print txn histograms");
    options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file");

    // parse the command line arguments
    CommandLine argsLine = parser.parse(options, args);
    if (argsLine.hasOption("h")) {
        printUsage(options);
        return;
    } else if (!argsLine.hasOption("scenario")) {
        INIT_LOG.fatal("Missing scenario description file");
        System.exit(-1);
    } else
        scenarioFile = argsLine.getOptionValue("scenario");
    if (argsLine.hasOption("r"))
        duration = argsLine.getOptionValue("r");
    if (argsLine.hasOption("runtime"))
        duration = argsLine.getOptionValue("runtime");

    // -------------------------------------------------------------------
    // CREATE TENANT SCHEDULE
    // -------------------------------------------------------------------
    INIT_LOG.info("Create schedule");
    Schedule schedule = new Schedule(duration, scenarioFile);
    HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents();
    ArrayList<Integer> tenantList = schedule.getTenantList();

    List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>();

    for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) {
        int tenantID = tenantList.get(tenInd);
        for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) {

            BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID)
                    .getBenchmarkSettings(tenEvent);

            // update benchmark Settings
            benchmarkSettings.setTenantID(tenantID);

            // -------------------------------------------------------------------
            // GET PLUGIN LIST
            // -------------------------------------------------------------------
            String plugins = benchmarkSettings.getBenchmark();
            String[] pluginList = plugins.split(",");

            String configFile = benchmarkSettings.getConfigFile();
            XMLConfiguration xmlConfig = new XMLConfiguration(configFile);
            xmlConfig.setExpressionEngine(new XPathExpressionEngine());
            int lastTxnId = 0;

            for (String plugin : pluginList) {

                // ----------------------------------------------------------------
                // WORKLOAD CONFIGURATION
                // ----------------------------------------------------------------

                String pluginTest = "";

                pluginTest = "[@bench='" + plugin + "']";

                WorkloadConfiguration wrkld = new WorkloadConfiguration();
                wrkld.setTenantId(tenantID);
                wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID));
                wrkld.setXmlConfig(xmlConfig);
                wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID)));
                wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID));
                wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID));
                wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID));
                wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID));
                wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID));
                String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"),
                        tenantID);
                int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString));
                wrkld.setTerminals(terminals);
                int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1"));
                if (taSize < 0)
                    INIT_LOG.fatal("taSize must not be negative!");
                wrkld.setTaSize(taSize);
                wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false));
                wrkld.setIsolationMode(setTenantIDinString(
                        xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID));
                wrkld.setScaleFactor(Double
                        .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID)));
                wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false));

                int size = xmlConfig.configurationsAt("/works/work").size();

                for (int i = 1; i < size + 1; i++) {
                    SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]");
                    List<String> weight_strings;

                    // use a workaround if there multiple workloads or
                    // single
                    // attributed workload
                    if (pluginList.length > 1 || work.containsKey("weights[@bench]")) {
                        weight_strings = get_weights(plugin, work);
                    } else {
                        weight_strings = work.getList("weights[not(@bench)]");
                    }
                    int rate = 1;
                    boolean rateLimited = true;
                    boolean disabled = false;

                    // can be "disabled", "unlimited" or a number
                    String rate_string;
                    rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID);
                    rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string),
                            tenantID);
                    if (rate_string.equals(RATE_DISABLED)) {
                        disabled = true;
                    } else if (rate_string.equals(RATE_UNLIMITED)) {
                        rateLimited = false;
                    } else if (rate_string.isEmpty()) {
                        LOG.fatal(String.format(
                                "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s",
                                i, plugin));
                        System.exit(-1);
                    } else {
                        try {
                            rate = Integer.parseInt(rate_string);
                            if (rate < 1) {
                                LOG.fatal("Tenant " + tenantID
                                        + ": Rate limit must be at least 1. Use unlimited or disabled values instead.");
                                System.exit(-1);
                            }
                        } catch (NumberFormatException e) {
                            LOG.fatal(String.format(
                                    "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number",
                                    RATE_DISABLED, RATE_UNLIMITED));
                            System.exit(-1);
                        }
                    }
                    Phase.Arrival arrival = Phase.Arrival.REGULAR;
                    String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID);
                    if (arrive.toUpperCase().equals("POISSON"))
                        arrival = Phase.Arrival.POISSON;

                    int activeTerminals;
                    activeTerminals = Integer.parseInt(setTenantIDinString(
                            work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)),
                            tenantID));
                    activeTerminals = Integer.parseInt(setTenantIDinString(
                            work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)),
                            tenantID));
                    if (activeTerminals > terminals) {
                        LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i
                                + ": number of active terminals" + ""
                                + "is bigger than the total number of terminals");
                        System.exit(-1);
                    }
                    wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)),
                            rate, weight_strings, rateLimited, disabled, activeTerminals, arrival);
                } // FOR

                int numTxnTypes = xmlConfig
                        .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
                if (numTxnTypes == 0 && pluginList.length == 1) {
                    // if it is a single workload run, <transactiontypes />
                    // w/o attribute is used
                    pluginTest = "[not(@bench)]";
                    numTxnTypes = xmlConfig
                            .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
                }
                wrkld.setNumTxnTypes(numTxnTypes);

                // CHECKING INPUT PHASES
                int j = 0;
                for (Phase p : wrkld.getAllPhases()) {
                    j++;
                    if (p.getWeightCount() != wrkld.getNumTxnTypes()) {
                        LOG.fatal(String.format("Tenant " + tenantID
                                + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types",
                                j, p.getWeightCount(), wrkld.getNumTxnTypes()));
                        System.exit(-1);
                    }
                } // FOR

                // Generate the dialect map
                wrkld.init();

                assert (wrkld.getNumTxnTypes() >= 0);
                assert (xmlConfig != null);

                // ----------------------------------------------------------------
                // BENCHMARK MODULE
                // ----------------------------------------------------------------

                String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']");

                if (classname == null) {
                    throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml");
                }
                BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld },
                        new Class<?>[] { WorkloadConfiguration.class });
                assert (benchList.get(0) != null);

                Map<String, Object> initDebug = new ListOrderedMap<String, Object>();
                initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname));
                initDebug.put("Configuration", configFile);
                initDebug.put("Type", wrkld.getDBType());
                initDebug.put("Driver", wrkld.getDBDriver());
                initDebug.put("URL", wrkld.getDBConnection());
                initDebug.put("Isolation", setTenantIDinString(
                        xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID));
                initDebug.put("Scale Factor", wrkld.getScaleFactor());
                INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug));
                INIT_LOG.info(SINGLE_LINE);

                // Load TransactionTypes
                List<TransactionType> ttypes = new ArrayList<TransactionType>();

                // Always add an INVALID type for Carlo
                ttypes.add(TransactionType.INVALID);
                int txnIdOffset = lastTxnId;
                for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) {
                    String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]";
                    String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID);
                    int txnId = i + 1;
                    if (xmlConfig.containsKey(key + "/id")) {
                        txnId = Integer
                                .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID));
                    }
                    ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset));
                    lastTxnId = i;
                } // FOR
                TransactionTypes tt = new TransactionTypes(ttypes);
                wrkld.setTransTypes(tt);
                if (benchmarkSettings.getBenchmarkSlaFile() != null)
                    wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile());
                LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt);

                bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent));
                bench.setTenantID(tenantID);
                bench.setBenchmarkSettings(benchmarkSettings);
                benchList.add(bench);
            }
        }
    }
    // create result collector
    ResultCollector rCollector = new ResultCollector(tenantList);

    // execute benchmarks in parallel
    ArrayList<Thread> benchThreads = new ArrayList<Thread>();
    for (BenchmarkModule benchmark : benchList) {
        BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine);
        Thread t = new Thread(benchThread);
        t.start();
        benchThreads.add(t);
        benchmark.getWorkloadConfiguration().setrCollector(rCollector);
    }

    // waiting for completion of all benchmarks
    for (Thread t : benchThreads) {
        t.join();
    }

    // print statistics
    int analysisBuckets = -1;
    if (argsLine.hasOption("analysis-buckets"))
        analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets"));
    String output = null;
    if (argsLine.hasOption("o"))
        output = argsLine.getOptionValue("o");
    String baseline = null;
    if (argsLine.hasOption("b"))
        baseline = argsLine.getOptionValue("b");

    rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline);

    // create GUI
    if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) {
        try {
            Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector,
                    output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:chibi.gemmaanalysis.cli.deprecated.PARMapper.java

/**
 * @param args/*from ww w. j av  a  2 s .com*/
 */
public static void main(String[] args) {
    PARMapper p = new PARMapper();
    Exception e = p.doWork(args);
    if (e != null) {
        throw new RuntimeException(e);
    }

}

From source file:com.jkoolcloud.tnt4j.streams.utils.ZorkaAttach.java

/**
 * Main entry point for attaching Zorka agent to running JVM.
 *
 * @param args// w  w w. ja  va 2 s  .  c  om
 *            command-line arguments. Supported arguments:
 *            <table summary="TNT4J-Streams agent command line arguments">
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;zorkaAgentPath</td>
 *            <td>(required) Zorka agent path</td>
 *            </tr>
 *            <tr>
 *            <td>&nbsp;&nbsp;</td>
 *            <td>&nbsp;VMNameToAttachTo</td>
 *            <td>(required) Java VM name to attach to</td>
 *            </tr>
 *            </table>
 */
public static void main(String... args) {
    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME, "ZorkaAttach.starting.main"));
    if (args.length != 2) {
        System.out.println(
                StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME, "ZorkaAttach.main.usage"));
        return;
    }
    List<VirtualMachineDescriptor> runningVMsList = VirtualMachine.list();
    boolean found = false;
    // args[0] - agent path to attach
    // args[1] - VM name to attach to

    for (VirtualMachineDescriptor rVM : runningVMsList) {
        if (rVM.displayName().contains(args[1])
                && !rVM.displayName().contains(ZorkaAttach.class.getSimpleName())) {
            try {
                VirtualMachine vm = VirtualMachine.attach(rVM.id());
                File pathFile = new File(
                        ZorkaAttach.class.getProtectionDomain().getCodeSource().getLocation().getPath());
                String agentPath = pathFile.getAbsolutePath();
                LOGGER.log(OpLevel.INFO, StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME,
                        "ZorkaAttach.attaching.agent"), agentPath, rVM.displayName());
                vm.loadAgent(agentPath, args[0]);
                vm.detach();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            found = true;
        }
    }

    if (!found) {
        System.out.println(StreamsResources.getStringFormatted(ZorkaConstants.RESOURCE_BUNDLE_NAME,
                "ZorkaAttach.no.jvm", args[0]));
        System.out.println(
                StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME, "ZorkaAttach.available.jvms"));
        System.out.println(
                StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME, "ZorkaAttach.list.begin"));
        for (VirtualMachineDescriptor vmD : runningVMsList) {
            System.out.println(vmD.displayName());
        }
        System.out.println(
                StreamsResources.getString(ZorkaConstants.RESOURCE_BUNDLE_NAME, "ZorkaAttach.list.end"));
    }
}

From source file:uk.ac.kcl.Main.java

public static void main(String[] args) {
    File folder = new File(args[0]);
    File[] listOfFiles = folder.listFiles();
    assert listOfFiles != null;
    for (File listOfFile : listOfFiles) {
        if (listOfFile.isFile()) {
            if (listOfFile.getName().endsWith(".properties")) {
                System.out.println("Properties sile found:" + listOfFile.getName()
                        + ". Attempting to launch application context");
                Properties properties = new Properties();
                InputStream input;
                try {
                    input = new FileInputStream(listOfFile);
                    properties.load(input);
                    if (properties.getProperty("globalSocketTimeout") != null) {
                        TcpHelper.setSocketTimeout(
                                Integer.valueOf(properties.getProperty("globalSocketTimeout")));
                    }/*  ww w  .j a v  a2  s  .  c o  m*/
                    Map<String, Object> map = new HashMap<>();
                    properties.forEach((k, v) -> {
                        map.put(k.toString(), v);
                    });
                    ConfigurableEnvironment environment = new StandardEnvironment();
                    MutablePropertySources propertySources = environment.getPropertySources();
                    propertySources.addFirst(new MapPropertySource(listOfFile.getName(), map));
                    @SuppressWarnings("resource")
                    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                    ctx.registerShutdownHook();
                    ctx.setEnvironment(environment);
                    String scheduling;
                    try {
                        scheduling = properties.getProperty("scheduler.useScheduling");
                        if (scheduling.equalsIgnoreCase("true")) {
                            ctx.register(ScheduledJobLauncher.class);
                            ctx.refresh();
                        } else if (scheduling.equalsIgnoreCase("false")) {
                            ctx.register(SingleJobLauncher.class);
                            ctx.refresh();
                            SingleJobLauncher launcher = ctx.getBean(SingleJobLauncher.class);
                            launcher.launchJob();
                        } else if (scheduling.equalsIgnoreCase("slave")) {
                            ctx.register(JobConfiguration.class);
                            ctx.refresh();
                        } else {
                            throw new RuntimeException(
                                    "useScheduling not configured. Must be true, false or slave");
                        }
                    } catch (NullPointerException ex) {
                        throw new RuntimeException(
                                "useScheduling not configured. Must be true, false or slave");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:jmona.driver.Main.java

/**
 * Run the {@link EvolutionContext#stepGeneration()} method until the
 * CompletionConditionon is met, executing any Processors after each
 * generation step./*  w w  w . ja  va 2s. c  o  m*/
 * 
 * Provide the location of the Spring XML configuration file by using the
 * <em>--config</em> command line option, followed by the location of the
 * configuration file. By default, this program will look for a configuration
 * file at <code>./context.xml</code>.
 * 
 * @param args
 *          The command-line arguments to this program.
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) {
    // set up the list of options which the parser accepts
    setUpParser();

    // get the options from the command line arguments
    final OptionSet options = PARSER.parse(args);

    // get the location of the XML configuration file
    final String configFile = (String) options.valueOf(OPT_CONFIG_FILE);

    // create an application context from the specified XML configuration file
    final ApplicationContext applicationContext = new FileSystemXmlApplicationContext(configFile);

    // get the evolution contexts, completion criteria, and processors
    @SuppressWarnings("rawtypes")
    final Map<String, EvolutionContext> evolutionContextsMap = applicationContext
            .getBeansOfType(EvolutionContext.class);
    @SuppressWarnings("rawtypes")
    final Map<String, CompletionCondition> completionCriteriaMap = applicationContext
            .getBeansOfType(CompletionCondition.class);
    @SuppressWarnings("rawtypes")
    final Map<String, Processor> processorMap = applicationContext.getBeansOfType(Processor.class);

    // assert that there is only one evolution context bean in the app. context
    if (evolutionContextsMap.size() != 1) {
        throw new RuntimeException("Application context contains " + evolutionContextsMap.size()
                + " EvolutionContext beans, but must contain only 1.");
    }

    // assert that there is only one completion criteria bean in the app context
    if (completionCriteriaMap.size() != 1) {
        throw new RuntimeException("Application context contains " + completionCriteriaMap.size()
                + "CompletionCondition beans, but must contain only 1.");
    }

    // get the evolution context and completion condition from their maps
    @SuppressWarnings("rawtypes")
    final EvolutionContext evolutionContext = MapUtils.firstValue(evolutionContextsMap);
    @SuppressWarnings("rawtypes")
    final CompletionCondition completionCondition = MapUtils.firstValue(completionCriteriaMap);

    try {
        // while the criteria has not been satisfied, create the next generation
        while (!completionCondition.execute(evolutionContext)) {
            // create the next generation in the evolution
            evolutionContext.stepGeneration();

            // perform all post-processing on the evolution context
            for (@SuppressWarnings("rawtypes")
            final Processor processor : processorMap.values()) {
                processor.process(evolutionContext);
            }
        }
    } catch (final CompletionException exception) {
        throw new RuntimeException(exception);
    } catch (final EvolutionException exception) {
        throw new RuntimeException(exception);
    } catch (final ProcessingException exception) {
        throw new RuntimeException(exception);
    }
}

From source file:com.flipkart.poseidon.Poseidon.java

public static void main(String[] args) {
    if (args.length < 1) {
        throw new RuntimeException("No Bootstrap File Specified");
    }

    (new Bootstrap()).init(args[0]);
}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

/**
 * @param args//from  w  w w . j  a  va 2 s . com
 */
public static void main(String[] args) {
    boolean inplace = false;

    String workspace = "/Users/davidabad/workspaces/SIDE-Modules/";
    String frameworkmodulesPath = "/Volumes/Data/SVN/side/HEAD/S-IDE/FrameworksModules/trunk/";
    String classifier_base = "enterprise";
    String version_base = "3.4.6";
    String classifier_target = "enterprise";
    String version_target = "3.4.11";
    String frameworkmodulesInplace = "/Volumes/Data/SVN/projects/Ifremer/IfremerV5/src/modules/mavenProjects";

    Properties props = new Properties();
    try {
        InputStream resourceAsStream = PrepareSIDEModulesMigration.class
                .getResourceAsStream("config.properties");
        if (resourceAsStream != null) {
            props.load(resourceAsStream);

            inplace = Boolean.parseBoolean(props.getProperty("inplace", Boolean.toString(inplace)));
            workspace = props.getProperty("workspace", workspace);
            frameworkmodulesPath = props.getProperty("frameworkmodulesPath", frameworkmodulesPath);
            classifier_base = props.getProperty("classifier_base", classifier_base);
            version_base = props.getProperty("version_base", version_base);
            classifier_target = props.getProperty("classifier_target", classifier_target);
            version_target = props.getProperty("version_target", version_target);
            frameworkmodulesInplace = props.getProperty("frameworkmodulesInplace", frameworkmodulesInplace);
        } else {
            System.out.println("no configuration founded in classpath config.properties");
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    System.out.println("properties :");
    Enumeration<?> propertyNames = props.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String nextElement = propertyNames.nextElement().toString();
        System.out.println("\t " + nextElement + " : " + props.getProperty(nextElement));
    }

    File workspaceFile = new File(workspace);

    File targetHome = new File(workspaceFile, MIGRATION_FOLDER);
    if (targetHome.exists()) {
        try {
            FileUtils.deleteDirectory(targetHome);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    final String versionInProjectName = getVersionInProjectName(classifier_base, version_base);
    String versionInProjectName2 = getVersionInProjectName(classifier_target, version_target);

    if (frameworkmodulesPath.contains(",")) {
        // this is a list of paths
        String[] split = frameworkmodulesPath.split(",");
        for (String string : split) {
            if (StringUtils.trimToNull(string) != null) {
                executeInpath(inplace, string, classifier_base, version_base, classifier_target, version_target,
                        frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2);
            }
        }
    } else {
        executeInpath(inplace, frameworkmodulesPath, classifier_base, version_base, classifier_target,
                version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName,
                versionInProjectName2);
    }

    System.out.println("Job's done !");
    System.out.println("Please check " + MIGRATION_FOLDER);
    System.out.println(
            "If all is ok you can use commit.sh in a terminal do : cd " + MIGRATION_FOLDER + "; sh commit.sh");
    System.out.println(
            "This script will create new svn projet and commit resources, add 'target' to svn:ignore ...");

}

From source file:com.px100systems.data.utility.RestoreUtility.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility "
                + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]");
        return;/*from   w  ww . j  a v  a  2 s .com*/
    }

    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]);
    try {
        PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class);

        File directory = new File(args[2]);
        if (!directory.isDirectory()) {
            System.err.println(directory.getName() + " is not a directory");
            return;
        }

        List<File> files = new ArrayList<File>();
        //noinspection ConstantConditions
        for (File file : directory.listFiles())
            if (BackupFile.isBackup(file))
                files.add(file);

        if (files.isEmpty()) {
            System.err.println(directory.getName() + " directory has no backup files");
            return;
        }

        if (args.length == 4 && args[3].equalsIgnoreCase("compare")) {
            final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>();

            for (String storage : persister.storage()) {
                System.out.println("Storage " + storage);
                persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() {
                    @Override
                    public void process(RawRecord record) {
                        Map<Long, RawRecord> unitList = units.get(record.getUnitName());
                        if (unitList == null) {
                            unitList = new HashMap<Long, RawRecord>();
                            units.put(record.getUnitName(), unitList);
                        }
                        unitList.put(record.getId(), record);
                    }
                });

                for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) {
                    BackupFile file = null;
                    for (int i = 0, n = files.size(); i < n; i++)
                        if (BackupFile.isBackup(files.get(i), unit.getKey())) {
                            file = new BackupFile(files.get(i));
                            files.remove(i);
                            break;
                        }

                    if (file == null)
                        throw new RuntimeException("Could not find backup file for unit " + unit.getKey());

                    final Long[] count = new Long[] { 0L };
                    file.read(new PersistenceProvider.LoadCallback() {
                        @Override
                        public void process(RawRecord record) {
                            RawRecord r = unit.getValue().get(record.getId());
                            if (r == null)
                                throw new RuntimeException("Could not find persisted record " + record.getId()
                                        + " for unit " + unit.getKey());
                            if (!r.equals(record))
                                throw new RuntimeException(
                                        "Record " + record.getId() + " mismatch for unit " + unit.getKey());
                            count[0] = count[0] + 1;
                        }
                    });

                    if (count[0] != unit.getValue().size())
                        throw new RuntimeException("Extra persisted records for unit " + unit.getKey());
                    System.out.println("   Unit " + unit.getKey() + ": OK");
                }

                units.clear();
            }

            if (!files.isEmpty()) {
                System.err.println("Extra backups: ");
                for (File file : files)
                    System.err.println("   " + file.getName());
            }
        } else {
            persister.init();
            for (File file : files) {
                InMemoryDatabase.readBackupFile(file, persister);
                System.out.println("Loaded " + file.getName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ctx.close();
    }
}

From source file:com.linkedin.pinot.transport.perf.ScatterGatherPerfServer.java

/**
 * @param args//w  w  w.  j  ava 2s .  co  m
 */
public static void main(String[] args) throws Exception {

    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = buildCommandLineOptions();

    CommandLine cmd = cliParser.parse(cliOptions, args, true);

    if (!cmd.hasOption(RESPONSE_SIZE_OPT_NAME) || !cmd.hasOption(SERVER_PORT_OPT_NAME)) {
        System.err.println("Missing required arguments !!");
        System.err.println(cliOptions);
        throw new RuntimeException("Missing required arguments !!");
    }

    int responseSize = Integer.parseInt(cmd.getOptionValue(RESPONSE_SIZE_OPT_NAME));
    int serverPort = Integer.parseInt(cmd.getOptionValue(SERVER_PORT_OPT_NAME));

    ScatterGatherPerfServer server = new ScatterGatherPerfServer(serverPort, responseSize, 2); // 2ms latency
    server.run();
}