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:io.smartspaces.launcher.bootstrap.SmartSpacesFrameworkBootstrap.java

/**
 * Set up the default exception handler.
 *///w ww . j av a2s .co m
private void setupExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            loggingProvider.getLog()
                    .error(String.format("Caught previously uncaught exception from thread %s", t), e);
        }
    });
}

From source file:org.apache.hadoop.yarn.server.nodemanager.NodeManager.java

public static void main(String[] args) throws IOException {
    Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
    StringUtils.startupShutdownMessage(NodeManager.class, args, LOG);
    NodeManager nodeManager = new NodeManager();
    Configuration conf = new YarnConfiguration();
    new GenericOptionsParser(conf, args);
    nodeManager.initAndStartNodeManager(conf, false);
}

From source file:org.apache.hadoop.yarn.service.launcher.ServiceLauncher.java

/**
 * The real main function, which takes the arguments as a list
 * arg 0 must be the service classname// w  w  w  .  j ava  2s.c o m
 * @param argsList the list of arguments
 */
public static void serviceMain(List<String> argsList) {
    if (argsList.isEmpty()) {
        exitWithMessage(EXIT_USAGE, USAGE_MESSAGE);
    } else {
        String serviceClassName = argsList.get(0);

        if (LOG.isDebugEnabled()) {
            LOG.debug(startupShutdownMessage(serviceClassName, argsList));
        }
        Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());

        ServiceLauncher serviceLauncher = new ServiceLauncher<Service>(serviceClassName);
        serviceLauncher.launchServiceAndExit(argsList);
    }
}

From source file:jsprit.core.algorithm.io.VehicleRoutingAlgorithms.java

