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:com.nuvolect.deepdive.probe.DecompileApk.java

private JSONObject dex2jar() {

    // DEX 2 JAR CONFIGS
    final boolean reuseReg = false; // reuse register while generate java .class file
    final boolean topologicalSort1 = false; // same with --topological-sort/-ts
    final boolean topologicalSort = false; // sort block by topological, that will generate more readable code
    final boolean verbose = true; // show progress
    final boolean debugInfo = false; // translate debug info
    final boolean printIR = false; // print ir to System.out
    final boolean optimizeSynchronized = true; // Optimise-synchronised

    final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override/*from  www.  jav a2  s .c  om*/
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_dex2jar_time = System.currentTimeMillis(); // Save start time for tracking

    m_dex2jarThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            boolean success = false;
            OmniFile dexFile = null;
            OmniFile jarFile = null;
            m_progressStream.putStream("DEX to JAR starting");

            for (String fileName : m_dexFileNames) {

                dexFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".dex");

                if (dexFile.exists() && dexFile.isFile()) {

                    String size = NumberFormat.getNumberInstance(Locale.US).format(dexFile.length());
                    m_progressStream.putStream("DEX to JAR processing: " + dexFile.getName() + ", " + size);

                    DexExceptionHandlerMod dexExceptionHandlerMod = new DexExceptionHandlerMod();
                    jarFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".jar");

                    if (jarFile.exists())
                        jarFile.delete();

                    try {
                        DexFileReader reader = new DexFileReader(dexFile.getStdFile());
                        Dex2jar dex2jar = Dex2jar.from(reader).reUseReg(reuseReg)
                                .topoLogicalSort(topologicalSort || topologicalSort1).skipDebug(!debugInfo)
                                .optimizeSynchronized(optimizeSynchronized).printIR(printIR);
                        //.verbose(verbose);
                        dex2jar.setExceptionHandler(dexExceptionHandlerMod);
                        dex2jar.to(jarFile.getStdFile());
                        success = true;
                    } catch (Exception e) {
                        String ex = LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                        m_progressStream.putStream(ex);
                        m_progressStream.putStream("DEX to JAR failed: " + jarFile.getName());
                        success = false;
                        continue;
                    }
                    if (success) {
                        size = NumberFormat.getNumberInstance(Locale.US).format(jarFile.length());
                        m_progressStream.putStream("DEX to JAR succeeded: " + jarFile.getName() + ", " + size);
                    } else {
                        m_progressStream
                                .putStream("Exception thrown, file cannot be decompiled: " + dexFile.getPath());
                    }
                }
            }
            if (jarFile == null)
                m_progressStream.putStream("No DEX file found: " + m_dexFileNames);

            m_progressStream.putStream("DEX to JAR complete: " + TimeUtil.deltaTimeHrMinSec(m_dex2jar_time));
            m_dex2jar_time = 0;

        }

    }, DEX2JAR_THREAD, STACK_SIZE);

    m_dex2jarThread.setPriority(Thread.MAX_PRIORITY);
    m_dex2jarThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_dex2jarThread.start();

    JSONObject wrapper = new JSONObject();
    try {
        wrapper.put("dex2jar_thread", getThreadStatus(true, m_dex2jarThread));

    } catch (JSONException e) {
        LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
    }

    return wrapper;
}

From source file:org.apache.storm.utils.Utils.java

public static void setupDefaultUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable thrown) {
            try {
                handleUncaughtException(thrown);
            } catch (Error err) {
                LOG.error("Received error in main thread.. terminating server...", err);
                Runtime.getRuntime().exit(-2);
            }//from w  ww .  ja  v a2 s. c  om
        }
    });
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

