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(String message, Throwable cause) 

Source Link

Document

Constructs a new runtime exception with the specified detail message and cause.

Usage

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description.//from   ww w.j a va 2 s. c om
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {/*  w w w .  ja v a  2 s.c  o m*/
    System.err.println(
        "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
    System.exit(1);
            }
    */
    String server = "imap.handysoft.co.kr";
    String username = "namjk24@handysoft.co.kr";
    String password = "22222";

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    imap.setDefaultTimeout(60000);

    File imap_log_file = new File("IMAMP-UNSEEN");
    try {
        System.out.println(imap_log_file.getAbsolutePath());
        PrintStream ps = new PrintStream(imap_log_file);
        // suppress login details
        imap.addProtocolCommandListener(new PrintCommandListener(ps, true));
    } catch (FileNotFoundException e1) {
        imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
    }

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        //            imap.capability();

        //            imap.select("inbox");

        //            imap.examine("inbox");

        imap.status("inbox", new String[] { "UNSEEN" });

        //            imap.logout();
        imap.disconnect();

        List<String> imap_log = FileUtils.readLines(imap_log_file);
        for (int i = 0; i < imap_log.size(); i++) {
            System.out.println(i + ":" + imap_log.get(i));
        }
        String unseenText = imap_log.get(4);
        unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')'));
        int unseenCount = Integer.parseInt(unseenText.split(" ")[1]);

        System.out.println(unseenCount);
        //imap_log.indexOf("UNSEEN ")
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:com.twitter.heron.eco.Eco.java

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

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd;/*from   w  ww  .j  a  va 2 s  . com*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    FileInputStream fin = new FileInputStream(new File(cmd.getOptionValue(ECO_CONFIG_FILE)));

    String propsFile = cmd.getOptionValue(PROPS);
    FileInputStream propsInputStream = null;

    if (propsFile != null) {
        propsInputStream = new FileInputStream(new File(propsFile));
    }

    Boolean filterFromEnv = cmd.hasOption(ENV_PROPS);

    Eco eco = new Eco(new EcoBuilder(new SpoutBuilder(), new BoltBuilder(), new StreamBuilder(),
            new ComponentBuilder(), new ConfigBuilder()), new EcoParser(), new EcoSubmitter());

    eco.submit(fin, propsInputStream, filterFromEnv);
}

From source file:com.centurylink.mdw.util.HttpHelper.java

public static void main(String[] args) {
    try {//from  www .ja  v  a2  s .  com
        HttpHelper helper = new HttpHelper(new URL(args[0]));
        System.out.println(helper.get());
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java

/**
 * @param args/*from ww  w . jav  a 2s.  co  m*/
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Thread {} caught unhandled exception.", t.getName());
            logger.error("Unhandled exception.", e);
        }
    });

    if (args.length != 2) {
        logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file",
                "path/to/out/folder");
        System.exit(1);
    }

    String exptPathStr = args[0];
    String outPathStr = args[1];

    // Verify path points to something.
    Path exptPath = Paths.get(exptPathStr);
    if (!Files.exists(exptPath)) {
        logger.error("File: {} does not exist. Re-run with the correct path to "
                + " the experiment 2 column file. See README.md.");
        System.exit(1);
    }

    logger.info("Experiment map located at: {}", exptPathStr);

    // Create output dir if not yet created.
    Path outPath = Paths.get(outPathStr);
    if (!Files.exists(outPath)) {
        logger.info("Creating directory: {}", outPath.toString());
        try {
            Files.createDirectories(outPath);
        } catch (IOException e) {
            logger.error("Caught an IOException when creating output dir.", e);
            System.exit(1);
        }
    }

    logger.info("Output directory located at: {}", outPathStr);

    // Read in expt map. See README.md.
    Map<String, Set<String>> exptMap = null;
    try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) {
        exptMap = ExperimentUtils.createFilenameToIdMap(br);
    } catch (IOException e) {
        logger.error("Caught an IOException when creating expt map.", e);
        System.exit(1);
    }

    // Start a timer.
    logger.info("Gigaword -> Concrete beginning.");
    StopWatch sw = new StopWatch();
    sw.start();
    // Iterate over expt map.
    exptMap.entrySet()
            // .parallelStream()
            .forEach(p -> {
                final String pathStr = p.getKey();
                final Set<String> ids = p.getValue();
                final Path lp = Paths.get(pathStr);
                logger.info("Converting path: {}", pathStr);

                // Get the file name and immediate folder it is under.
                int nElements = lp.getNameCount();
                Path fileName = lp.getName(nElements - 1);
                Path subFolder = lp.getName(nElements - 2);
                String newFnStr = fileName.toString().split("\\.")[0] + ".tar";

                // Mirror folders in output dir.
                Path localOutFolder = outPath.resolve(subFolder);
                Path localOutPath = localOutFolder.resolve(newFnStr);

                // Create output subfolders.
                if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) {
                    logger.info("Creating out file: {}", localOutFolder.toString());
                    try {
                        Files.createDirectories(localOutFolder);
                    } catch (IOException e) {
                        throw new RuntimeException("Caught an IOException when creating output dir.", e);
                    }
                }

                // Iterate over communications.
                Iterator<Communication> citer;
                try (OutputStream os = Files.newOutputStream(localOutPath);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        Archiver archiver = new TarArchiver(bos);) {
                    citer = new ConcreteGigawordDocumentFactory().iterator(lp);
                    while (citer.hasNext()) {
                        Communication c = citer.next();
                        String cId = c.getId();

                        // Document ID must be in the set. Remove.
                        boolean wasInSet = ids.remove(cId);
                        if (!wasInSet) {
                            // Some IDs are duplicated in Gigaword.
                            // See ERRATA.
                            logger.debug(
                                    "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.",
                                    cId, pathStr);

                            // Attempt to create a duplicate id (append .duplicate to the id).
                            // Then, try to remove again.
                            String newId = RepairDuplicateIDs.repairDuplicate(cId);
                            boolean dupeRemoved = ids.remove(newId);
                            // There are not nested duplicates, so this should never fire.
                            if (!dupeRemoved) {
                                logger.info("Failed to remove dupe.");
                                return;
                            } else
                                // Modify the communication ID to the unique version.
                                c.setId(newId);
                        }

                        archiver.addEntry(new ArchivableCommunication(c));
                    }

                    logger.info("Finished path: {}", pathStr);
                } catch (ConcreteException ex) {
                    logger.error("Caught ConcreteException during Concrete mapping.", ex);
                    logger.error("Path: {}", pathStr);
                } catch (IOException e) {
                    logger.error("Error archiving communications.", e);
                    logger.error("Path: {}", localOutPath.toString());
                }
            });

    sw.stop();
    logger.info("Finished.");
    Minutes m = new Duration(sw.getTime()).toStandardMinutes();
    logger.info("Runtime: Approximately {} minutes.", m.getMinutes());
}