private static VehicleRoutingAlgorithm readAndCreateAlgorithm(final VehicleRoutingProblem vrp,
        XMLConfiguration config, int nuOfThreads, final SolutionCostCalculator solutionCostCalculator,
        final StateManager stateManager, ConstraintManager constraintManager,
        boolean addDefaultCostCalculators) {
    // map to store constructed modules
    TypedMap definedClasses = new TypedMap();

    // algorithm listeners
    Set<PrioritizedVRAListener> algorithmListeners = new HashSet<PrioritizedVRAListener>();

    // insertion listeners
    List<InsertionListener> insertionListeners = new ArrayList<InsertionListener>();

    //threading/*from w w w.java 2  s. co  m*/
    final ExecutorService executorService;
    if (nuOfThreads > 0) {
        log.debug("setup executor-service with " + nuOfThreads + " threads");
        executorService = Executors.newFixedThreadPool(nuOfThreads);
        algorithmListeners.add(new PrioritizedVRAListener(Priority.LOW, new AlgorithmEndsListener() {

            @Override
            public void informAlgorithmEnds(VehicleRoutingProblem problem,
                    Collection<VehicleRoutingProblemSolution> solutions) {
                log.debug("shutdown executor-service");
                executorService.shutdown();
            }
        }));
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread arg0, Throwable arg1) {
                System.err.println(arg1.toString());
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (!executorService.isShutdown()) {
                    System.err.println("shutdowHook shuts down executorService");
                    executorService.shutdown();
                }
            }
        });
    } else
        executorService = null;

    //create fleetmanager
    final VehicleFleetManager vehicleFleetManager = createFleetManager(vrp);

    String switchString = config.getString("construction.insertion.allowVehicleSwitch");
    final boolean switchAllowed;
    if (switchString != null) {
        switchAllowed = Boolean.parseBoolean(switchString);
    } else
        switchAllowed = true;
    ActivityTimeTracker.ActivityPolicy activityPolicy;
    if (stateManager.timeWindowUpdateIsActivated()) {
        UpdateVehicleDependentPracticalTimeWindows timeWindowUpdater = new UpdateVehicleDependentPracticalTimeWindows(
                stateManager, vrp.getTransportCosts());
        timeWindowUpdater
                .setVehiclesToUpdate(new UpdateVehicleDependentPracticalTimeWindows.VehiclesToUpdate() {
                    Map<VehicleTypeKey, Vehicle> uniqueTypes = new HashMap<VehicleTypeKey, Vehicle>();

                    @Override
                    public Collection<Vehicle> get(VehicleRoute vehicleRoute) {
                        if (uniqueTypes.isEmpty()) {
                            for (Vehicle v : vrp.getVehicles()) {
                                if (!uniqueTypes.containsKey(v.getVehicleTypeIdentifier())) {
                                    uniqueTypes.put(v.getVehicleTypeIdentifier(), v);
                                }
                            }
                        }
                        Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
                        vehicles.addAll(uniqueTypes.values());
                        return vehicles;
                    }
                });
        stateManager.addStateUpdater(timeWindowUpdater);
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS;
    } else {
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_ARRIVED;
    }
    stateManager.addStateUpdater(new UpdateActivityTimes(vrp.getTransportCosts(), activityPolicy));
    stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(),
            stateManager, activityPolicy));

    final SolutionCostCalculator costCalculator;
    if (solutionCostCalculator == null)
        costCalculator = getDefaultCostCalculator(stateManager);
    else
        costCalculator = solutionCostCalculator;

    PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp, vehicleFleetManager,
            stateManager, constraintManager);
    //construct initial solution creator
    final InsertionStrategy initialInsertionStrategy = createInitialSolution(config, vrp, vehicleFleetManager,
            stateManager, algorithmListeners, definedClasses, executorService, nuOfThreads, costCalculator,
            constraintManager, addDefaultCostCalculators);
    if (initialInsertionStrategy != null)
        prettyAlgorithmBuilder.constructInitialSolutionWith(initialInsertionStrategy, costCalculator);

    //construct algorithm, i.e. search-strategies and its modules
    int solutionMemory = config.getInt("strategy.memory");
    List<HierarchicalConfiguration> strategyConfigs = config
            .configurationsAt("strategy.searchStrategies.searchStrategy");
    for (HierarchicalConfiguration strategyConfig : strategyConfigs) {
        String name = getName(strategyConfig);
        SolutionAcceptor acceptor = getAcceptor(strategyConfig, vrp, algorithmListeners, definedClasses,
                solutionMemory);
        SolutionSelector selector = getSelector(strategyConfig, vrp, algorithmListeners, definedClasses);

        SearchStrategy strategy = new SearchStrategy(name, selector, acceptor, costCalculator);
        strategy.setName(name);
        List<HierarchicalConfiguration> modulesConfig = strategyConfig.configurationsAt("modules.module");
        for (HierarchicalConfiguration moduleConfig : modulesConfig) {
            SearchStrategyModule module = buildModule(moduleConfig, vrp, vehicleFleetManager, stateManager,
                    algorithmListeners, definedClasses, executorService, nuOfThreads, constraintManager,
                    addDefaultCostCalculators);
            strategy.addModule(module);
        }
        prettyAlgorithmBuilder.withStrategy(strategy, strategyConfig.getDouble("probability"));
    }

    //construct algorithm
    VehicleRoutingAlgorithm metaAlgorithm = prettyAlgorithmBuilder.build();
    int maxIterations = getMaxIterations(config);
    if (maxIterations > -1)
        metaAlgorithm.setMaxIterations(maxIterations);

    //define prematureBreak
    PrematureAlgorithmTermination prematureAlgorithmTermination = getPrematureTermination(config,
            algorithmListeners);
    if (prematureAlgorithmTermination != null)
        metaAlgorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
    else {
        List<HierarchicalConfiguration> terminationCriteria = config
                .configurationsAt("terminationCriteria.termination");
        for (HierarchicalConfiguration terminationConfig : terminationCriteria) {
            PrematureAlgorithmTermination termination = getTerminationCriterion(terminationConfig,
                    algorithmListeners);
            if (termination != null)
                metaAlgorithm.addTerminationCriterion(termination);
        }
    }
    for (PrioritizedVRAListener l : algorithmListeners) {
        metaAlgorithm.getAlgorithmListeners().add(l);
    }
    return metaAlgorithm;
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());

    if (getPreferences().getBoolean("global", "pref_fullscreen", false)) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        IS_FULL_SCREEN = true;//from www .j  a  v a2  s.  c  o m
    } //else getWindow().addFlags(WindowManager.LayoutParams.FLAG
    else {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        IS_FULL_SCREEN = false;
    }

    IS_KEYBOARD_AVAILABLE = getContext().getResources()
            .getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY;

    loadPreferences();

    if (getPreferences().getBoolean("global", "pref_hardware_accel", true) && !BEFORE_HONEYCOMB)
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

    //mActionBarHelper = ActionBarHelper.createInstance(this);
    //mActionBarHelper.onCreate(savedInstanceState);
    if (BEFORE_HONEYCOMB) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        USE_ACTION_BAR = false;
        //} else if(isGTV()) {
        //   USE_ACTION_BAR = false;
        //   mBar = (LeftNavBarService.instance()).getLeftNavBar(this);
    } else if (!BEFORE_HONEYCOMB) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        USE_ACTION_BAR = true;
        mBar = getActionBar();
    }
    if (mBar != null) {
        if (Build.VERSION.SDK_INT >= 14)
            mBar.setHomeButtonEnabled(true);
        mBar.setDisplayUseLogoEnabled(true);
        try {
            mBar.setCustomView(R.layout.title_bar);
            mBar.setDisplayShowCustomEnabled(true);
            mBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            //ViewGroup cv = (ViewGroup)ab.getCustomView();
            //if(cv.findViewById(R.id.title_paste) != null)
            //   cv.removeView(cv.findViewById(R.id.title_paste));
            //ab.getCustomView().findViewById(R.id.title_icon).setVisibility(View.GONE);
        } catch (InflateException e) {
            Logger.LogWarning("Couldn't set up ActionBar custom view", e);
        }
    } else
        USE_ACTION_BAR = false;

    OpenFile.setTempFileRoot(new OpenFile(getFilesDir()).getChild("temp"));
    setupLoggingDb();
    handleExceptionHandler();
    getMimeTypes();
    setupFilesDb();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_fragments);
    getWindow().setBackgroundDrawableResource(R.drawable.background_holo_dark);

    try {
        upgradeViewSettings();
    } catch (Exception e) {
    }
    //try {
    showWarnings();
    //} catch(Exception e) { }

    mEvHandler.setUpdateListener(this);

    getClipboard().setClipboardUpdateListener(this);

    try {
        /*
        Signature[] sigs = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures;
        for(Signature sig : sigs)
           if(sig.toCharsString().indexOf("4465627567") > -1) // check for "Debug" in signature
              IS_DEBUG_BUILD = true;
        */
        if (IS_DEBUG_BUILD)
            IS_DEBUG_BUILD = (getPackageManager().getActivityInfo(getComponentName(),
                    PackageManager.GET_META_DATA).applicationInfo.flags
                    & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE;
        if (isBlackBerry())
            IS_DEBUG_BUILD = false;
    } catch (NameNotFoundException e1) {
    }

    handleNetworking();
    refreshCursors();

    checkWelcome();

    checkRoot();

    if (!BEFORE_HONEYCOMB) {
        boolean show_underline = true;
        if (Build.VERSION.SDK_INT < 14)
            show_underline = isGTV();
        else if (getResources().getBoolean(R.bool.large)) // ICS+ tablets
            show_underline = false;
        if (Build.VERSION.SDK_INT > 13 && !getResources().getBoolean(R.bool.large))
            show_underline = true;

        View tu = findViewById(R.id.title_underline);
        if (tu != null && !show_underline) {
            getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_shadow));
            tu.setVisibility(View.GONE);
        }

        //if(USE_ACTION_BAR)
        //   setViewVisibility(false, false, R.id.title_bar, R.id.title_underline, R.id.title_underline_2);
    }
    if (BEFORE_HONEYCOMB || !USE_ACTION_BAR)
        ViewUtils.inflateView(this, R.id.title_stub);
    if (BEFORE_HONEYCOMB)
        ViewUtils.inflateView(this, R.id.base_stub);
    setViewVisibility(false, false, R.id.title_paste, R.id.title_ops, R.id.title_log);
    setOnClicks(R.id.title_ops, //R.id.menu_global_ops_icon, R.id.menu_global_ops_text,
            R.id.title_log, R.id.title_icon, R.id.menu_more, R.id.title_paste_icon
    //,R.id.title_sort, R.id.title_view, R.id.title_up
    );
    checkTitleSeparator();
    IconContextMenu.clearInstances();

    if (findViewById(R.id.list_frag) == null)
        mSinglePane = true;
    else if (findViewById(R.id.list_frag).getVisibility() == View.GONE)
        mSinglePane = true;

    Logger.LogDebug("Looking for path");
    OpenPath path = mLastPath;
    if (savedInstanceState == null || path == null) {
        String start = getPreferences().getString("global", "pref_start", "External");

        if (savedInstanceState != null && savedInstanceState.containsKey("last")
                && !savedInstanceState.getString("last").equals(""))
            start = savedInstanceState.getString("last");

        path = FileManager.getOpenCache(start, this);
    }

    if (path == null)
        path = OpenFile.getExternalMemoryDrive(true);

    if (FileManager.checkForNoMedia(path))
        showToast(R.string.s_error_no_media, Toast.LENGTH_LONG);

    mLastPath = path;

    boolean bAddToStack = true;

    if (findViewById(R.id.content_pager_frame_stub) != null)
        ((ViewStub) findViewById(R.id.content_pager_frame_stub)).inflate();

    Logger.LogDebug("Pager inflated");

    if (fragmentManager == null) {
        fragmentManager = getSupportFragmentManager();
        fragmentManager.addOnBackStackChangedListener(this);
    }

    mLogFragment = new LogViewerFragment();

    FragmentTransaction ft = fragmentManager.beginTransaction();

    Logger.LogDebug("Creating with " + path.getPath());
    if (path instanceof OpenFile)
        new PeekAtGrandKidsTask().execute((OpenFile) path);

    initPager();
    if (handleIntent(getIntent())) {
        path = mLastPath = null;
        bAddToStack = false;
    }

    if (mViewPager != null && mViewPagerAdapter != null && path != null) {
        //mViewPagerAdapter.add(mContentFragment);
        mLastPath = null;
        changePath(path, bAddToStack, true);
        setCurrentItem(mViewPagerAdapter.getCount() - 1, false);
        restoreOpenedEditors();
    } else
        Logger.LogWarning("Nothing to show?!");

    ft.commit();

    invalidateOptionsMenu();
    initBookmarkDropdown();

    handleMediaReceiver();

    if (!getPreferences().getBoolean("global", "pref_splash", false))
        showSplashIntent(this, getPreferences().getString("global", "pref_start", "Internal"));
}