private JSONObject cfr() {

    m_srcCfrFolder.mkdirs();/*from  ww  w .jav  a 2 s . c  om*/

    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_cfr_time = System.currentTimeMillis(); // Save start time for tracking

    m_cfrThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            m_progressStream = new ProgressStream(
                    new OmniFile(m_volumeId, m_srcCfrFolderPath + "cfr_decompile_log.txt"));
            m_progressStream.putStream("CFR " + MiscConstants.CFR_VERSION + " starting");
            OmniFile jarFile = null;
            try {
                for (String fileName : m_dexFileNames) {

                    jarFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".jar");

                    if (jarFile.exists() && jarFile.isFile()) {

                        String[] args = { jarFile.getStdFile().toString(), "--outputdir",
                                m_srcCfrFolder.getStdFile().toString() };

                        Map<String, String> optionArgs = new HashMap<String, String>();
                        optionArgs.put("outputdir", m_srcCfrFolder.getStdFile().toString());
                        Options options = new OptionsImpl(optionArgs);
                        ClassFileSourceImpl classFileSource = new ClassFileSourceImpl(options);
                        final DCCommonState dcCommonState = new DCCommonState(options, classFileSource);
                        DumperFactoryImpl dumperFactory = new DumperFactoryImpl(options);
                        org.benf.cfr.reader.Main.doJar(dcCommonState, jarFile.getAbsolutePath(), dumperFactory);
                    }
                }

            } catch (Exception | StackOverflowError e) {
                m_progressStream.putStream(e.toString());
            }
            m_progressStream.putStream("CFR complete: " + TimeUtil.deltaTimeHrMinSec(m_cfr_time));
            m_progressStream.close();
            m_cfr_time = 0;

        }
    }, DEEPDIVE_THREAD_GROUP, STACK_SIZE);

    m_cfrThread.setPriority(Thread.MAX_PRIORITY);
    m_cfrThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_cfrThread.start();

    String processKey = "cfr_thread";
    String urlKey = "cfr_url";

    return processWrapper(processKey, urlKey);
}

From source file:com.brainflow.application.toplevel.Brainflow.java

private void initExceptionHandler() {
    LookAndFeelFactory.UIDefaultsCustomizer uiDefaultsCustomizer = new LookAndFeelFactory.UIDefaultsCustomizer() {
        public void customize(UIDefaults defaults) {
            ThemePainter painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter");
            defaults.put("OptionPaneUI", "com.jidesoft.plaf.basic.BasicJideOptionPaneUI");

            defaults.put("OptionPane.showBanner", Boolean.TRUE); // show banner or not. default is true
            //defaults.put("OptionPane.bannerIcon", JideIconsFactory.getImageIcon(JideIconsFactory.JIDE50));
            defaults.put("OptionPane.bannerFontSize", 13);
            defaults.put("OptionPane.bannerFontStyle", Font.BOLD);
            defaults.put("OptionPane.bannerMaxCharsPerLine", 60);
            defaults.put("OptionPane.bannerForeground",
                    painter != null ? painter.getOptionPaneBannerForeground() : null); // you should adjust this if banner background is not the default gradient paint
            defaults.put("OptionPane.bannerBorder", null); // use default border

            // set both bannerBackgroundDk and // set both bannerBackgroundLt to null if you don't want gradient
            defaults.put("OptionPane.bannerBackgroundDk",
                    painter != null ? painter.getOptionPaneBannerDk() : null);
            defaults.put("OptionPane.bannerBackgroundLt",
                    painter != null ? painter.getOptionPaneBannerLt() : null);
            defaults.put("OptionPane.bannerBackgroundDirection", Boolean.TRUE); // default is true

            // optionally, you can set a Paint object for BannerPanel. If so, the three UIDefaults related to banner background above will be ignored.
            defaults.put("OptionPane.bannerBackgroundPaint", null);

            defaults.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(6, 6, 6, 6));
            defaults.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
        }/*from   www.j  av a 2 s.co  m*/
    };
    uiDefaultsCustomizer.customize(UIManager.getDefaults());

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            JideOptionPane optionPane = new JideOptionPane(
                    "Click \"Details\" button to see more information ... ", JOptionPane.ERROR_MESSAGE,
                    JideOptionPane.CLOSE_OPTION);
            optionPane.setTitle("An " + e.getClass().getName() + " occurred in Brainflow : " + e.getMessage());

            JTextArea textArea = new JTextArea();
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            e.printStackTrace(out);
            // Add string to end of text area
            textArea.append(sw.toString());
            textArea.setRows(10);
            optionPane.setDetails(new JScrollPane(textArea));
            JDialog dialog = optionPane.createDialog(brainFrame, "Warning");
            dialog.setResizable(true);
            dialog.pack();
            dialog.setVisible(true);
        }
    });

}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

