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:com.mparticle.internal.ConfigManager.java

public void enableUncaughtExceptionLogging(boolean userTriggered) {
    if (null == mExHandler) {
        Thread.UncaughtExceptionHandler currentUncaughtExceptionHandler = Thread
                .getDefaultUncaughtExceptionHandler();
        if (!(currentUncaughtExceptionHandler instanceof ExceptionHandler)) {
            mExHandler = new ExceptionHandler(currentUncaughtExceptionHandler);
            Thread.setDefaultUncaughtExceptionHandler(mExHandler);
            if (userTriggered) {
                setLogUnhandledExceptions(true);
            }//w ww  .  j a  va  2  s.  c  o  m
        }
    }
}

From source file:org.geometerplus.android.fbreader.FBReader.java

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));

    bindService(new Intent(this, DataService.class), DataConnection, DataService.BIND_AUTO_CREATE);

    final Config config = Config.Instance();
    config.runOnConnect(new Runnable() {
        public void run() {
            config.requestAllValuesForGroup("Options");
            config.requestAllValuesForGroup("Style");
            config.requestAllValuesForGroup("LookNFeel");
            config.requestAllValuesForGroup("Fonts");
            config.requestAllValuesForGroup("Colors");
            config.requestAllValuesForGroup("Files");
        }/*from w w w .ja  va  2  s  . c  o m*/
    });

    final ZLAndroidLibrary zlibrary = getZLibrary();
    myShowStatusBarFlag = zlibrary.ShowStatusBarOption.getValue();

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    myRootView = (RelativeLayout) findViewById(R.id.root_view);
    myMainView = (ZLAndroidWidget) findViewById(R.id.main_view);
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

    zlibrary.setActivity(this);

    myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
    if (myFBReaderApp == null) {
        myFBReaderApp = new FBReaderApp(new BookCollectionShadow());
    }
    getCollection().bindToService(this, null);
    myBook = null;

    myFBReaderApp.setWindow(this);
    myFBReaderApp.initWindow();

    myFBReaderApp.setExternalFileOpener(new ExternalFileOpener(this));

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            myShowStatusBarFlag ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (myFBReaderApp.getPopupById(TextSearchPopup.ID) == null) {
        new TextSearchPopup(myFBReaderApp);
    }
    if (myFBReaderApp.getPopupById(NavigationPopup.ID) == null) {
        new NavigationPopup(myFBReaderApp);
    }
    if (myFBReaderApp.getPopupById(SelectionPopup.ID) == null) {
        new SelectionPopup(myFBReaderApp);
    }

    myFBReaderApp.addAction(ActionCode.SHOW_LIBRARY, new ShowLibraryAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_PREFERENCES, new ShowPreferencesAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_BOOK_INFO, new ShowBookInfoAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_TOC, new ShowTOCAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_BOOKMARKS, new ShowBookmarksAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_NETWORK_LIBRARY, new ShowNetworkLibraryAction(this, myFBReaderApp));

    myFBReaderApp.addAction(ActionCode.SHOW_MENU, new ShowMenuAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHOW_NAVIGATION, new ShowNavigationAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SEARCH, new SearchAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SHARE_BOOK, new ShareBookAction(this, myFBReaderApp));

    myFBReaderApp.addAction(ActionCode.SELECTION_SHOW_PANEL, new SelectionShowPanelAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SELECTION_HIDE_PANEL, new SelectionHidePanelAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SELECTION_COPY_TO_CLIPBOARD,
            new SelectionCopyAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SELECTION_SHARE, new SelectionShareAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SELECTION_TRANSLATE, new SelectionTranslateAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.SELECTION_BOOKMARK, new SelectionBookmarkAction(this, myFBReaderApp));

    myFBReaderApp.addAction(ActionCode.PROCESS_HYPERLINK, new ProcessHyperlinkAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.OPEN_VIDEO, new OpenVideoAction(this, myFBReaderApp));

    myFBReaderApp.addAction(ActionCode.SHOW_CANCEL_MENU, new ShowCancelMenuAction(this, myFBReaderApp));

    myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_SYSTEM,
            new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_SYSTEM));
    myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_SENSOR,
            new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_SENSOR));
    myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_PORTRAIT,
            new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_PORTRAIT));
    myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_LANDSCAPE,
            new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_LANDSCAPE));
    if (ZLibrary.Instance().supportsAllOrientations()) {
        myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_REVERSE_PORTRAIT,
                new SetScreenOrientationAction(this, myFBReaderApp,
                        ZLibrary.SCREEN_ORIENTATION_REVERSE_PORTRAIT));
        myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
                new SetScreenOrientationAction(this, myFBReaderApp,
                        ZLibrary.SCREEN_ORIENTATION_REVERSE_LANDSCAPE));
    }
    myFBReaderApp.addAction(ActionCode.OPEN_WEB_HELP, new OpenWebHelpAction(this, myFBReaderApp));
    myFBReaderApp.addAction(ActionCode.INSTALL_PLUGINS, new InstallPluginsAction(this, myFBReaderApp));

    final Intent intent = getIntent();
    final String action = intent.getAction();

    myOpenBookIntent = intent;
    if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
        if (FBReaderIntents.Action.CLOSE.equals(action)) {
            myCancelIntent = intent;
            myOpenBookIntent = null;
        } else if (FBReaderIntents.Action.PLUGIN_CRASH.equals(action)) {
            myFBReaderApp.ExternalBook = null;
            myOpenBookIntent = null;
            getCollection().bindToService(this, new Runnable() {
                public void run() {
                    myFBReaderApp.openBook(null, null, null, FBReader.this);
                }
            });
        }
    }
}

