Example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

Introduction

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

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:Main.java

public static void main(String[] args) {

    Thread t = new Thread(new MyThread());
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " throws exception: " + e);
        }/*from w w  w . j  a v  a  2  s . co  m*/
    });
    t.start();
}

From source file:MainClass.java

public static void main(String[] args) {
    Thread thread = new Thread(new MyThread());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " threw exception: " + e);
        }//from w w  w.j  ava2  s. c  om
    });
    thread.start();
}

From source file:Main.java

public static void main(String[] args) {

    Thread t = new Thread(new MyThread());

    t.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " throws exception: " + e);
        }//from   w  w  w.ja v a  2 s.c  om
    });
    t.start();
}

From source file:Uncaught.java

public static void main(String[] args) {
    Thread thread = new Thread(new Uncaught());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();//  w w w .j  av a2  s.  c  o  m
        }
    });
    thread.start();
}

From source file:com.joshlong.lazyblogger.Main.java

public static void main(String[] args) {

    try {//from ww  w .  ja  v a2  s  . com
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable e) {
                LOGGER.info(ExceptionUtils.getFullStackTrace(e));
            }
        });
        new ClassPathXmlApplicationContext("integrations-context.xml").start();

        LOGGER.info("Started context: ");
    } catch (Throwable e) {
        LOGGER.info(ExceptionUtils.getFullStackTrace(e));
    }

}

From source file:sample.SampleApp.java

public static void main(String[] args) throws InterruptedException {
    final Log logger = LogFactory.getLog(SampleApp.class);

    //create AWSCloudTrailProcessingExecutor and start it
    final AWSCloudTrailProcessingExecutor executor = new AWSCloudTrailProcessingExecutor.Builder(
            new SampleEventsProcessor(), "/sample/awscloudtrailprocessinglibrary.properties")
                    .withSourceFilter(new SampleSourceFilter()).withEventFilter(new SampleEventFilter())
                    .withProgressReporter(new SampleProgressReporter())
                    .withExceptionHandler(new SampleExceptionHandler()).build();
    executor.start();/*from   ww w.ja  v a2  s . c  o  m*/

    // add shut down hook to gracefully stop executor (optional)
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            logger.info("Shut Down Hook is called.");
            executor.stop();
        }
    });

    // register a Default Uncaught Exception Handler (optional)
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Handled by global Exception handler. " + e.getMessage() + " " + t.getName());

            //Two options here:
            //First, we can call System.exit(1); in such case shut down hook will be called.
            //Second, we can optionally restart another executor and start.
            final AWSCloudTrailProcessingExecutor executor = new AWSCloudTrailProcessingExecutor.Builder(
                    new SampleEventsProcessor(), "/sample/awscloudtrailprocessinglibrary.properties")
                            .withSourceFilter(new SampleSourceFilter()).withEventFilter(new SampleEventFilter())
                            .withProgressReporter(new SampleProgressReporter())
                            .withExceptionHandler(new SampleExceptionHandler()).build();
            executor.start();
        }
    });

    //can optionally limit running time, or remove both lines so it is running forever. (optional)
    Thread.sleep(24 * 60 * 60 * 1000);
    executor.stop();
}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *//*from w ww.j a  v a  2s .c  om*/
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:com.amazon.kinesis.streaming.agent.Agent.java