/**
 * Jadx converts a DEX file directly into Java files.  It does not input JAR files.
 *///from   w  w w.  j  a va 2  s.  co m
private JSONObject jadx() {

    m_srcJadxFolder.mkdirs();
    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_jadx_time = System.currentTimeMillis(); // Save start time for tracking

    m_jadxThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            m_progressStream.putStream("Jadx starting");
            /*
             * Type File require, versus OmniFile, in order to provide loadFiles
             * a list of <File>.
             */
            List<File> dexList = new ArrayList<>();
            JadxDecompiler jadx = new JadxDecompiler();
            jadx.setOutputDir(m_srcJadxFolder.getStdFile());
            String loadingNames = "";
            String spacer = "";

            for (String fileName : m_dexFileNames) {

                OmniFile dexFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".dex");

                if (dexFile.exists() && dexFile.isFile()) {

                    dexList.add(dexFile.getStdFile());
                    loadingNames += spacer + dexFile.getName();
                    spacer = ", ";

                    if (fileName.contentEquals(OPTIMIZED_CLASSES))
                        break;
                }
            }
            try {
                m_progressStream.putStream("Loading: " + loadingNames);
                jadx.loadFiles(dexList);
                m_progressStream.putStream("Load complete");
            } catch (Exception e) {
                LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                m_progressStream.putStream(e.toString());
            }
            try {
                m_progressStream.putStream("Jadx saveSources start");
                jadx.saveSources();
                m_progressStream.putStream("Jadx saveSources complete");
            } catch (Exception e) {
                LogUtil.logException(LogUtil.LogType.DECOMPILE, e);
                m_progressStream.putStream(e.toString());
            }

            m_progressStream.putStream("Jadx complete: " + TimeUtil.deltaTimeHrMinSec(m_jadx_time));
            m_jadx_time = 0;

        }
    }, JADX_THREAD, STACK_SIZE);

    m_jadxThread.setPriority(Thread.MAX_PRIORITY);
    m_jadxThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_jadxThread.start();

    String processKey = "jadx_thread";
    //                processStatus = getThreadStatus( true, m_jadxThread);
    String urlKey = "jadx_url";
    //                url = OmniHash.getHashedServerUrl( m_ctx, m_volumeId, m_srcJadxFolderPath);

    return processWrapper(processKey, urlKey);
}

From source file:org.apache.hadoop.hbase.replication.regionserver.ReplicationSource.java

public void startup() {
    String n = Thread.currentThread().getName();
    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(final Thread t, final Throwable e) {
            LOG.error("Unexpected exception in ReplicationSource," + " currentPath=" + currentPath, e);
        }//from  w  ww.ja va 2  s.  c  o m
    };
    Threads.setDaemonThreadRunning(this, n + ".replicationSource," + this.peerClusterZnode, handler);
}

From source file:org.apache.samza.storage.ContainerStorageManager.java