From source file:org.apache.jmeter.JMeter.java

/**
 * Takes the command line arguments and uses them to determine how to
 * startup JMeter./*w  w  w  . ja  v  a 2s .co  m*/
 * 
 * Called reflectively by {@link NewDriver#main(String[])}
 * @param args The arguments for JMeter
 */
public void start(String[] args) {
    CLArgsParser parser = new CLArgsParser(args, options);
    String error = parser.getErrorString();
    if (error == null) {// Check option combinations
        boolean gui = parser.getArgumentById(NONGUI_OPT) == null;
        boolean nonGuiOnly = parser.getArgumentById(REMOTE_OPT) != null
                || parser.getArgumentById(REMOTE_OPT_PARAM) != null
                || parser.getArgumentById(REMOTE_STOP) != null;
        if (gui && nonGuiOnly) {
            error = "-r and -R and -X are only valid in non-GUI mode";
        }
    }
    if (null != error) {
        System.err.println("Error: " + error);
        System.out.println("Usage");
        System.out.println(CLUtil.describeOptions(options).toString());
        // repeat the error so no need to scroll back past the usage to see it
        System.out.println("Error: " + error);
        return;
    }
    try {
        initializeProperties(parser); // Also initialises JMeter logging
        /*
         * The following is needed for HTTPClient.
         * (originally tried doing this in HTTPSampler2,
         * but it appears that it was done too late when running in GUI mode)
         * Set the commons logging default to Avalon Logkit, if not already defined
         */
        if (System.getProperty("org.apache.commons.logging.Log") == null) { // $NON-NLS-1$
            System.setProperty("org.apache.commons.logging.Log" // $NON-NLS-1$
                    , "org.apache.commons.logging.impl.LogKitLogger"); // $NON-NLS-1$
        }

        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                if (!(e instanceof ThreadDeath)) {
                    log.error("Uncaught exception: ", e);
                    System.err.println("Uncaught Exception " + e + ". See log file for details.");
                }
            }
        });

        log.info(JMeterUtils.getJMeterCopyright());
        log.info("Version " + JMeterUtils.getJMeterVersion());
        logProperty("java.version"); //$NON-NLS-1$
        logProperty("java.vm.name"); //$NON-NLS-1$
        logProperty("os.name"); //$NON-NLS-1$
        logProperty("os.arch"); //$NON-NLS-1$
        logProperty("os.version"); //$NON-NLS-1$
        logProperty("file.encoding"); // $NON-NLS-1$
        log.info("Max memory     =" + Runtime.getRuntime().maxMemory());
        log.info("Available Processors =" + Runtime.getRuntime().availableProcessors());
        log.info("Default Locale=" + Locale.getDefault().getDisplayName());
        log.info("JMeter  Locale=" + JMeterUtils.getLocale().getDisplayName());
        log.info("JMeterHome=" + JMeterUtils.getJMeterHome());
        logProperty("user.dir", "  ="); //$NON-NLS-1$
        log.info("PWD       =" + new File(".").getCanonicalPath());//$NON-NLS-1$
        log.info("IP: " + JMeterUtils.getLocalHostIP() + " Name: " + JMeterUtils.getLocalHostName()
                + " FullName: " + JMeterUtils.getLocalHostFullName());
        setProxy(parser);

        updateClassLoader();
        if (log.isDebugEnabled()) {
            String jcp = System.getProperty("java.class.path");// $NON-NLS-1$
            String[] bits = jcp.split(File.pathSeparator);
            log.debug("ClassPath");
            for (String bit : bits) {
                log.debug(bit);
            }
        }

        // Set some (hopefully!) useful properties
        long now = System.currentTimeMillis();
        JMeterUtils.setProperty("START.MS", Long.toString(now));// $NON-NLS-1$
        Date today = new Date(now); // so it agrees with above
        // TODO perhaps should share code with __time() function for this...
        JMeterUtils.setProperty("START.YMD", new SimpleDateFormat("yyyyMMdd").format(today));// $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.setProperty("START.HMS", new SimpleDateFormat("HHmmss").format(today));// $NON-NLS-1$ $NON-NLS-2$

        if (parser.getArgumentById(VERSION_OPT) != null) {
            displayAsciiArt();
        } else if (parser.getArgumentById(HELP_OPT) != null) {
            displayAsciiArt();
            System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));// $NON-NLS-1$
        } else if (parser.getArgumentById(OPTIONS_OPT) != null) {
            displayAsciiArt();
            System.out.println(CLUtil.describeOptions(options).toString());
        } else if (parser.getArgumentById(SERVER_OPT) != null) {
            // Start the server
            try {
                RemoteJMeterEngineImpl.startServer(JMeterUtils.getPropDefault("server_port", 0)); // $NON-NLS-1$
            } catch (Exception ex) {
                System.err.println("Server failed to start: " + ex);
                log.error("Giving up, as server failed with:", ex);
                throw ex;
            }
            startOptionalServers();
        } else {
            String testFile = null;
            CLOption testFileOpt = parser.getArgumentById(TESTFILE_OPT);
            if (testFileOpt != null) {
                testFile = testFileOpt.getArgument();
                if (USE_LAST_JMX.equals(testFile)) {
                    testFile = LoadRecentProject.getRecentFile(0);// most recent
                }
            }
            CLOption testReportOpt = parser.getArgumentById(REPORT_GENERATING_OPT);
            if (testReportOpt != null) { // generate report from existing file
                String reportFile = testReportOpt.getArgument();
                extractAndSetReportOutputFolder(parser);
                ReportGenerator generator = new ReportGenerator(reportFile, null);
                generator.generate();
            } else if (parser.getArgumentById(NONGUI_OPT) == null) { // not non-GUI => GUI
                startGui(testFile);
                startOptionalServers();
            } else { // NON-GUI must be true
                extractAndSetReportOutputFolder(parser);

                CLOption rem = parser.getArgumentById(REMOTE_OPT_PARAM);
                if (rem == null) {
                    rem = parser.getArgumentById(REMOTE_OPT);
                }
                CLOption jtl = parser.getArgumentById(LOGFILE_OPT);
                String jtlFile = null;
                if (jtl != null) {
                    jtlFile = processLAST(jtl.getArgument(), ".jtl"); // $NON-NLS-1$
                }
                CLOption reportAtEndOpt = parser.getArgumentById(REPORT_AT_END_OPT);
                if (reportAtEndOpt != null) {
                    if (jtlFile == null) {
                        throw new IllegalUserActionException("Option -" + ((char) REPORT_AT_END_OPT)
                                + " requires -" + ((char) LOGFILE_OPT) + " option");
                    }
                }
                startNonGui(testFile, jtlFile, rem, reportAtEndOpt != null);
                startOptionalServers();
            }
        }
    } catch (IllegalUserActionException e) {
        System.out.println("Incorrect Usage:" + e.getMessage());
        System.out.println(CLUtil.describeOptions(options).toString());
    } catch (Throwable e) {
        log.fatalError("An error occurred: ", e);
        System.out.println("An error occurred: " + e.getMessage());
        System.exit(1); // TODO - could this be return?
    }
}