From source file:com.mycompany.rproject.runnableClass.java

public static void main(String args[]) throws Exception {
    try {/* ww  w.j  a va  2 s  .  c o  m*/
        System.out.println("Loading driver...");
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded!");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Cannot find the driver in the classpath!", e);
    }
    use();

}

From source file:com.twitter.heron.scheduler.SchedulerMain.java

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

    // construct the options and help options first.
    Options options = constructOptions();
    Options helpOptions = constructHelpOptions();

    // parse the options
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(helpOptions, args, true);

    // print help, if we receive wrong set of arguments
    if (cmd.hasOption("h")) {
        usage(options);/*from   w  w  w  . ja  va2  s. com*/
        return;
    }

    // Now parse the required options
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    // initialize the scheduler with the options
    String topologyName = cmd.getOptionValue("topology_name");
    SchedulerMain schedulerMain = createInstance(cmd.getOptionValue("cluster"), cmd.getOptionValue("role"),
            cmd.getOptionValue("environment"), cmd.getOptionValue("topology_jar"), topologyName,
            Integer.parseInt(cmd.getOptionValue("http_port")));

    // run the scheduler
    boolean ret = schedulerMain.runScheduler();

    // Log the result and exit
    if (!ret) {
        throw new RuntimeException("Failed to schedule topology: " + topologyName);
    } else {
        // stop the server and close the state manager
        LOG.log(Level.INFO, "Shutting down topology: {0}", topologyName);
    }
}