public static void main(String[] args) throws Exception {
    AgentOptions opts = AgentOptions.parse(args);
    String configFile = opts.getConfigFile();
    AgentConfiguration config = tryReadConfigurationFile(Paths.get(opts.getConfigFile()));
    Path logFile = opts.getLogFile() != null ? Paths.get(opts.getLogFile())
            : (config != null ? config.logFile() : null);
    String logLevel = opts.getLogLevel() != null ? opts.getLogLevel()
            : (config != null ? config.logLevel() : null);
    int logMaxBackupFileIndex = (config != null ? config.logMaxBackupIndex() : -1);
    long logMaxFileSize = (config != null ? config.logMaxFileSize() : -1L);
    Logging.initialize(logFile, logLevel, logMaxBackupFileIndex, logMaxFileSize);
    final Logger logger = Logging.getLogger(Agent.class);

    // Install an unhandled exception hook
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/* w w w. j a v  a2 s. c  o m*/
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof OutOfMemoryError) {
                // This prevents the JVM from hanging in case of an OOME
                dontShutdownOnExit = true;
            }
            String msg = "FATAL: Thread " + t.getName() + " threw an unrecoverable error. Aborting application";
            try {
                try { // We don't know if logging is still working
                    logger.error(msg, e);
                } finally {
                    System.err.println(msg);
                    e.printStackTrace();
                }
            } finally {
                System.exit(1);
            }
        }
    });

    try {
        logger.info("Reading configuration from file: {}", configFile);
        if (config == null) {
            config = readConfigurationFile(Paths.get(opts.getConfigFile()));
        }
        // Initialize and start the agent
        AgentContext agentContext = new AgentContext(config);
        if (agentContext.flows().isEmpty()) {
            throw new ConfigurationException("There are no flows configured in configuration file.");
        }
        final Agent agent = new Agent(agentContext);

        // Make sure everything terminates cleanly when process is killed
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (!dontShutdownOnExit && agent.isRunning()) {
                    agent.stopAsync();
                    agent.awaitTerminated();
                }
            }
        });

        agent.startAsync();
        agent.awaitRunning();
        agent.awaitTerminated();
    } catch (Exception e) {
        logger.error("Unhandled error.", e);
        System.err.println("Unhandled error.");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.apache.rya.export.client.MergeDriverClient.java

public static void main(final String[] args)
        throws ParseException, MergeConfigurationException, UnknownHostException, MergerException,
        java.text.ParseException, SailException, AccumuloException, AccumuloSecurityException,
        InferenceEngineException, RepositoryException, MalformedQueryException, UpdateExecutionException {

    final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration");
    if (StringUtils.isNotBlank(log4jConfiguration)) {
        final String parsedConfiguration = StringUtils.removeStart(log4jConfiguration, "file:");
        final File configFile = new File(parsedConfiguration);
        if (configFile.exists()) {
            DOMConfigurator.configure(parsedConfiguration);
        } else {//from  ww  w .  j a v a 2s. c om
            BasicConfigurator.configure();
        }
    }

    final MergeConfigurationCLI config = new MergeConfigurationCLI(args);
    try {
        configuration = config.createConfiguration();
    } catch (final MergeConfigurationException e) {
        LOG.error("Configuration failed.", e);
    }

    final boolean useTimeSync = configuration.getUseNtpServer();
    Optional<Long> offset = Optional.absent();
    if (useTimeSync) {
        final String tomcat = configuration.getChildTomcatUrl();
        final String ntpHost = configuration.getNtpServerHost();
        try {
            offset = Optional
                    .<Long>fromNullable(TimeUtils.getNtpServerAndMachineTimeDifference(ntpHost, tomcat));
        } catch (final IOException e) {
            LOG.error("Unable to get time difference between time server: " + ntpHost + " and the server: "
                    + tomcat, e);
        }
    }

    final StatementStoreFactory storeFactory = new StatementStoreFactory(configuration);
    try {
        final RyaStatementStore parentStore = storeFactory.getParentStatementStore();
        final RyaStatementStore childStore = storeFactory.getChildStatementStore();

        LOG.info("Starting Merge Tool");
        if (configuration.getParentDBType() == ACCUMULO && configuration.getChildDBType() == ACCUMULO) {
            final AccumuloRyaStatementStore childAStore = (AccumuloRyaStatementStore) childStore;
            final AccumuloRyaStatementStore parentAStore = (AccumuloRyaStatementStore) parentStore;

            //do map reduce merging.
            //TODO: Run Merger
        } else {
            if (configuration.getMergePolicy() == TIMESTAMP) {
                final TimestampPolicyMergeConfiguration timeConfig = (TimestampPolicyMergeConfiguration) configuration;
                final Long timeOffset;
                if (offset.isPresent()) {
                    timeOffset = offset.get();
                } else {
                    timeOffset = 0L;
                }
                final MemoryTimeMerger merger = new MemoryTimeMerger(parentStore, childStore,
                        new VisibilityStatementMerger(), timeConfig.getToolStartTime(),
                        configuration.getParentRyaInstanceName(), timeOffset);
                merger.runJob();
            }
        }
    } catch (final Exception e) {
        LOG.error("Something went wrong creating a Rya Statement Store connection.", e);
    }

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOG.error("Uncaught exception in " + thread.getName(), throwable);
        }
    });

    LOG.info("Finished running Merge Tool");
    System.exit(1);
}

From source file:org.apache.pdfbox.debugger.PDFDebugger.java

/**
 * Entry point./*w  ww. j a  va  2 s  .  com*/
 *
 * @param args the command line arguments
 * @throws Exception If anything goes wrong.
 */
public static void main(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
    }

    // handle uncaught exceptions
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            new ErrorDialog(throwable).setVisible(true);
        }
    });

    // open file, if any
    String filename = null;
    String password = "";
    boolean viewPages = true;

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(PASSWORD)) {
            i++;
            if (i >= args.length) {
                usage();
            }
            password = args[i];
        } else if (args[i].equals(VIEW_STRUCTURE)) {
            viewPages = false;
        } else {
            filename = args[i];
        }
    }
    filename = "/home/data/work/pdfxx_m.pdf";
    final PDFDebugger viewer = new PDFDebugger(viewPages);

    if (filename != null) {
        File file = new File(filename);
        if (file.exists()) {
            viewer.readPDFFile(filename, password);
        }
    }
    viewer.setVisible(true);
}