From source file:com.graphhopper.jsprit.core.algorithm.io.VehicleRoutingAlgorithms.java

private static VehicleRoutingAlgorithm readAndCreateAlgorithm(final VehicleRoutingProblem vrp,
        XMLConfiguration config, int nuOfThreads, final SolutionCostCalculator solutionCostCalculator,
        final StateManager stateManager, ConstraintManager constraintManager,
        boolean addDefaultCostCalculators) {
    // map to store constructed modules
    TypedMap definedClasses = new TypedMap();

    // algorithm listeners
    Set<PrioritizedVRAListener> algorithmListeners = new HashSet<PrioritizedVRAListener>();

    // insertion listeners
    List<InsertionListener> insertionListeners = new ArrayList<InsertionListener>();

    //threading/*from w ww.  ja  v  a 2  s  .co m*/
    final ExecutorService executorService;
    if (nuOfThreads > 0) {
        log.debug("setup executor-service with " + nuOfThreads + " threads");
        executorService = Executors.newFixedThreadPool(nuOfThreads);
        algorithmListeners.add(new PrioritizedVRAListener(Priority.LOW, new AlgorithmEndsListener() {

            @Override
            public void informAlgorithmEnds(VehicleRoutingProblem problem,
                    Collection<VehicleRoutingProblemSolution> solutions) {
                log.debug("shutdown executor-service");
                executorService.shutdown();
            }
        }));
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread arg0, Throwable arg1) {
                System.err.println(arg1.toString());
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (!executorService.isShutdown()) {
                    System.err.println("shutdowHook shuts down executorService");
                    executorService.shutdown();
                }
            }
        });
    } else
        executorService = null;

    //create fleetmanager
    final VehicleFleetManager vehicleFleetManager = createFleetManager(vrp);

    String switchString = config.getString("construction.insertion.allowVehicleSwitch");
    final boolean switchAllowed;
    if (switchString != null) {
        switchAllowed = Boolean.parseBoolean(switchString);
    } else
        switchAllowed = true;
    ActivityTimeTracker.ActivityPolicy activityPolicy;
    if (stateManager.timeWindowUpdateIsActivated()) {
        UpdateVehicleDependentPracticalTimeWindows timeWindowUpdater = new UpdateVehicleDependentPracticalTimeWindows(
                stateManager, vrp.getTransportCosts(), vrp.getActivityCosts());
        timeWindowUpdater
                .setVehiclesToUpdate(new UpdateVehicleDependentPracticalTimeWindows.VehiclesToUpdate() {
                    Map<VehicleTypeKey, Vehicle> uniqueTypes = new HashMap<VehicleTypeKey, Vehicle>();

                    @Override
                    public Collection<Vehicle> get(VehicleRoute vehicleRoute) {
                        if (uniqueTypes.isEmpty()) {
                            for (Vehicle v : vrp.getVehicles()) {
                                if (!uniqueTypes.containsKey(v.getVehicleTypeIdentifier())) {
                                    uniqueTypes.put(v.getVehicleTypeIdentifier(), v);
                                }
                            }
                        }
                        Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
                        vehicles.addAll(uniqueTypes.values());
                        return vehicles;
                    }
                });
        stateManager.addStateUpdater(timeWindowUpdater);
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS;
    } else {
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_ARRIVED;
    }
    stateManager.addStateUpdater(
            new UpdateActivityTimes(vrp.getTransportCosts(), activityPolicy, vrp.getActivityCosts()));
    stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(),
            stateManager, activityPolicy));

    final SolutionCostCalculator costCalculator;
    if (solutionCostCalculator == null)
        costCalculator = getDefaultCostCalculator(stateManager);
    else
        costCalculator = solutionCostCalculator;

    PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp, vehicleFleetManager,
            stateManager, constraintManager);
    //construct initial solution creator
    final InsertionStrategy initialInsertionStrategy = createInitialSolution(config, vrp, vehicleFleetManager,
            stateManager, algorithmListeners, definedClasses, executorService, nuOfThreads, costCalculator,
            constraintManager, addDefaultCostCalculators);
    if (initialInsertionStrategy != null)
        prettyAlgorithmBuilder.constructInitialSolutionWith(initialInsertionStrategy, costCalculator);

    //construct algorithm, i.e. search-strategies and its modules
    int solutionMemory = config.getInt("strategy.memory");
    List<HierarchicalConfiguration> strategyConfigs = config
            .configurationsAt("strategy.searchStrategies.searchStrategy");
    for (HierarchicalConfiguration strategyConfig : strategyConfigs) {
        String name = getName(strategyConfig);
        SolutionAcceptor acceptor = getAcceptor(strategyConfig, vrp, algorithmListeners, definedClasses,
                solutionMemory);
        SolutionSelector selector = getSelector(strategyConfig, vrp, algorithmListeners, definedClasses);

        SearchStrategy strategy = new SearchStrategy(name, selector, acceptor, costCalculator);
        strategy.setName(name);
        List<HierarchicalConfiguration> modulesConfig = strategyConfig.configurationsAt("modules.module");
        for (HierarchicalConfiguration moduleConfig : modulesConfig) {
            SearchStrategyModule module = buildModule(moduleConfig, vrp, vehicleFleetManager, stateManager,
                    algorithmListeners, definedClasses, executorService, nuOfThreads, constraintManager,
                    addDefaultCostCalculators);
            strategy.addModule(module);
        }
        prettyAlgorithmBuilder.withStrategy(strategy, strategyConfig.getDouble("probability"));
    }

    //construct algorithm
    VehicleRoutingAlgorithm metaAlgorithm = prettyAlgorithmBuilder.build();
    int maxIterations = getMaxIterations(config);
    if (maxIterations > -1)
        metaAlgorithm.setMaxIterations(maxIterations);

    //define prematureBreak
    PrematureAlgorithmTermination prematureAlgorithmTermination = getPrematureTermination(config,
            algorithmListeners);
    if (prematureAlgorithmTermination != null)
        metaAlgorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
    else {
        List<HierarchicalConfiguration> terminationCriteria = config
                .configurationsAt("terminationCriteria.termination");
        for (HierarchicalConfiguration terminationConfig : terminationCriteria) {
            PrematureAlgorithmTermination termination = getTerminationCriterion(terminationConfig,
                    algorithmListeners);
            if (termination != null)
                metaAlgorithm.addTerminationCriterion(termination);
        }
    }
    for (PrioritizedVRAListener l : algorithmListeners) {
        metaAlgorithm.getAlgorithmListeners().add(l);
    }
    return metaAlgorithm;
}

