Example usage for java.lang Thread setDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler

Introduction

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

Prototype

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Usage

From source file:org.videolan.vlc.AudioService.java

@Override
public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {//from ww w. ja  v  a 2 s  .c o m
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:majordodo.task.BrokerTestUtils.java

@Before
public void brokerTestUtilsBefore() throws Exception {
    // Setup exception handler
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override/*  ww w.  j  ava2 s .c om*/
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
            unhandledExceptions.add(e);
        }
    });

    // Setup Logger
    System.out.println("Setup logger to level " + logLevel.getName());
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(logLevel);
    ch.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
            return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " ["
                    + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] "
                    + record.getLoggerName() + ": " + formatMessage(record) + "\n";
        }
    });
    java.util.logging.Logger.getLogger("").setLevel(logLevel);
    java.util.logging.Logger.getLogger("").addHandler(ch);

    // Initialize groupsMap
    groupsMap.clear();
    groupsMap.put(userId, group);

    // Setup workdir
    Path mavenTargetDir = Paths.get("target").toAbsolutePath();
    workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime());

    if (startBroker) {
        broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));
        broker.startAsWritable();

        server = new NettyChannelAcceptor(broker.getAcceptor());
        server.start();
    }
    if (startReplicatedBrokers) {
        zkServer = new ZKTestEnv(folderZk.getRoot().toPath());
        zkServer.startBookie();

        // Broker 1
        broker1 = new Broker(broker1Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker1Host, broker1Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker1.startAsWritable();

        server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port);
        server1.start();

        // Broker 2
        broker2 = new Broker(broker2Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker2Host, broker2Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker2.start();

        server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port);
        server2.start();

        // Broker locator
        brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath());
    }

}

From source file:org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager.java

private String executeTest(File test) throws Exception {
    String reportFileName;/* w  w w.j  a  v  a  2  s.c  om*/
    String reportFileFullPath;
    JMeter jmeterInstance = new JMeter();
    try {
        log.info("Executing test: " + test.getCanonicalPath());
        reportFileName = test.getName().substring(0, test.getName().lastIndexOf(".")) + "-"
                + fmt.format(new Date()) + ".jmeterResult" + ".jtl";

        File reportDir = JMeterInstallationProvider.getInstance().getReportDir();
        reportFileFullPath = reportDir.toString() + File.separator + reportFileName;
        List<String> argsTmp = Arrays.asList("-n", "-t", test.getCanonicalPath(), "-l",
                reportDir.toString() + File.separator + reportFileName, "-p", jmeterProps.toString(), "-d",
                jmeterHome.getCanonicalPath(), "-L", "jorphan=" + jmeterLogLevel, "-L",
                "jmeter.util=" + jmeterLogLevel);

        List<String> args = new ArrayList<String>();

        args.addAll(argsTmp);

        SecurityManager oldManager = System.getSecurityManager();

        UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            public void uncaughtException(Thread t, Throwable e) {
                if (e instanceof ExitException && ((ExitException) e).getCode() == 0) {
                    return; //Ignore
                }
                log.error("Error in thread " + t.getName());
            }
        });

        try {
            logParamsAndProps(args);

            jmeterInstance.start(args.toArray(new String[] {}));

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(new FileInputStream(jmeterLogFile), Charset.defaultCharset()));

            while (!checkForEndOfTest(in)) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }
            }

        } catch (ExitException e) {
            if (e.getCode() != 0) {
                throw new Exception("Test failed", e);
            }
        } catch (Exception e) {
            log.error(e);

        } finally {
            System.setSecurityManager(oldManager);
            Thread.setDefaultUncaughtExceptionHandler(oldHandler);
        }
    } catch (IOException e) {
        throw new Exception("Can't execute test", e);
    }
    return reportFileFullPath;
}

From source file:org.videolan.vlc.MediaService.java

@Override
public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {/*w w w  . ja va  2s  .c  om*/
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IMediaServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:org.midonet.midolman.Midolman.java

private void setUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/* www. j av  a2s.  c  om*/
        public void uncaughtException(Thread t, Throwable e) {
            log.error("Unhandled exception: ", e);
            dumpStacks();
            System.exit(MIDOLMAN_ERROR_CODE_UNHANDLED_EXCEPTION);
        }
    });
}