From source file:edu.jhu.hlt.concrete.ingesters.bolt.BoltForumPostIngester.java

public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    if (args.length < 2) {
        LOGGER.info("Usage: {} {} {} {}", BoltForumPostIngester.class.getName(), "/path/to/output/folder",
                "/path/to/bolt/.xml/file", "<additional/xml/file/paths>");
        System.exit(1);//from w w  w  .jav a  2 s .c o m
    }

    Path outPath = Paths.get(args[0]);
    Optional.ofNullable(outPath.getParent()).ifPresent(p -> {
        if (!Files.exists(p))
            try {
                Files.createDirectories(p);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
    });

    if (!Files.isDirectory(outPath)) {
        LOGGER.error("Output path must be a directory.");
        System.exit(1);
    }

    BoltForumPostIngester ing = new BoltForumPostIngester();
    for (int i = 1; i < args.length; i++) {
        Path lp = Paths.get(args[i]);
        LOGGER.info("On path: {}", lp.toString());
        try {
            Communication c = ing.fromCharacterBasedFile(lp);
            new WritableCommunication(c).writeToFile(outPath.resolve(c.getId() + ".comm"), true);
        } catch (IngestException | ConcreteException e) {
            LOGGER.error("Caught exception during ingest on file: " + args[i], e);
        }
    }
}

From source file:com.mparticle.internal.ConfigManager.java

public void disableUncaughtExceptionLogging(boolean userTriggered) {
    if (null != mExHandler) {
        Thread.UncaughtExceptionHandler currentUncaughtExceptionHandler = Thread
                .getDefaultUncaughtExceptionHandler();
        if (currentUncaughtExceptionHandler instanceof ExceptionHandler) {
            Thread.setDefaultUncaughtExceptionHandler(mExHandler.getOriginalExceptionHandler());
            mExHandler = null;// w  w  w. j  a  va 2s  .c  om
            if (userTriggered) {
                setLogUnhandledExceptions(false);
            }
        }
    }
}

From source file:org.apache.tajo.worker.TajoWorker.java

public static void main(String[] args) throws Exception {
    Thread.setDefaultUncaughtExceptionHandler(new TajoUncaughtExceptionHandler());
    StringUtils.startupShutdownMessage(TajoWorker.class, args, LOG);

    TajoConf tajoConf = new TajoConf();
    tajoConf.addResource(new Path(TajoConstants.SYSTEM_CONF_FILENAME));

    try {/*from   w  w  w. ja v  a2 s  .c  o m*/
        TajoWorker tajoWorker = new TajoWorker();
        tajoWorker.startWorker(tajoConf, args);
    } catch (Throwable t) {
        LOG.fatal("Error starting TajoWorker", t);
        System.exit(-1);
    }
}

From source file:org.acra.ErrorReporter.java