private void startSideInputs() {

    LOG.info("SideInput Restore started");

    // initialize the sideInputStorageManagers
    getSideInputStorageManagers().forEach(sideInputStorageManager -> sideInputStorageManager.init());

    // start the checkpointing thread at the commit-ms frequency
    sideInputsFlushFuture = sideInputsFlushExecutor.scheduleWithFixedDelay(new Runnable() {
        @Override//from  w  w  w . j  ava  2 s.  co m
        public void run() {
            try {
                getSideInputStorageManagers()
                        .forEach(sideInputStorageManager -> sideInputStorageManager.flush());
            } catch (Exception e) {
                LOG.error("Exception during flushing side inputs", e);
                sideInputException = Optional.of(e);
            }
        }
    }, 0, new TaskConfig(config).getCommitMs(), TimeUnit.MILLISECONDS);

    // set the latch to the number of sideInput SSPs
    this.sideInputsCaughtUp = new CountDownLatch(this.sideInputStorageManagers.keySet().size());

    // register all side input SSPs with the consumers
    for (SystemStreamPartition ssp : sideInputStorageManagers.keySet()) {
        String startingOffset = sideInputStorageManagers.get(ssp).getStartingOffset(ssp);

        if (startingOffset == null) {
            throw new SamzaException("No offset defined for SideInput SystemStreamPartition : " + ssp);
        }

        // register startingOffset with the sysConsumer and register a metric for it
        sideInputSystemConsumers.register(ssp, startingOffset, null);
        taskInstanceMetrics.get(sideInputStorageManagers.get(ssp).getTaskName()).addOffsetGauge(ssp,
                ScalaJavaUtil
                        .toScalaFunction(() -> sideInputStorageManagers.get(ssp).getLastProcessedOffset(ssp)));

        SystemStreamMetadata systemStreamMetadata = streamMetadataCache
                .getSystemStreamMetadata(ssp.getSystemStream(), false);
        SystemStreamMetadata.SystemStreamPartitionMetadata sspMetadata = (systemStreamMetadata == null) ? null
                : systemStreamMetadata.getSystemStreamPartitionMetadata().get(ssp.getPartition());

        // record a copy of the sspMetadata, to later check if its caught up
        initialSideInputSSPMetadata.put(ssp, sspMetadata);

        // check if the ssp is caught to upcoming, even at start
        checkSideInputCaughtUp(ssp, startingOffset, SystemStreamMetadata.OffsetType.UPCOMING, false);
    }

    // start the systemConsumers for consuming input
    this.sideInputSystemConsumers.start();

    // create a thread for sideInput reads
    Thread readSideInputs = new Thread(() -> {
        while (!shutDownSideInputRead) {
            IncomingMessageEnvelope envelope = sideInputSystemConsumers.choose(true);
            if (envelope != null) {

                if (!envelope.isEndOfStream())
                    sideInputStorageManagers.get(envelope.getSystemStreamPartition()).process(envelope);

                checkSideInputCaughtUp(envelope.getSystemStreamPartition(), envelope.getOffset(),
                        SystemStreamMetadata.OffsetType.NEWEST, envelope.isEndOfStream());

            } else {
                LOG.trace("No incoming message was available");
            }
        }
    });

    readSideInputs.setDaemon(true);
    readSideInputs.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            sideInputException = Optional.of(e);
            sideInputsCaughtUp.countDown();
        }
    });

    try {
        readSideInputs.start();
        // Make the main thread wait until all sideInputs have been caughtup or thrown an exception
        this.sideInputsCaughtUp.await();

        if (sideInputException.isPresent()) { // Throw exception if there was an exception in catching-up sideInputs
            // TODO: SAMZA-2113 relay exception to main thread
            throw new SamzaException("Exception in restoring side inputs", sideInputException.get());
        }
    } catch (InterruptedException e) {
        sideInputException = Optional.of(e);
        throw new SamzaException("Side inputs read was interrupted", e);
    }

    LOG.info("SideInput Restore complete");
}

From source file:com.ngdata.sep.impl.fork.ForkedReplicationSource.java

public void startup() {
    String n = Thread.currentThread().getName();
    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(final Thread t, final Throwable e) {
            LOG.error("Unexpected exception in ReplicationSource," + " currentPath=" + currentPath, e);
        }//w w w .  j ava2s.c o  m
    };
    Threads.setDaemonThreadRunning(this, n + ".replicationSource," + peerClusterZnode, handler);
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

/**
 * Fernflower converts JAR files to a zipped decompiled JAR file then
 * it unzips the JAR file.//from w ww .  j a va  2s .  c  om
 */