From source file:com.graphhopper.jsprit.io.algorithm.VehicleRoutingAlgorithms.java

private static VehicleRoutingAlgorithm readAndCreateAlgorithm(final VehicleRoutingProblem vrp,
        XMLConfiguration config, int nuOfThreads, final SolutionCostCalculator solutionCostCalculator,
        final StateManager stateManager, ConstraintManager constraintManager, boolean addDefaultCostCalculators,
        boolean addCoreConstraints) {
    // map to store constructed modules
    TypedMap definedClasses = new TypedMap();

    // algorithm listeners
    Set<PrioritizedVRAListener> algorithmListeners = new HashSet<PrioritizedVRAListener>();

    // insertion listeners
    List<InsertionListener> insertionListeners = new ArrayList<InsertionListener>();

    //threading/*  w  w  w. j  a  v  a 2 s  . c  o m*/
    final ExecutorService executorService;
    if (nuOfThreads > 0) {
        log.debug("setup executor-service with " + nuOfThreads + " threads");
        executorService = Executors.newFixedThreadPool(nuOfThreads);
        algorithmListeners.add(new PrioritizedVRAListener(Priority.LOW, new AlgorithmEndsListener() {

            @Override
            public void informAlgorithmEnds(VehicleRoutingProblem problem,
                    Collection<VehicleRoutingProblemSolution> solutions) {
                log.debug("shutdown executor-service");
                executorService.shutdown();
            }
        }));
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread arg0, Throwable arg1) {
                System.err.println(arg1.toString());
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (!executorService.isShutdown()) {
                    System.err.println("shutdowHook shuts down executorService");
                    executorService.shutdown();
                }
            }
        });
    } else
        executorService = null;

    //create fleetmanager
    final VehicleFleetManager vehicleFleetManager = createFleetManager(vrp);

    String switchString = config.getString("construction.insertion.allowVehicleSwitch");
    final boolean switchAllowed;
    if (switchString != null) {
        switchAllowed = Boolean.parseBoolean(switchString);
    } else
        switchAllowed = true;
    ActivityTimeTracker.ActivityPolicy activityPolicy;
    if (stateManager.timeWindowUpdateIsActivated()) {
        UpdateVehicleDependentPracticalTimeWindows timeWindowUpdater = new UpdateVehicleDependentPracticalTimeWindows(
                stateManager, vrp.getTransportCosts(), vrp.getActivityCosts());
        timeWindowUpdater
                .setVehiclesToUpdate(new UpdateVehicleDependentPracticalTimeWindows.VehiclesToUpdate() {
                    Map<VehicleTypeKey, Vehicle> uniqueTypes = new HashMap<VehicleTypeKey, Vehicle>();

                    @Override
                    public Collection<Vehicle> get(VehicleRoute vehicleRoute) {
                        if (uniqueTypes.isEmpty()) {
                            for (Vehicle v : vrp.getVehicles()) {
                                if (!uniqueTypes.containsKey(v.getVehicleTypeIdentifier())) {
                                    uniqueTypes.put(v.getVehicleTypeIdentifier(), v);
                                }
                            }
                        }
                        Collection<Vehicle> vehicles = new ArrayList<Vehicle>();
                        vehicles.addAll(uniqueTypes.values());
                        return vehicles;
                    }
                });
        stateManager.addStateUpdater(timeWindowUpdater);
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_TIME_WINDOW_OPENS;
    } else {
        activityPolicy = ActivityTimeTracker.ActivityPolicy.AS_SOON_AS_ARRIVED;
    }
    stateManager.addStateUpdater(
            new UpdateActivityTimes(vrp.getTransportCosts(), activityPolicy, vrp.getActivityCosts()));
    stateManager.addStateUpdater(new UpdateVariableCosts(vrp.getActivityCosts(), vrp.getTransportCosts(),
            stateManager, activityPolicy));

    final SolutionCostCalculator costCalculator;
    if (solutionCostCalculator == null)
        costCalculator = getDefaultCostCalculator(stateManager);
    else
        costCalculator = solutionCostCalculator;

    PrettyAlgorithmBuilder prettyAlgorithmBuilder = PrettyAlgorithmBuilder.newInstance(vrp, vehicleFleetManager,
            stateManager, constraintManager);
    if (addCoreConstraints)
        prettyAlgorithmBuilder.addCoreStateAndConstraintStuff();
    //construct initial solution creator
    final InsertionStrategy initialInsertionStrategy = createInitialSolution(config, vrp, vehicleFleetManager,
            stateManager, algorithmListeners, definedClasses, executorService, nuOfThreads, costCalculator,
            constraintManager, addDefaultCostCalculators);
    if (initialInsertionStrategy != null)
        prettyAlgorithmBuilder.constructInitialSolutionWith(initialInsertionStrategy, costCalculator);

    //construct algorithm, i.e. search-strategies and its modules
    int solutionMemory = config.getInt("strategy.memory");
    List<HierarchicalConfiguration> strategyConfigs = config
            .configurationsAt("strategy.searchStrategies.searchStrategy");
    for (HierarchicalConfiguration strategyConfig : strategyConfigs) {
        String name = getName(strategyConfig);
        SolutionAcceptor acceptor = getAcceptor(strategyConfig, vrp, algorithmListeners, definedClasses,
                solutionMemory);
        SolutionSelector selector = getSelector(strategyConfig, vrp, algorithmListeners, definedClasses);

        SearchStrategy strategy = new SearchStrategy(name, selector, acceptor, costCalculator);
        strategy.setName(name);
        List<HierarchicalConfiguration> modulesConfig = strategyConfig.configurationsAt("modules.module");
        for (HierarchicalConfiguration moduleConfig : modulesConfig) {
            SearchStrategyModule module = buildModule(moduleConfig, vrp, vehicleFleetManager, stateManager,
                    algorithmListeners, definedClasses, executorService, nuOfThreads, constraintManager,
                    addDefaultCostCalculators);
            strategy.addModule(module);
        }
        prettyAlgorithmBuilder.withStrategy(strategy, strategyConfig.getDouble("probability"));
    }

    //construct algorithm
    VehicleRoutingAlgorithm metaAlgorithm = prettyAlgorithmBuilder.build();
    int maxIterations = getMaxIterations(config);
    if (maxIterations > -1)
        metaAlgorithm.setMaxIterations(maxIterations);

    //define prematureBreak
    PrematureAlgorithmTermination prematureAlgorithmTermination = getPrematureTermination(config,
            algorithmListeners);
    if (prematureAlgorithmTermination != null)
        metaAlgorithm.setPrematureAlgorithmTermination(prematureAlgorithmTermination);
    else {
        List<HierarchicalConfiguration> terminationCriteria = config
                .configurationsAt("terminationCriteria.termination");
        for (HierarchicalConfiguration terminationConfig : terminationCriteria) {
            PrematureAlgorithmTermination termination = getTerminationCriterion(terminationConfig,
                    algorithmListeners);
            if (termination != null)
                metaAlgorithm.addTerminationCriterion(termination);
        }
    }
    for (PrioritizedVRAListener l : algorithmListeners) {
        metaAlgorithm.getAlgorithmListeners().add(l);
    }
    return metaAlgorithm;
}