/**
 * Can only be constructed from within this class.
 *
 * @param context//from  w ww. ja v  a2  s. c o m
 *            Context for the application in which ACRA is running.
 * @param prefs
 *            SharedPreferences used by ACRA.
 * @param enabled
 *            Whether this ErrorReporter should capture Exceptions and
 *            forward their reports.
 */
ErrorReporter(Application context, SharedPreferences prefs, boolean enabled) {

    this.mContext = context;
    this.prefs = prefs;
    this.enabled = enabled;

    // Store the initial Configuration state.
    // This is expensive to gather, so only do so if we plan to report it.
    final String initialConfiguration;
    if (ACRA.getConfig().getReportFields().contains(ReportField.INITIAL_CONFIGURATION)) {
        initialConfiguration = ConfigurationCollector.collectConfiguration(mContext);
    } else {
        initialConfiguration = null;
    }

    // Sets the application start date.
    // This will be included in the reports, will be helpful compared to
    // user_crash date.
    final Calendar appStartDate = new GregorianCalendar();

    if (Compatibility.getAPILevel() >= Compatibility.VERSION_CODES.ICE_CREAM_SANDWICH) { // ActivityLifecycleCallback
        // only available for API14+
        ApplicationHelper.registerActivityLifecycleCallbacks(context, new ActivityLifecycleCallbacksCompat() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityCreated " + activity.getClass());
                if (!(activity instanceof BaseCrashReportDialog)) {
                    // Ignore CrashReportDialog because we want the last
                    // application Activity that was started so that we can
                    // explicitly kill it off.
                    lastActivityCreated = new WeakReference<Activity>(activity);
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityStarted " + activity.getClass());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityResumed " + activity.getClass());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityPaused " + activity.getClass());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityStopped " + activity.getClass());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.i(LOG_TAG, "onActivitySaveInstanceState " + activity.getClass());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.i(LOG_TAG, "onActivityDestroyed " + activity.getClass());
            }
        });
    }

    crashReportDataFactory = new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration);

    // If mDfltExceptionHandler is not null, initialization is already done.
    // Don't do it twice to avoid losing the original handler.
    mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}

From source file:com.hijacker.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from  w  ww  . j  a  v  a  2 s . co m
        public void uncaughtException(Thread thread, Throwable throwable) {
            throwable.printStackTrace();
            String stackTrace = "";
            stackTrace += throwable.getMessage() + '\n';
            for (int i = 0; i < throwable.getStackTrace().length; i++) {
                stackTrace += throwable.getStackTrace()[i].toString() + '\n';
            }

            Intent intent = new Intent();
            intent.setAction("com.hijacker.SendLogActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("exception", stackTrace);
            startActivity(intent);

            finish();
            System.exit(1);
        }
    });
    adapter = new MyListAdapter(); //ALWAYS BEFORE setContentView AND setup(), can't stress it enough...
    adapter.setNotifyOnChange(true);
    custom_action_adapter = new CustomActionAdapter();
    custom_action_adapter.setNotifyOnChange(true);
    file_explorer_adapter = new FileExplorerAdapter();
    file_explorer_adapter.setNotifyOnChange(true);
    setContentView(R.layout.activity_main);
    setSupportActionBar((Toolbar) findViewById(R.id.my_toolbar));

    //Google AppIndex
    client = new GoogleApiClient.Builder(MainActivity.this).addApi(AppIndex.API).build();

    //fullSetup();
    new SetupTask().execute();
}

From source file:VASSAL.launch.ModuleManager.java