private JSONObject fern_flower() {// https://github.com/fesh0r/fernflower

    m_srcFernFolder.mkdirs();

    Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {

            LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString());
            m_progressStream.putStream("Uncaught exception: " + t.getName());
            m_progressStream.putStream("Uncaught exception: " + e.toString());
        }
    };

    m_fern_time = System.currentTimeMillis(); // Save start time for tracking

    m_fernThread = new Thread(m_threadGroup, new Runnable() {
        @Override
        public void run() {

            File inputJarFile = null;
            String inputJarFileName = "";

            for (int i = 0; i < m_dexFileNames.length; i++) {

                inputJarFileName = m_dexFileNames[i] + ".jar";
                OmniFile inputJarOmniFile = new OmniFile(m_volumeId, m_appFolderPath + inputJarFileName);
                inputJarFile = inputJarOmniFile.getStdFile();

                if (inputJarFile.exists() && inputJarFile.isFile()) {

                    boolean success = true;
                    try {
                        m_progressStream.putStream("Fernflower starting: " + inputJarFileName);
                        PrintStream printStream = new PrintStream(m_progressStream);
                        System.setErr(printStream);
                        System.setOut(printStream);
                        OmniFile fernLog = new OmniFile(m_volumeId,
                                m_srcFernFolderPath + "/" + m_dexFileNames[i] + "_log.txt");
                        PrintStream logStream = new PrintStream(fernLog.getOutputStream());
                        PrintStreamLogger logger = new PrintStreamLogger(logStream);

                        final Map<String, Object> mapOptions = new HashMap<>();
                        ConsoleDecompiler decompiler = new ConsoleDecompiler(m_srcFernFolder.getStdFile(),
                                mapOptions, logger);
                        decompiler.addSpace(inputJarFile, true);

                        m_progressStream
                                .putStream("Fernflower decompiler.addSpace complete: " + inputJarFileName);
                        decompiler.decompileContext();
                        m_progressStream.putStream(
                                "Fernflower decompiler.decompileContext complete: " + inputJarFileName);

                        String decompiledJarFilePath = m_srcFernFolderPath + "/" + inputJarFileName;
                        OmniFile decompiledJarFile = new OmniFile(m_volumeId, decompiledJarFilePath);
                        success = OmniZip.unzipFile(decompiledJarFile, m_srcFernFolder, null, null);
                        decompiledJarFile.delete();

                        if (success) {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack complete: " + inputJarFileName);
                        } else {
                            m_progressStream
                                    .putStream("Fernflower decompiler.unpack failed: " + inputJarFileName);
                        }
                    } catch (Exception e) {
                        String str = LogUtil.logException(LogUtil.LogType.FERNFLOWER, e);
                        m_progressStream.putStream("Fernflower exception " + inputJarFileName);
                        m_progressStream.putStream(str);
                        success = false;
                    }
                    /**
                     * Look for the classes.jar file and unzip it
                     */
                    if (!success) {

                        OmniFile of = new OmniFile(m_volumeId, m_srcFernFolderPath + "/classes.jar");
                        if (of.exists()) {

                            ApkZipUtil.unzip(of, m_srcFernFolder, m_progressStream);
                            m_progressStream.putStream(
                                    "Fernflower utility unzip complete with errors: " + inputJarFileName);
                        } else {
                            m_progressStream.putStream("File does not exist: " + of.getAbsolutePath());
                        }
                    }
                }
            }
            m_progressStream.putStream("Fernflower complete: " + TimeUtil.deltaTimeHrMinSec(m_fern_time));
            m_fern_time = 0;

        }
    }, FERN_THREAD, STACK_SIZE);

    m_fernThread.setPriority(Thread.MAX_PRIORITY);
    m_fernThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    m_fernThread.start();

    //                String processStatus = getThreadStatus( true, m_fernThread);
    //                String url = OmniHash.getHashedServerUrl( m_ctx, m_volumeId, m_srcFernFolderPath);

    String processKey = "fern_thread";
    String urlKey = "fern_url";

    return processWrapper(processKey, urlKey);
}

From source file:org.apache.storm.util.CoreUtil.java

/**
 * Set a default uncaught exception handler to handle exceptions not caught in
 * other threads./*from w w  w.j a va  2  s .  c  o m*/
 */
@ClojureClass(className = "backtype.storm.util#setup-default-uncaught-exception-handler")
public static void setupDefaultUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable thrown) {
            try {
                Utils.handleUncaughtException(thrown);
            } catch (Error err) {
                LOG.error("Received error in main thread.. terminating server...");
                Runtime.getRuntime().exit(-2);
            }
        }
    });
}