From source file:com.twitter.heron.scheduler.RuntimeManagerMain.java

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, IOException, ParseException {

    Options options = constructOptions();
    Options helpOptions = constructHelpOptions();
    CommandLineParser parser = new DefaultParser();
    // parse the help options first.
    CommandLine cmd = parser.parse(helpOptions, args, true);

    if (cmd.hasOption("h")) {
        usage(options);//w  ww.  j  av a2  s  .c om
        return;
    }

    try {
        // Now parse the required options
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    Boolean verbose = false;
    Level logLevel = Level.INFO;
    if (cmd.hasOption("v")) {
        logLevel = Level.ALL;
        verbose = true;
    }

    // init log
    LoggingHelper.loggerInit(logLevel, false);

    String cluster = cmd.getOptionValue("cluster");
    String role = cmd.getOptionValue("role");
    String environ = cmd.getOptionValue("environment");
    String heronHome = cmd.getOptionValue("heron_home");
    String configPath = cmd.getOptionValue("config_path");
    String overrideConfigFile = cmd.getOptionValue("override_config_file");
    String releaseFile = cmd.getOptionValue("release_file");
    String topologyName = cmd.getOptionValue("topology_name");
    String commandOption = cmd.getOptionValue("command");

    // Optional argument in the case of restart
    // TODO(karthik): convert into CLI
    String containerId = Integer.toString(-1);
    if (cmd.hasOption("container_id")) {
        containerId = cmd.getOptionValue("container_id");
    }

    Command command = Command.makeCommand(commandOption);

    // first load the defaults, then the config from files to override it
    Config.Builder defaultsConfig = Config.newBuilder().putAll(ClusterDefaults.getDefaults())
            .putAll(ClusterConfig.loadConfig(heronHome, configPath, releaseFile));

    // add config parameters from the command line
    Config.Builder commandLineConfig = Config.newBuilder().put(Keys.cluster(), cluster).put(Keys.role(), role)
            .put(Keys.environ(), environ).put(Keys.verbose(), verbose)
            .put(Keys.topologyContainerId(), containerId);

    Config.Builder topologyConfig = Config.newBuilder().put(Keys.topologyName(), topologyName);

    Config.Builder overrideConfig = Config.newBuilder()
            .putAll(ClusterConfig.loadOverrideConfig(overrideConfigFile));

    // build the final config by expanding all the variables
    Config config = Config
            .expand(Config.newBuilder().putAll(defaultsConfig.build()).putAll(overrideConfig.build())
                    .putAll(commandLineConfig.build()).putAll(topologyConfig.build()).build());

    LOG.fine("Static config loaded successfully ");
    LOG.fine(config.toString());

    // Create a new instance of RuntimeManagerMain
    RuntimeManagerMain runtimeManagerMain = new RuntimeManagerMain(config, command);
    boolean isSuccessful = runtimeManagerMain.manageTopology();

    // Log the result and exit
    if (!isSuccessful) {
        throw new RuntimeException(String.format("Failed to %s topology %s", command, topologyName));
    } else {
        LOG.log(Level.FINE, "Topology {0} {1} successfully", new Object[] { topologyName, command });
    }
}

From source file:de.micromata.genome.tpsb.executor.GroovyShellExecutor.java

public static void main(String[] args) {
    String methodName = null;// w  w  w.  jav a2 s.  com
    if (args.length > 0 && StringUtils.isNotBlank(args[0])) {
        methodName = args[0];
    }
    GroovyShellExecutor exec = new GroovyShellExecutor();
    //System.out.println("GroovyShellExecutor start");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    StringBuffer code = new StringBuffer();
    try {
        while ((line = in.readLine()) != null) {
            if (line.equals("--EOF--") == true) {
                break;
            }
            code.append(line);
            code.append("\n");

            //System.out.flush();
        }
    } catch (IOException ex) {
        throw new RuntimeException("Failure reading std in: " + ex.toString(), ex);
    }
    try {
        exec.executeCode(code.toString(), methodName);
    } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework
        warn("GroovyShellExecutor failed with exception: " + ex.getClass().getName() + ": " + ex.getMessage()
                + "\n" + ExceptionUtils.getStackTrace(ex));
    }
    System.out.println("--EOP--");
    System.out.flush();
}

From source file:com.twitter.heron.healthmgr.HealthManager.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options slaManagerCliOptions = constructCliOptions();

    // parse the help options first.
    Options helpOptions = constructHelpOptions();
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(slaManagerCliOptions);//from ww  w  .j  a  va2  s  .  co  m
        return;
    }

    try {
        cmd = parser.parse(slaManagerCliOptions, args);
    } catch (ParseException e) {
        usage(slaManagerCliOptions);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    HealthManagerMode mode = HealthManagerMode.cluster;
    if (hasOption(cmd, CliArgs.MODE)) {
        mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE));
    }

    Config config;
    switch (mode) {
    case cluster:
        config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig())
                .putAll(commandLineConfigs(cmd)).build());
        break;

    case local:
        if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) {
            throw new IllegalArgumentException("Missing heron_home or config_path argument");
        }
        String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME);
        String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH);
        config = Config.toLocalMode(
                Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
                        .putAll(commandLineConfigs(cmd)).build());
        break;

    default:
        throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE));
    }

    setupLogging(cmd, config);

    LOG.info("Static Heron config loaded successfully ");
    LOG.fine(config.toString());

    // load the default config value and override with any command line values
    String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key());
    metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName);

    String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key());
    metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl);

    AbstractModule module = buildMetricsProviderModule(metricsUrl, metricSourceClassName);
    HealthManager healthManager = new HealthManager(config, module);

    LOG.info("Initializing health manager");
    healthManager.initialize();

    LOG.info("Starting Health Manager metirc posting thread");
    HealthManagerMetrics publishingMetricsRunnable = null;
    if (hasOption(cmd, CliArgs.METRICSMGR_PORT)) {
        publishingMetricsRunnable = new HealthManagerMetrics(
                Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT)));
    }

    LOG.info("Starting Health Manager");
    PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies);
    ScheduledFuture<?> future = policyExecutor.start();
    if (publishingMetricsRunnable != null) {
        new Thread(publishingMetricsRunnable).start();
    }
    try {
        future.get();
    } finally {
        policyExecutor.destroy();
        if (publishingMetricsRunnable != null) {
            publishingMetricsRunnable.close();
        }
    }
}