public ModuleManager(ServerSocket serverSocket, long key, FileOutputStream lout, FileLock lock)
        throws IOException {

    if (instance != null)
        throw new IllegalStateException();
    instance = this;

    this.serverSocket = serverSocket;
    this.key = key;

    // we hang on to these to prevent the lock from being lost
    this.lout = lout;
    this.lock = lock;

    // truncate the errorLog
    final File errorLog = new File(Info.getHomeDir(), "errorLog");
    new FileOutputStream(errorLog).close();

    final StartUp start = SystemUtils.IS_OS_MAC_OSX ? new ModuleManagerMacOSXStartUp() : new StartUp();

    start.startErrorLog();//  w  w  w.  j  a  v a  2 s  .c  o  m

    // log everything which comes across our stderr
    System.setErr(new PrintStream(new LoggedOutputStream(), true));

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

    start.initSystemProperties();

    // check whether we need to migrate pre-3.2 preferences
    final File oldprefs = new File(System.getProperty("user.home"), "VASSAL/Preferences");
    if (oldprefs.exists()) {
        final File newprefs = new File(Info.getHomeDir(), "Preferences");
        if (!newprefs.exists()) {
            FileUtils.copyFile(oldprefs, newprefs);
        }
    }

    if (SystemUtils.IS_OS_MAC_OSX)
        new MacOSXMenuManager();
    else
        new ModuleManagerMenuManager();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            launch();
        }
    });

    // ModuleManagerWindow.getInstance() != null now, so listen on the socket
    new Thread(new SocketListener(serverSocket), "socket listener").start();

    final Prefs globalPrefs = Prefs.getGlobalPrefs();

    // determine when we should next check on the current version of VASSAL
    final LongConfigurer nextVersionCheckConfig = new LongConfigurer(NEXT_VERSION_CHECK, null, -1L);
    globalPrefs.addOption(null, nextVersionCheckConfig);

    long nextVersionCheck = nextVersionCheckConfig.getLongValue(-1L);
    if (nextVersionCheck < System.currentTimeMillis()) {
        new UpdateCheckRequest().execute();
    }

    // set the time for the next version check
    if (nextVersionCheck == -1L) {
        // this was our first check; randomly check after 0-10 days to
        // to spread version checks evenly over a 10-day period
        nextVersionCheck = System.currentTimeMillis() + (long) (Math.random() * 10 * 86400000);
    } else {
        // check again in 10 days
        nextVersionCheck += 10 * 86400000;
    }

    nextVersionCheckConfig.setValue(nextVersionCheck);

    // FIXME: the importer heap size configurers don't belong here
    // the initial heap size for the module importer
    final IntConfigurer initHeapConf = new IntConfigurer(INITIAL_HEAP,
            Resources.getString("GlobalOptions.initial_heap"), //$NON-NLS-1$
            Integer.valueOf(256));
    globalPrefs.addOption("Importer", initHeapConf);

    // the maximum heap size for the module importer
    final IntConfigurer maxHeapConf = new IntConfigurer(MAXIMUM_HEAP,
            Resources.getString("GlobalOptions.maximum_heap"), //$NON-NLS-1$
            Integer.valueOf(512));
    globalPrefs.addOption("Importer", maxHeapConf);

    /*
        final InetAddress lo = InetAddress.getByName(null);
        signalServerSocket = new ServerSocket(0, 0, lo);
            
        final MultiplexedSignalSource mss = new DefaultMultiplexedSignalSource();
        final SignalDispatcher sd = new SignalDispatcher(mss);
            
        sd.addEventListener(
          AbstractLaunchAction.NotifyOpenModuleOk.class,
          new AbstractLaunchAction.NotifyOpenModuleOkListener()
        );
            
        sd.addEventListener(
          AbstractLaunchAction.NotifyNewModuleOk.class,
          new AbstractLaunchAction.NotifyNewModuleOkListener()
        );
            
        sd.addEventListener(
          AbstractLaunchAction.NotifyImportModuleOk.class,
          new AbstractLaunchAction.NotifyImportModuleOkListener()
        );
            
        sd.addEventListener(
          AbstractLaunchAction.NotifyOpenModuleFailed.class,
          new AbstractLaunchAction.NotifyOpenModuleFailedListener()
        );
            
        sd.addEventListener(
          AbstractLaunchAction.NotifySaveFileOk.class,
          new AbstractLaunchAction.NotifySaveFileOkListener()
        );
            
        final SignalSender ss = new SignalSender();
            
        signalServer = new SignalServer(signalServerSocket, mss, sd, ss);
        new Thread(signalServer, "comm server").start();
    */
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public Quorrabot(String username, String oauth, String apioauth, String clientid, String channelName,
        String owner, int baseport, InetAddress ip, String hostname, int port, double msglimit30,
        String datastore, String datastoreconfig, String youtubekey, String gamewispauth,
        String gamewisprefresh, String twitchalertstoken, String lastfmuser, String tpetoken,
        String twittertoken, String twittertokensecret, String streamtiptoken, String streamtipid,
        boolean webenable, String webauth, String webauthro, boolean musicenable, boolean usehttps,
        String timeZone, String mySqlHost, String mySqlPort, String mySqlConn, String mySqlPass,
        String mySqlUser, String mySqlName, String keystorepath, FollowersCache followersCache,
        ChannelHostCache hostCache, ChannelUsersCache channelUsersCache, SubscribersCache subscribersCache,
        String discordToken, String discordMainChannel) {
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    com.gmt2001.Console.out.println();
    com.gmt2001.Console.out.println(botVersion());
    com.gmt2001.Console.out.println(botRevision());
    com.gmt2001.Console.out.println("www.quorrabot.com");
    com.gmt2001.Console.out.println();
    com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir"));

    interactive = System.getProperty("interactive") != null;

    this.username = username;
    this.oauth = oauth;
    this.apioauth = apioauth;
    this.ownerName = owner;
    this.channelName = channelName.toLowerCase();
    this.baseport = baseport;
    this.ip = ip;
    this.datastore = datastore;
    this.datastoreconfig = datastoreconfig;
    this.hostCache = ChannelHostCache.instance(this.ownerName);
    this.subscribersCache = SubscribersCache.instance(this.ownerName);
    this.channelUsersCache = ChannelUsersCache.instance(this.ownerName);
    this.followersCache = FollowersCache.instance(this.ownerName);

    this.youtubekey = youtubekey;
    if (!timeZone.isEmpty()) {
        this.timeZone = timeZone;
    } else {/*w  w  w. j  av a  2s  .  co  m*/
        this.timeZone = "EDT";
    }

    if (!youtubekey.isEmpty()) {
        YouTubeAPIv3.instance().SetAPIKey(youtubekey);
    }

    this.discordToken = discordToken;
    this.discordMainChannel = discordMainChannel;

    this.gamewispauth = gamewispauth;
    this.gamewisprefresh = gamewisprefresh;
    this.twitchalertstoken = twitchalertstoken;
    if (!twitchalertstoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(twitchalertstoken, "twitchalerts");
    }
    this.lastfmuser = lastfmuser;
    if (!lastfmuser.isEmpty()) {
        LastFMAPI.instance().SetUsername(lastfmuser);
    }
    this.tpetoken = tpetoken;
    if (!tpetoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(tpetoken, "tpestream");
    }
    this.streamtiptoken = streamtiptoken;
    if (!streamtiptoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(streamtiptoken, "streamtip");
    }
    this.streamtipid = streamtipid;
    if (!streamtipid.isEmpty()) {
        DonationHandlerAPI.instance().SetClientID(streamtipid, "streamtip");
    }
    this.twittertoken = twittertoken;
    this.twittertokensecret = twittertokensecret;
    if (!twittertoken.isEmpty() || !twittertokensecret.isEmpty()) {
        TwitterAPI.instance().loadAccessToken(twittertoken, twittertokensecret);
    }

    if (msglimit30 != 0) {
        Quorrabot.msglimit30 = msglimit30;
    } else {
        Quorrabot.msglimit30 = 18.75;
    }

    this.mySqlName = mySqlName;
    this.mySqlUser = mySqlUser;
    this.mySqlPass = mySqlPass;
    this.mySqlConn = mySqlConn;
    this.mySqlHost = mySqlHost;
    this.mySqlPort = mySqlPort;

    this.webenable = webenable;
    this.musicenable = musicenable;
    this.usehttps = usehttps;
    this.keystorepath = keystorepath;
    this.webauth = webauth;
    this.webauthro = webauthro;

    if (clientid.length() == 0) {
        this.clientid = "pcaalhorck7ryamyg6ijd5rtnls5pjl";
    } else {
        this.clientid = clientid;
    }

    /**
     * Create a map for multiple channels.
     */
    channels = new HashMap<>();

    /**
     * Create a map for multiple sessions.
     */
    sessions = new HashMap<>();

    /**
     * Create a map for multiple oauth tokens.
     */
    apiOAuths = new HashMap<>();

    rng = new SecureRandom();
    pollResults = new TreeMap<>();
    voters = new TreeSet<>();

    if (hostname.isEmpty()) {
        this.hostname = "irc.chat.twitch.tv";
        this.port = 6667;
    } else {
        this.hostname = hostname;
        this.port = port;
    }

    if (msglimit30 > 0) {
        this.msglimit30 = msglimit30;
    } else {
        this.msglimit30 = 18.75;
    }

    if (datastore.equalsIgnoreCase("IniStore")) {
        dataStoreObj = IniStore.instance();
    } else if (datastore.equalsIgnoreCase("mysqlstore")) {
        dataStoreObj = MySQLStore.instance();
        if (this.mySqlPort.isEmpty()) {
            this.mySqlConn = "jdbc:mariadb://" + this.mySqlHost + "/" + this.mySqlName;
        } else {
            this.mySqlConn = "jdbc:mariadb://" + this.mySqlHost + ":" + this.mySqlPort + "/" + this.mySqlName;
        }

        /**
         * Check to see if we can create a connection
         */
        if (dataStoreObj.CreateConnection(this.mySqlConn, this.mySqlUser, this.mySqlPass) == null) {
            com.gmt2001.Console.out
                    .println("Could not create a connection with MySql. QuorraBot now shutting down...");
            System.exit(0);
        }

        if (IniStore.instance().GetFileList().length > 0) {
            ini2MySql(true);
        } else if (SqliteStore.instance().GetFileList().length > 0) {
            sqlite2MySql();
        }
    } else {
        dataStoreObj = SqliteStore.instance();
        if (datastore.isEmpty() && IniStore.instance().GetFileList().length > 0
                && SqliteStore.instance().GetFileList().length == 0) {
            ini2sqlite(true);
        }
    }
    TwitchAPIv3.instance().SetClientID(this.clientid);
    TwitchAPIv3.instance().SetOAuth(apioauth);

    this.init();

    this.tcechannel = Channel.instance("tcechannel", this.ownerName, this.apioauth, EventBus.instance(),
            this.ownerName);
    //Give the bot some time in between sessions so to be sure the stream channel connects last
    //This needs to be done in order for the parser to detect which chat channel to use
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
        //
    }
    this.channel = Channel.instance(this.channelName, this.username, this.oauth, EventBus.instance(),
            this.ownerName);

    if (SystemUtils.IS_OS_LINUX && !interactive) {
        try {
            java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
                    .getRuntimeMXBean();
            int pid = Integer.parseInt(runtime.getName().split("@")[0]);

            File f = new File("/var/run/QuorraBot." + this.username.toLowerCase() + ".pid");

            try (FileOutputStream fs = new FileOutputStream(f, false)) {
                PrintStream ps = new PrintStream(fs);
                ps.print(pid);
            }
            f.deleteOnExit();
        } catch (SecurityException | IllegalArgumentException | IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

}

From source file:openscience.crowdsource.video.experiments.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    setContentView(R.layout.activity_main);
    setTaskBarColored(this);

    Button consoleButton = (Button) findViewById(R.id.btn_consoleMain);
    consoleButton.setOnClickListener(new View.OnClickListener() {
        @Override/* ww w .  j av  a2s  . c  o m*/
        public void onClick(View v) {
            Intent logIntent = new Intent(MainActivity.this, ConsoleActivity.class);
            startActivity(logIntent);
        }
    });

    Button infoButton = (Button) findViewById(R.id.btn_infoMain);
    infoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent aboutIntent = new Intent(MainActivity.this, InfoActivity.class);
            startActivity(aboutIntent);
        }
    });

    initConsole();

    startStopCam = (Button) findViewById(R.id.btn_capture);
    startStopCam.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            createDirIfNotExist(externalSDCardOpenscienceTmpPath);
            String takenPictureFilPath = String.format(
                    externalSDCardOpenscienceTmpPath + File.separator + "%d.jpg", System.currentTimeMillis());
            AppConfigService.updateActualImagePath(takenPictureFilPath);
            Intent aboutIntent = new Intent(MainActivity.this, CaptureActivity.class);
            startActivity(aboutIntent);
        }
    });

    recognize = (Button) findViewById(R.id.suggest);
    recognize.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final RecognitionScenario recognitionScenario = RecognitionScenarioService
                    .getSelectedRecognitionScenario();
            if (recognitionScenario == null) {
                AppLogger.logMessage(" Please select an image recognition scenario first! \n");
                return;
            }

            if (recognitionScenario.getState() == RecognitionScenario.State.NEW) {
                AlertDialog.Builder clarifyDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                clarifyDialogBuilder
                        .setMessage(Html.fromHtml("Please download this scenario first or select another one."))
                        .setCancelable(false)
                        .setPositiveButton("continue", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                                LoadScenarioFilesAsyncTask loadScenarioFilesAsyncTask = new LoadScenarioFilesAsyncTask();
                                loadScenarioFilesAsyncTask.execute(recognitionScenario);
                                recognitionScenario.setLoadScenarioFilesAsyncTask(loadScenarioFilesAsyncTask);
                                Intent mainIntent = new Intent(MainActivity.this, ScenariosActivity.class);
                                startActivity(mainIntent);
                            }
                        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                final AlertDialog clarifyDialog = clarifyDialogBuilder.create();
                clarifyDialog.show();
                return;
            }

            if (recognitionScenario.getState() == RecognitionScenario.State.DOWNLOADING_IN_PROGRESS) {
                AlertDialog.Builder clarifyDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                clarifyDialogBuilder.setMessage(Html.fromHtml("Download is in progress, please wait ..."))
                        .setCancelable(false)
                        .setPositiveButton("continue", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                final AlertDialog clarifyDialog = clarifyDialogBuilder.create();
                clarifyDialog.show();
                return;
            }

            if (isCameraStarted) {
                captureImageFromCameraPreviewAndPredict(true);
                return;
            }

            // Call prediction
            predictImage(AppConfigService.getActualImagePath());
        }
    });

    final View selectedScenarioTopBar = findViewById(R.id.selectedScenarioTopBar);
    selectedScenarioTopBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent selectScenario = new Intent(MainActivity.this, ScenariosActivity.class);
            startActivity(selectScenario);

        }
    });
    selectedScenarioTopBar.setEnabled(false);

    final TextView selectedScenarioText = (TextView) findViewById(R.id.selectedScenarioText);
    selectedScenarioText.setText(PRELOADING_TEXT);

    imageView = (ImageView) findViewById(R.id.imageView1);

    btnOpenImage = (Button) findViewById(R.id.btn_ImageOpen);
    btnOpenImage.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, REQUEST_IMAGE_SELECT);
        }
    });

    // Lazy preload scenarios
    RecognitionScenarioService.initRecognitionScenariosAsync(new RecognitionScenarioService.ScenariosUpdater() {
        @Override
        public void update() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RecognitionScenario selectedRecognitionScenario = RecognitionScenarioService
                            .getSelectedRecognitionScenario();
                    selectedScenarioText.setText(selectedRecognitionScenario.getTitle());
                    updateViewFromState();
                }
            });
        }
    });

    SharedPreferences sharedPreferences = getSharedPreferences(
            AppConfigService.CROWDSOURCE_VIDEO_EXPERIMENTS_ON_ANDROID_PREFERENCES, MODE_PRIVATE);
    if (sharedPreferences.getBoolean(AppConfigService.SHARED_PREFERENCES, true)) {
        AppLogger.logMessage(welcome);
        sharedPreferences.edit().putBoolean(AppConfigService.SHARED_PREFERENCES, false).apply();
    }

    this.glSurfaceView = new GLSurfaceView(this);
    this.glSurfaceView.setRenderer(this);
    ((ViewGroup) imageView.getParent()).addView(this.glSurfaceView);

    initAppConfig(this);

    client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

    final TextView resultPreviewText = (TextView) findViewById(R.id.resultPreviewtText);
    resultPreviewText.setText(AppConfigService.getPreviewRecognitionText());
    AppConfigService.registerPreviewRecognitionText(new AppConfigService.Updater() {
        @Override
        public void update(final String message) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    View imageButtonsBar = (View) findViewById(R.id.imageButtonBar);
                    imageButtonsBar.setVisibility(View.VISIBLE);
                    imageButtonsBar.setEnabled(true);
                    resultPreviewText.setText(message);
                }
            });

        }
    });
    updateViewFromState();
}