From source file:org.adblockplus.android.AdblockPlus.java

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    // Check for crash report
    try {/*  ww w .ja v  a  2s. c  om*/
        InputStreamReader reportFile = new InputStreamReader(openFileInput(CrashHandler.REPORT_FILE));
        final char[] buffer = new char[0x1000];
        StringBuilder out = new StringBuilder();
        int read;
        do {
            read = reportFile.read(buffer, 0, buffer.length);
            if (read > 0)
                out.append(buffer, 0, read);
        } while (read >= 0);
        String report = out.toString();
        if (!"".equals(report)) {
            final Intent intent = new Intent(this, CrashReportDialog.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("report", report);
            startActivity(intent);
        }
    } catch (FileNotFoundException e) {
        // ignore
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, e.getMessage(), e);
    }

    // Set crash handler
    Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this));

    // Initiate update check
    scheduleUpdater(0);
}

From source file:com.github.vatbub.tictactoe.view.Main.java

@FXML
// This method is called by the FXMLLoader when initialization is complete
void initialize() {
    // modify the default exception handler to show a good error message on every uncaught exception
    final Thread.UncaughtExceptionHandler currentUncaughtExceptionHandler = Thread
            .getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
        if (currentUncaughtExceptionHandler != null) {
            // execute current handler as we only want to append it
            currentUncaughtExceptionHandler.uncaughtException(thread, exception);
        }//from   ww  w  .j  a v  a 2  s  .  com
        Platform.runLater(() -> new ExceptionAlert(exception).showAndWait());
    });

    opponentsTurnHBox.heightProperty()
            .addListener((observable, oldValue, newValue) -> updateOpponentsTurnHBox(false));

    aiLevelLabelClipRectangle = new Rectangle(0, 0, 0, 0);
    aiLevelLabelClipRectangle.setEffect(new MotionBlur(0, 10));
    aiLevelLabelPane.setClip(aiLevelLabelClipRectangle);
    aiLevelLabelClipRectangle.heightProperty().bind(aiLevelLabelPane.heightProperty());
    aiLevelLabelPane.widthProperty().addListener((observable, oldValue, newValue) -> updateAILevelLabel(true));

    Rectangle menuSubBoxClipRectangle = new Rectangle(0, 0, 0, 0);
    menuSubBox.setClip(menuSubBoxClipRectangle);
    menuSubBoxClipRectangle.heightProperty().bind(menuSubBox.heightProperty());
    menuSubBoxClipRectangle.widthProperty().bind(menuSubBox.widthProperty());

    Rectangle playOnlineClipRectangle = new Rectangle(0, 0, 0, 0);
    playOnlineClipAnchorPane.setClip(playOnlineClipRectangle);
    playOnlineClipRectangle.heightProperty().bind(playOnlineClipAnchorPane.heightProperty());
    playOnlineClipRectangle.widthProperty().bind(playOnlineClipAnchorPane.widthProperty());

    player1SetSampleName();
    player2SetSampleName();

    gameTable.heightProperty()
            .addListener((observable, oldValue, newValue) -> refreshedNodes.refreshAll(gameTable.getWidth(),
                    oldValue.doubleValue(), gameTable.getWidth(), newValue.doubleValue()));
    gameTable.widthProperty()
            .addListener((observable, oldValue, newValue) -> refreshedNodes.refreshAll(oldValue.doubleValue(),
                    gameTable.getHeight(), newValue.doubleValue(), gameTable.getHeight()));

    player1AIToggle.selectedProperty().addListener((observable, oldValue, newValue) -> {
        showHideAILevelSlider(newValue, player2AIToggle.isSelected());
        player1SetSampleName();
    });
    player2AIToggle.selectedProperty().addListener((observable, oldValue, newValue) -> {
        showHideAILevelSlider(player1AIToggle.isSelected(), newValue);
        player2SetSampleName();
    });

    gameTable.setSelectionModel(null);
    gameTable.heightProperty().addListener((observable, oldValue, newValue) -> {
        Pane header = (Pane) gameTable.lookup("TableHeaderRow");
        if (header.isVisible()) {
            header.setMaxHeight(0);
            header.setMinHeight(0);
            header.setPrefHeight(0);
            header.setVisible(false);
        }
        renderRows();
    });
    gameTable.setRowFactory(param -> {
        TableRow<Row> row = new TableRow<>();
        row.styleProperty().bind(style);

        if (rowFont == null) {
            rowFont = new SimpleObjectProperty<>();
            rowFont.bind(row.fontProperty());
        }

        return row;
    });

    looseImage.fitHeightProperty().bind(looserPane.heightProperty());
    looseImage.fitWidthProperty().bind(looserPane.widthProperty());
    looseImage.fitHeightProperty().addListener((observable, oldValue, newValue) -> reloadImage(looseImage,
            getClass().getResource("loose.png").toString(), looseImage.getFitWidth(), newValue.doubleValue()));
    looseImage.fitWidthProperty().addListener((observable, oldValue, newValue) -> reloadImage(looseImage,
            getClass().getResource("loose.png").toString(), newValue.doubleValue(), looseImage.getFitWidth()));

    confetti.fitHeightProperty().bind(winPane.heightProperty());
    confetti.fitWidthProperty().bind(winPane.widthProperty());
    confetti.fitHeightProperty().addListener((observable, oldValue, newValue) -> reloadImage(confetti,
            getClass().getResource("confetti.png").toString(), confetti.getFitWidth(), newValue.doubleValue()));
    confetti.fitWidthProperty().addListener((observable, oldValue, newValue) -> reloadImage(confetti,
            getClass().getResource("confetti.png").toString(), newValue.doubleValue(), confetti.getFitWidth()));

    aiLevelSlider.valueProperty().addListener((observable, oldValue, newValue) -> updateAILevelLabel());

    playOnlineHyperlink.widthProperty().addListener((observable, oldValue, newValue) -> {
        if (playOnlineAnchorPane.isVisible()) {
            setLowerRightAnchorPaneDimensions(playOnlineHyperlink, currentPlayerLabel, true);
        }
    });
    playOnlineHyperlink.heightProperty().addListener((observable, oldValue, newValue) -> {
        if (playOnlineAnchorPane.isVisible()) {
            setLowerRightAnchorPaneDimensions(playOnlineHyperlink, currentPlayerLabel, true);
        }
    });
    playOnlineHyperlink.textProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue.equals(oldValue)) {
            if (newValue.contains("ff")) {
                setLowerRightAnchorPaneDimensions(playOnlineHyperlink, currentPlayerLabel, true, 1);
            } else {
                setLowerRightAnchorPaneDimensions(playOnlineHyperlink, currentPlayerLabel, true, -1);
            }
        }
    });

    // Kunami code
    root.setOnKeyPressed(event -> {
        if (KunamiCode.isCompleted(event.getCode())) {
            if (root.getEffect() != null && root.getEffect() instanceof Blend) {
                BlendMode currentMode = ((Blend) root.getEffect()).getMode();
                BlendMode nextMode;
                if (currentMode == BlendMode.values()[BlendMode.values().length - 1]) {
                    nextMode = BlendMode.values()[0];
                } else {
                    nextMode = BlendMode.values()[Arrays.asList(BlendMode.values()).indexOf(currentMode) + 1];
                }
                ((Blend) root.getEffect()).setMode(nextMode);
            } else {
                root.setEffect(new Blend(BlendMode.EXCLUSION));
            }
        }
    });

    // prompt text of the my username field in the online multiplayer menu
    onlineMyUsername.promptTextProperty().bind(player1Name.promptTextProperty());
    onlineMyUsername.textProperty().bindBidirectional(player1Name.textProperty());

    setAccessibleTextsForNodesThatDoNotChange();
    updateAccessibleTexts();

    initBoard();
    initNewGame();
}