From source file:com.javielinux.tweettopics2.TweetTopicsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    try {/* ww  w.  j a v a  2  s  . com*/
        DataFramework.getInstance().open(this, Utils.packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    super.onCreate(savedInstanceState);

    CacheData.getInstance().fillHide();

    ConnectionManager.getInstance().open(this);
    ConnectionManager.getInstance().loadUsers();

    OnAlarmReceiver.callAlarm(this);

    if (PreferenceUtils.getFinishForceClose(this)) {
        PreferenceUtils.setFinishForceClose(this, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.title_crash);
        builder.setMessage(R.string.msg_crash);
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Utils.sendLastCrash(TweetTopicsActivity.this);
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });
        builder.create();
        builder.show();
    }

    Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (currentHandler != null) {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorReporter(currentHandler, getApplication()));
    }

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("prf_orientation", "2").equals("2")) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    // borrar notificaciones
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("prf_notif_delete_notifications_inside",
            true)) {
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
    }

    long goToColumnPosition = -1;
    int goToColumnType = -1;
    long goToColumnUser = -1;
    long goToColumnSearch = -1;
    long selectedTweetId = -1;

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_POSITION)) {
            goToColumnPosition = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_POSITION);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_TYPE)) {
            goToColumnType = extras.getInt(KEY_EXTRAS_GOTO_COLUMN_TYPE);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_USER)) {
            goToColumnUser = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_USER);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_SEARCH)) {
            goToColumnSearch = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_SEARCH);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_TWEET_ID)) {
            selectedTweetId = extras.getLong(KEY_EXTRAS_GOTO_TWEET_ID);
        }
    }

    int positionFromSensor = -1;
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_SAVE_STATE_COLUMN_POS)) {
        positionFromSensor = savedInstanceState.getInt(KEY_SAVE_STATE_COLUMN_POS);
    }

    Utils.createDirectoriesIfIsNecessary();

    Display display = getWindowManager().getDefaultDisplay();
    widthScreen = display.getWidth();
    heightScreen = display.getHeight();

    themeManager = new ThemeManager(this);
    themeManager.setTheme();

    setContentView(R.layout.tweettopics_activity);

    fragmentAdapter = new TweetTopicsFragmentAdapter(this, getSupportFragmentManager());

    pager = (ViewPager) findViewById(R.id.tweet_pager);
    pager.setAdapter(fragmentAdapter);

    indicator = (TitlePageIndicator) findViewById(R.id.tweettopics_bar_indicator);
    indicator.setFooterIndicatorStyle(TitlePageIndicator.IndicatorStyle.Triangle);
    indicator.setFooterLineHeight(0);
    indicator.setFooterColor(Color.WHITE);
    indicator.setClipPadding(-getWindowManager().getDefaultDisplay().getWidth());
    indicator.setViewPager(pager);
    indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {
        }

        @Override
        public void onPageSelected(int i) {
            reloadBarAvatar();
            if (i == 0) {
                refreshMyActivity();
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
    indicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarColumns();
        }
    });

    findViewById(R.id.tweettopics_bar_my_activity).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarIndicatorAndMovePager(0);
        }
    });

    findViewById(R.id.tweettopics_bar_options).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showMenuColumnsOptions(view);
        }
    });

    layoutOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_options_columns);
    layoutMainOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_main_options_columns);
    layoutMainOptionsColumns.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsMain = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_main);
    btnOptionsColumnsMain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            Toast.makeText(TweetTopicsActivity.this,
                    getString(R.string.column_main_message, fragmentAdapter.setColumnActive(pos)),
                    Toast.LENGTH_LONG).show();
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsEdit = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_edit);
    btnOptionsColumnsEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            EditColumnDialogFragment frag = new EditColumnDialogFragment(
                    fragmentAdapter.getFragmentList().get(pos), new Callable() {
                        @Override
                        public Object call() throws Exception {
                            refreshActionBarColumns();
                            return null;
                        }
                    });
            frag.show(getSupportFragmentManager(), "dialog");
            hideOptionsColumns();
        }
    });

    // cargar el popup de enlaces

    FrameLayout root = ((FrameLayout) findViewById(R.id.tweettopics_root));
    popupLinks = new PopupLinks(this);
    popupLinks.loadPopup(root);

    splitActionBarMenu = new SplitActionBarMenu(this);
    splitActionBarMenu.loadSplitActionBarMenu(root);

    layoutBackgroundApp = (RelativeLayout) findViewById(R.id.tweettopics_layout_background_app);

    layoutBackgroundBar = (RelativeLayout) findViewById(R.id.tweettopics_bar_background);

    horizontalScrollViewColumns = (HorizontalScrollView) findViewById(R.id.tweettopics_bar_horizontal_scroll);

    layoutBackgroundColumnsBarContainer = (LinearLayout) findViewById(R.id.tweettopics_bar_columns_container);

    layoutBackgroundColumnsBar = (LinearLayout) findViewById(R.id.tweettopics_bar_columns);
    //        layoutBackgroundColumnsBar.setCols(4);
    //
    //        layoutBackgroundColumnsBar.setOnRearrangeListener(new OnRearrangeListener() {
    //            public void onRearrange(int oldIndex, int newIndex) {
    //                reorganizeColumns(oldIndex, newIndex);
    //            }
    //
    //            @Override
    //            public void onStartDrag(int x, int index) {
    //                showOptionsColumns(x, index, true);
    //            }
    //
    //            @Override
    //            public void onMoveDragged(int index) {
    //                hideOptionsColumns();
    //            }
    //
    //        });
    //        layoutBackgroundColumnsBar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    //            @Override
    //            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    //                showActionBarIndicatorAndMovePager(position);
    //            }
    //        });

    imgBarAvatar = (ImageView) findViewById(R.id.tweettopics_bar_avatar);
    imgBarAvatarBg = (ImageView) findViewById(R.id.tweettopics_bar_avatar_bg);
    imgBarCounter = (TextView) findViewById(R.id.tweettopics_bar_counter);
    imgNewStatus = (ImageView) findViewById(R.id.tweettopics_bar_new_status);
    imgNewStatus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newStatus();
        }
    });

    imgBarAvatarGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public void onLongPress(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            animateDragged();
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    });

    imgBarAvatarBg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return imgBarAvatarGestureDetector.onTouchEvent(motionEvent);
        }
    });

    refreshTheme();

    reloadBarAvatar();

    refreshActionBarColumns();

    if (goToColumnType >= 0) {
        if ((goToColumnType == TweetTopicsUtils.COLUMN_TIMELINE
                || goToColumnType == TweetTopicsUtils.COLUMN_MENTIONS
                || goToColumnType == TweetTopicsUtils.COLUMN_DIRECT_MESSAGES) && goToColumnUser >= 0) {
            openUserColumn(goToColumnUser, goToColumnType);
        }
        if (goToColumnType == TweetTopicsUtils.COLUMN_SEARCH && goToColumnSearch > 0) {
            openSearchColumn(new Entity("search", goToColumnSearch));
        }
    } else if (goToColumnType == TweetTopicsUtils.COLUMN_MY_ACTIVITY) {
    } else if (goToColumnPosition > 0) {
        goToColumn((int) goToColumnPosition, false, selectedTweetId);
    } else if (positionFromSensor >= 0) {
        goToColumn(positionFromSensor, false, selectedTweetId);
    } else {
        int col = fragmentAdapter.getPositionColumnActive();
        if (col > 0)
            goToColumn(col, false, selectedTweetId);
    }

    // comprobar si hay que proponer ir al market

    int access_count = PreferenceUtils.getApplicationAccessCount(this);

    if (access_count <= 20) {
        if (access_count == 20) {
            try {
                AlertDialog dialog = DialogUtils.RateAppDialogBuilder.create(this);
                dialog.show();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        PreferenceUtils.setApplicationAccessCount(this, access_count + 1);
    }

    PreferenceUtils.showChangeLog(this, true);

}

From source file:org.apache.hadoop.mapreduce.v2.hs.JobHistoryServer.java

static JobHistoryServer launchJobHistoryServer(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
    StringUtils.startupShutdownMessage(JobHistoryServer.class, args, LOG);
    JobHistoryServer jobHistoryServer = null;
    try {/*from  w  w  w .j a  va  2s  . c  o m*/
        jobHistoryServer = new JobHistoryServer();
        ShutdownHookManager.get().addShutdownHook(new CompositeServiceShutdownHook(jobHistoryServer),
                SHUTDOWN_HOOK_PRIORITY);
        YarnConfiguration conf = new YarnConfiguration(new JobConf());
        new GenericOptionsParser(conf, args);
        jobHistoryServer.init(conf);
        jobHistoryServer.start();
    } catch (Throwable t) {
        LOG.fatal("Error starting JobHistoryServer", t);
        ExitUtil.terminate(-1, "Error starting JobHistoryServer");
    }
    return jobHistoryServer;
}

From source file:net.technicpack.launcher.LauncherMain.java

private static void setupLogging(LauncherDirectories directories, ResourceLoader resources) {
    System.out.println("Setting up logging");
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(directories.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();/*ww  w . j  a  v  a  2s . c  o m*/
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new BuildLogFormatter(resources.getLauncherBuild()));

    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.addHandler(fileHandler);
    logger.setUseParentHandlers(false);

    LauncherMain.consoleFrame = new ConsoleFrame(2500, resources.getImage("icon.png"));
    Console console = new Console(LauncherMain.consoleFrame, resources.getLauncherBuild());

    logger.addHandler(new ConsoleHandler(console));

    System.setOut(new PrintStream(new LoggerOutputStream(console, Level.INFO, logger), true));
    System.setErr(new PrintStream(new LoggerOutputStream(console, Level.SEVERE, logger), true));

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "Unhandled Exception in " + t, e);

            //                if (errorDialog == null) {
            //                    LauncherFrame frame = null;
            //
            //                    try {
            //                        frame = Launcher.getFrame();
            //                    } catch (Exception ex) {
            //                        //This can happen if we have a very early crash- before Launcher initializes
            //                    }
            //
            //                    errorDialog = new ErrorDialog(frame, e);
            //                    errorDialog.setVisible(true);
            //                }
        }
    });
}