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

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

Introduction

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

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:org.apache.distributedlog.TestDistributedLogBase.java

@BeforeClass
public static void setupCluster() throws Exception {
    File zkTmpDir = IOUtils.createTempDir("zookeeper", "distrlog");
    tmpDirs.add(zkTmpDir);//from   ww w  . ja  v  a2s  .  co  m
    Pair<ZooKeeperServerShim, Integer> serverAndPort = LocalDLMEmulator.runZookeeperOnAnyPort(zkTmpDir);
    zks = serverAndPort.getLeft();
    zkPort = serverAndPort.getRight();
    bkutil = LocalDLMEmulator.newBuilder().numBookies(numBookies).zkHost("127.0.0.1").zkPort(zkPort)
            .serverConf(DLMTestUtil.loadTestBkConf()).shouldStartZK(false).build();
    bkutil.start();
    zkServers = "127.0.0.1:" + zkPort;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.warn("Uncaught exception at Thread {} : ", t.getName(), e);
        }
    });
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args//w w  w . j  ava 2  s  .  co  m
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}

From source file:com.viacoin.wallet.WalletApplication.java

@Override
public void onCreate() {
    new LinuxSecureRandom(); // init proper random number generator

    initLogging();/*ww w  .  j  av a  2 s.  co  m*/

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().permitDiskReads()
            .permitDiskWrites().penaltyLog().build());

    Threading.throwOnLockCycles();

    log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod",
            Constants.NETWORK_PARAMETERS.getId());

    super.onCreate();

    packageInfo = packageInfoFromContext(this);

    CrashReporter.init(getCacheDir());

    Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            log.info("bitcoinj uncaught exception", throwable);
            CrashReporter.saveBackgroundTrace(throwable, packageInfo);
        }
    };

    initMnemonicCode();

    config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this));
    activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class);
    blockchainServiceCancelCoinsReceivedIntent = new Intent(BlockchainService.ACTION_CANCEL_COINS_RECEIVED,
            null, this, BlockchainServiceImpl.class);
    blockchainServiceResetBlockchainIntent = new Intent(BlockchainService.ACTION_RESET_BLOCKCHAIN, null, this,
            BlockchainServiceImpl.class);

    walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF);

    loadWalletFromProtobuf();

    config.updateLastVersionCode(packageInfo.versionCode);

    afterLoadWallet();
}

From source file:com.att.arocollector.AROCollectorActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "onCreate(...)");
    // Setup handler for uncaught exceptions.
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*  w  w w .j  a  va 2s. c  o  m*/
        public void uncaughtException(Thread thread, Throwable e) {
            handleUncaughtException(thread, e);
        }
    });

    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    final TextView splashText = (TextView) findViewById(R.id.splash_message);
    splashText.setText(String.format(getString(R.string.splashmessageopensource),
            getString(R.string.app_brand_name), getString(R.string.app_url_name)));
    AttenuatorManager.getInstance().init();
    Intent intent = getIntent();
    //delay
    int delayDl = intent.getIntExtra(BundleKeyUtil.DL_DELAY, 0);
    int delayUl = intent.getIntExtra(BundleKeyUtil.UL_DELAY, 0);

    if (delayDl >= 0) {
        AttenuatorManager.getInstance().setDelayDl(delayDl);
    } else {
        Log.i(TAG, "Invalid attenuation delay value" + delayDl + "ms");
    }

    if (delayUl >= 0) {
        AttenuatorManager.getInstance().setDelayUl(delayUl);
    } else {
        Log.i(TAG, "Invalid attenuation delay value" + delayUl + "ms");
    }

    //throttle
    int throttleDl = intent.getIntExtra(BundleKeyUtil.DL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED);
    int throttleUl = intent.getIntExtra(BundleKeyUtil.UL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED);

    AttenuatorManager.getInstance().setThrottleDL(throttleDl);
    Log.d(TAG, "Download speed throttle value: " + throttleDl + " kbps");

    AttenuatorManager.getInstance().setThrottleUL(throttleUl);
    Log.d(TAG, "Upload speed throttle value: " + throttleUl + " kbps");

    printLog = intent.getBooleanExtra(BundleKeyUtil.PRINT_LOG, false);

    setVideoOption(intent);

    bitRate = intent.getIntExtra(BundleKeyUtil.BIT_RATE, 0);
    String screenSizeTmp = intent.getStringExtra(BundleKeyUtil.SCREEN_SIZE);
    screenSize = screenSizeTmp == null ? screenSize : screenSizeTmp;

    setVideoOrient(intent);

    Log.i(TAG,
            "get from intent delayTime: " + AttenuatorManager.getInstance().getDelayDl()
                    + "get from intent delayTimeUL: " + AttenuatorManager.getInstance().getDelayUl()
                    + "get from intent throttleDL: " + AttenuatorManager.getInstance().getThrottleDL()
                    + "get from intnetn throttleUL: " + AttenuatorManager.getInstance().getThrottleUL()
                    + " video: " + videoOption + " bitRate: " + bitRate + " screenSize: " + screenSize
                    + " orientation: " + videoOrient);

    context = getApplicationContext();
    launchAROCpuTraceService();
    launchAROCpuTempService();
    if (networkAndAirplaneModeCheck()) {

        // register to listen for close down message
        registerAnalyzerCloseCmdReceiver();
        Log.d(TAG, "register the attenuator delay signal");

        startVPN();
    }

    { // test code
        PackageInfo packageInfo = null;
        try {
            packageInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        boolean valu = (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        // build datetime
        Date buildDate = new Date(BuildConfig.TIMESTAMP);
        String appBuildDate = "";
        if (buildDate != null) {
            appBuildDate = buildDate.toString();
        }

        String display = "App Build Date: " + appBuildDate + "\n"
        //               +" DownStream Delay Time: " + AttenuatorManager.getInstance().getDelayDl() + " ms\n"
        //               +" UpStream Delay Time: " + AttenuatorManager.getInstance().getDelayUl() + " ms\n"
        //               +" DownStream Throttle: " + AttenuatorManager.getInstance().getThrottleDL() + " kbps\n"
        //               +" Upstream Throttle: " + AttenuatorManager.getInstance().getThrottleUL() + " kbps\n"
                + AttenuatorUtil.getInstance().notificationMessage() + "\n" + " Version: "
                + packageInfo.versionName + " (" + (valu ? "Debug" : "Production") + ")";

        ((TextView) findViewById(R.id.version)).setText(display);
    }
}

From source file:systems.soapbox.ombuds.client.WalletApplication.java

@Override
public void onCreate() {
    new LinuxSecureRandom(); // init proper random number generator

    initLogging();//from w  ww  .j a  va 2 s  . c  o  m

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().permitDiskReads()
            .permitDiskWrites().penaltyLog().build());

    Threading.throwOnLockCycles();

    log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod",
            Constants.NETWORK_PARAMETERS.getId());

    super.onCreate();

    packageInfo = packageInfoFromContext(this);

    CrashReporter.init(getCacheDir());

    Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            log.info("bitcoinj uncaught exception", throwable);
            CrashReporter.saveBackgroundTrace(throwable, packageInfo);
        }
    };

    initMnemonicCode();

    config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this), getResources());
    activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class);
    blockchainServiceCancelCoinsReceivedIntent = new Intent(BlockchainService.ACTION_CANCEL_COINS_RECEIVED,
            null, this, BlockchainServiceImpl.class);
    blockchainServiceResetBlockchainIntent = new Intent(BlockchainService.ACTION_RESET_BLOCKCHAIN, null, this,
            BlockchainServiceImpl.class);

    walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF);

    loadWalletFromProtobuf();

    if (config.versionCodeCrossed(packageInfo.versionCode, VERSION_CODE_SHOW_BACKUP_REMINDER)
            && !wallet.getImportedKeys().isEmpty()) {
        log.info("showing backup reminder once, because of imported keys being present");
        config.armBackupReminder();
    }

    config.updateLastVersionCode(packageInfo.versionCode);

    afterLoadWallet();

    cleanupFiles();
}

From source file:org.signserver.test.performance.cli.Main.java

/**
 * @param args the command line arguments
 *///from  w ww.ja v  a  2 s  .  c  o  m
public static void main(String[] args) throws RemoteException, InvalidWorkerIdException {
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("(Debug logging is enabled)");
        }

        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);

        // Test suite
        final TestSuites ts;
        if (commandLine.hasOption(TEST_SUITE)) {
            ts = TestSuites.valueOf(commandLine.getOptionValue(TEST_SUITE));
        } else {
            throw new ParseException("Missing option: -" + TEST_SUITE);
        }

        // Time limit
        final long limitedTime;
        if (commandLine.hasOption(TIME_LIMIT)) {
            limitedTime = Long.parseLong(commandLine.getOptionValue(TIME_LIMIT));
        } else {
            limitedTime = -1;
        }

        final int numThreads;
        if (commandLine.hasOption(THREADS)) {
            numThreads = Integer.parseInt(commandLine.getOptionValue(THREADS));
        } else {
            throw new ParseException("Missing option: -" + THREADS);
        }

        final int maxWaitTime;
        if (commandLine.hasOption(MAX_WAIT_TIME)) {
            maxWaitTime = Integer.parseInt(commandLine.getOptionValue(MAX_WAIT_TIME));
        } else {
            maxWaitTime = DEFUALT_MAX_WAIT_TIME;
        }

        final String url;
        boolean useWorkerServlet = false;
        if (commandLine.hasOption(TSA_URL)) {
            if (!ts.equals(TestSuites.TimeStamp1)) {
                throw new ParseException("Option " + TSA_URL + " can only be used with the "
                        + TestSuites.TimeStamp1.toString() + " test suite.");
            }
            url = commandLine.getOptionValue(TSA_URL);
        } else if (commandLine.hasOption(PROCESS_URL)) {
            if (!ts.equals(TestSuites.DocumentSigner1)) {
                throw new ParseException("Option " + TSA_URL + " can only be used with the "
                        + TestSuites.TimeStamp1.toString() + " test suite.");
            }
            url = commandLine.getOptionValue(PROCESS_URL);
            useWorkerServlet = false;
        } else if (commandLine.hasOption(WORKER_URL)) {
            if (!ts.equals(TestSuites.DocumentSigner1)) {
                throw new ParseException("Option " + TSA_URL + " can only be used with the "
                        + TestSuites.TimeStamp1.toString() + " test suite.");
            }
            url = commandLine.getOptionValue(WORKER_URL);
            useWorkerServlet = true;
        } else {
            if (ts.equals(TestSuites.TimeStamp1)) {
                throw new ParseException("Missing option: -" + TSA_URL);
            } else {
                throw new ParseException("Missing option: -" + PROCESS_URL);
            }
        }

        String workerNameOrId = null;
        if (commandLine.hasOption(WORKER_NAME_OR_ID)) {
            workerNameOrId = commandLine.getOptionValue(WORKER_NAME_OR_ID);
        } else if (ts.equals(TestSuites.DocumentSigner1)) {
            throw new ParseException("Must specify worker name or ID.");
        }

        if (commandLine.hasOption(INFILE)) {
            final String file = commandLine.getOptionValue(INFILE);
            final File infile = new File(file);

            try {
                data = FileUtils.readFileToByteArray(infile);
            } catch (IOException e) {
                LOG.error("Failed to read input file: " + e.getMessage());
            }
        } else if (commandLine.hasOption(DATA)) {
            data = commandLine.getOptionValue(DATA).getBytes();
        } else if (ts.equals(TestSuites.DocumentSigner1)) {
            throw new ParseException("Must specify an input file.");
        }

        if (commandLine.hasOption(WARMUP_TIME)) {
            warmupTime = Long.parseLong(commandLine.getOptionValue(WARMUP_TIME));
        } else {
            warmupTime = 0;
        }

        // Time limit
        final File statFolder;
        if (commandLine.hasOption(STAT_OUTPUT_DIR)) {
            statFolder = new File(commandLine.getOptionValue(STAT_OUTPUT_DIR));
            if (!statFolder.exists() || !statFolder.isDirectory()) {
                throw new ParseException("Option -" + STAT_OUTPUT_DIR + " must be an existing directory");
            }
        } else {
            statFolder = null;
        }

        // Support for sending requests with (optionally random) username specified
        userPrefix = commandLine.getOptionValue(USERPREFIX, null);
        final String userSuffixMinValue = commandLine.getOptionValue(USERSUFFIXMIN, null);
        final String userSuffixMaxValue = commandLine.getOptionValue(USERSUFFIXMAX, null);
        final String userNameDescription;
        if (userPrefix == null) {
            if (userSuffixMinValue != null || userSuffixMaxValue != null) {
                throw new ParseException(
                        USERSUFFIXMIN + " and " + USERSUFFIXMAX + " requires a " + USERPREFIX + " option");
            }
            userNameDescription = "n/a";
        } else {
            if ((userSuffixMinValue == null && userSuffixMaxValue != null)
                    || (userSuffixMinValue != null && userSuffixMaxValue == null)) {
                throw new ParseException(
                        "Specify either both or none of " + USERSUFFIXMIN + " and " + USERSUFFIXMAX);
            } else {
                if (userSuffixMinValue != null) {
                    usersuffixMin = Integer.parseInt(userSuffixMinValue);
                    usersuffixMax = Integer.parseInt(userSuffixMaxValue);
                    userNameDescription = "[" + userPrefix + usersuffixMin + ", " + userPrefix + usersuffixMax
                            + "]";
                } else {
                    userNameDescription = userPrefix;
                }
            }
        }

        // Print info
        LOG.info(String.format(
                "-- Configuration -----------------------------------------------------------%n"
                        + "   Start time:              %s%n" + "   Test suite:              %s%n"
                        + "   Threads:                 %10d%n" + "   Warm up time:            %10d ms%n"
                        + "   Max wait time:           %10d ms%n" + "   Time limit:              %10d ms%n"
                        + "   URL:                     %s%n" + "   Username(s):             %s%n"
                        + "   Output statistics:       %s%n"
                        + "-------------------------------------------------------------------------------%n",
                new Date(), ts.name(), numThreads, warmupTime, maxWaitTime, limitedTime, url,
                userNameDescription, statFolder == null ? "no" : statFolder.getAbsolutePath()));

        final LinkedList<WorkerThread> threads = new LinkedList<WorkerThread>();
        final FailureCallback callback = new FailureCallback() {

            @Override
            public void failed(WorkerThread thread, String message) {
                for (WorkerThread w : threads) {
                    w.stopIt();
                }

                // Print message
                LOG.error("   " + message);
                exitCode = -1;
            }
        };
        Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                LOG.error("Uncaught exception from t", e);
                callback.failed((WorkerThread) t, "Uncaught exception: " + e.getMessage());
            }
        };

        Thread shutdownHook = new Thread() {
            @Override
            public void run() {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Shutdown hook called");
                }
                shutdown(threads);
            }
        };

        Runtime.getRuntime().addShutdownHook(shutdownHook);

        try {
            switch (ts) {
            case TimeStamp1:
                timeStamp1(threads, numThreads, callback, url, maxWaitTime, warmupTime, limitedTime,
                        statFolder);
                break;
            case DocumentSigner1:
                documentSigner1(threads, numThreads, callback, url, useWorkerServlet, workerNameOrId,
                        maxWaitTime, warmupTime, limitedTime, statFolder, userPrefix, usersuffixMin,
                        usersuffixMax);
                break;
            default:
                throw new Exception("Unsupported test suite");
            }

            // Wait 1 second to start
            Thread.sleep(1000);

            // Start all threads
            startTime = System.currentTimeMillis();
            for (WorkerThread w : threads) {
                w.setUncaughtExceptionHandler(handler);
                w.start();
            }

            // Wait for the threads to finish
            try {
                for (WorkerThread w : threads) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Waiting for thread " + w.getName());
                    }
                    w.join();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Thread " + w.getName() + " stopped");
                    }
                }
            } catch (InterruptedException ex) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Interupted when waiting for thread: " + ex.getMessage());
                }
            }
        } catch (Exception ex) {
            LOG.error("Failed: " + ex.getMessage(), ex);
            exitCode = -1;
        }

        System.exit(exitCode);
    } catch (ParseException ex) {
        LOG.error("Parse error: " + ex.getMessage());
        printUsage();
        System.exit(-2);
    }
}

From source file:de.langerhans.wallet.WalletApplication.java

@Override
public void onCreate() {
    new LinuxSecureRandom(); // init proper random number generator

    initLogging();//from  www  . ja  v a  2  s.c  om

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().permitDiskReads()
            .permitDiskWrites().penaltyLog().build());

    Threading.throwOnLockCycles();

    log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod",
            Constants.NETWORK_PARAMETERS.getId());

    super.onCreate();

    packageInfo = packageInfoFromContext(this);

    CrashReporter.init(getCacheDir());

    Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            log.info("bitcoinj uncaught exception", throwable);
            CrashReporter.saveBackgroundTrace(throwable, packageInfo);
        }
    };

    initMnemonicCode();

    config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this));
    activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class);
    blockchainServiceCancelCoinsReceivedIntent = new Intent(BlockchainService.ACTION_CANCEL_COINS_RECEIVED,
            null, this, BlockchainServiceImpl.class);
    blockchainServiceResetBlockchainIntent = new Intent(BlockchainService.ACTION_RESET_BLOCKCHAIN, null, this,
            BlockchainServiceImpl.class);

    walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF);

    loadWalletFromProtobuf();

    if (config.versionCodeCrossed(packageInfo.versionCode, VERSION_CODE_SHOW_BACKUP_REMINDER)
            && !wallet.getImportedKeys().isEmpty()) {
        log.info("showing backup reminder once, because of imported keys being present");
        config.armBackupReminder();
    }

    config.updateLastVersionCode(packageInfo.versionCode);

    afterLoadWallet();

    cleanupFiles();
}

From source file:org.wso2.carbon.appfactory.core.queue.QueueProcessor.java

public ThreadExecutor(Executor<T> executor, T t) {
    this.executor = executor;
    this.t = t;/*  w ww .jav a2s  .com*/
    this.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("exception " + e + " from thread " + t);
        }
    });
}

From source file:org.apache.hadoop.corona.Utilities.java

/**
 * Sets an uncaught exception handler. This will make the process exit with
 * exit code 1 if a thread exits due to an uncaught exception.
 */// w ww .  java2s  . c  o m
public static void makeProcessExitOnUncaughtException(final Log log) {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("UNCAUGHT: Thread " + t.getName() + " got an uncaught exception", e);
            System.exit(1);
        }
    });
}

From source file:op.OPDE.java

/**
 * Hier ist die main Methode von OPDE. In dieser Methode wird auch festgestellt, wie OPDE gestartet wurde.
 * <ul>//from   w ww  .  j  a v  a  2  s.c  om
 * <li>Im Standard Modus, das heisst mit graphischer Oberflche. Das drfte der hufigste Fall sein.</li>
 * <li>Im DFNImport Modus. Der wird meist auf dem Datenbankserver gebraucht um Nachts die Durchfhrungsnachweise anhand der
 * DFNImport Tabelle zu generieren. Das alles gehrt zu der Pflegeplanung.</li>
 * <li>Im BHPImport Modus. Auch dieser Modus wird auf dem DB-Server gebraucht um die Behandlungspflege Massnahmen
 * anhand der rztlichen Verordnungen zu generieren.</li>
 * </ul>
 *
 * @param args Hier stehen die Kommandozeilen Parameter. Diese werden mit
 */
public static void main(String[] args) throws Exception {
    /***
     *
     *              ____
     *            ,'  , `.
     *         ,-+-,.' _ |              ,--,
     *      ,-+-. ;   , ||            ,--.'|         ,---,
     *     ,--.'|'   |  ;|            |  |,      ,-+-. /  |
     *    |   |  ,', |  ':  ,--.--.   `--'_     ,--.'|'   |
     *    |   | /  | |  || /       \  ,' ,'|   |   |  ,"' |
     *    '   | :  | :  |,.--.  .-. | '  | |   |   | /  | |
     *    ;   . |  ; |--'  \__\/: . . |  | :   |   | |  | |
     *    |   : |  | ,     ," .--.; | '  : |__ |   | |  |/
     *    |   : '  |/     /  /  ,.  | |  | '.'||   | |--'
     *    ;   | |`-'     ;  :   .'   \;  :    ;|   |/
     *    |   ;/         |  ,     .-./|  ,   / '---'
     *    '---'           `--`---'     ---`-'
     *
     */
    uptime = SYSCalendar.now();

    //        arial14 = new Font("Arial", Font.PLAIN, 14);
    //        arial28 = new Font("Arial", Font.PLAIN, 28);

    /***
     *      _                                               ____                  _ _
     *     | |    __ _ _ __   __ _ _   _  __ _  __ _  ___  | __ ) _   _ _ __   __| | | ___
     *     | |   / _` | '_ \ / _` | | | |/ _` |/ _` |/ _ \ |  _ \| | | | '_ \ / _` | |/ _ \
     *     | |__| (_| | | | | (_| | |_| | (_| | (_| |  __/ | |_) | |_| | | | | (_| | |  __/
     *     |_____\__,_|_| |_|\__, |\__,_|\__,_|\__, |\___| |____/ \__,_|_| |_|\__,_|_|\___|
     *                       |___/             |___/
     */
    lang = ResourceBundle.getBundle("languageBundle", Locale.getDefault());

    validatorFactory = Validation.buildDefaultValidatorFactory();

    /***
     *       ____      _       _             _ _                                                        _   _
     *      / ___|__ _| |_ ___| |__     __ _| | |  _ __ ___   __ _ _   _  ___    _____  _____ ___ _ __ | |_(_) ___  _ __  ___
     *     | |   / _` | __/ __| '_ \   / _` | | | | '__/ _ \ / _` | | | |/ _ \  / _ \ \/ / __/ _ \ '_ \| __| |/ _ \| '_ \/ __|
     *     | |__| (_| | || (__| | | | | (_| | | | | | | (_) | (_| | |_| |  __/ |  __/>  < (_|  __/ |_) | |_| | (_) | | | \__ \
     *      \____\__,_|\__\___|_| |_|  \__,_|_|_| |_|  \___/ \__, |\__,_|\___|  \___/_/\_\___\___| .__/ \__|_|\___/|_| |_|___/
     *                                                       |___/                               |_|
     */
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            OPDE.fatal(e);
        }
    });

    localProps = new SortedProperties();
    props = new Properties();

    /***
     *                         _      _               ___        __
     *      _ __ ___  __ _  __| |    / \   _ __  _ __|_ _|_ __  / _| ___
     *     | '__/ _ \/ _` |/ _` |   / _ \ | '_ \| '_ \| || '_ \| |_ / _ \
     *     | | |  __/ (_| | (_| |  / ___ \| |_) | |_) | || | | |  _| (_) |
     *     |_|  \___|\__,_|\__,_| /_/   \_\ .__/| .__/___|_| |_|_|  \___/
     *                                    |_|   |_|
     */
    appInfo = new AppInfo();

    /***
     *       ____                                          _   _     _               ___        _   _
     *      / ___|___  _ __ ___  _ __ ___   __ _ _ __   __| | | |   (_)_ __   ___   / _ \ _ __ | |_(_) ___  _ __  ___
     *     | |   / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | |   | | '_ \ / _ \ | | | | '_ \| __| |/ _ \| '_ \/ __|
     *     | |__| (_) | | | | | | | | | | | (_| | | | | (_| | | |___| | | | |  __/ | |_| | |_) | |_| | (_) | | | \__ \
     *      \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_____|_|_| |_|\___|  \___/| .__/ \__|_|\___/|_| |_|___/
     *                                                                                   |_|
     */
    Options opts = new Options();
    opts.addOption("h", "hilfe", false, "Gibt die Hilfeseite fr OPDE aus.");
    opts.addOption("v", "version", false, "Zeigt die Versionsinformationen an.");
    opts.addOption("x", "experimental", false,
            "Schaltet experimentelle Programm-Module fr User frei, die Admin Rechte haben. VORSICHT !!!!");
    opts.addOption("a", "anonym", false,
            "Blendet die Bewohnernamen in allen Ansichten aus. Spezieller Modus fr Schulungsmaterial zu erstellen.");
    opts.addOption("w", "workingdir", true,
            "Damit kannst Du ein anderes Arbeitsverzeichnis setzen. Wenn Du diese Option weglsst, dann ist das Dein Benutzerverzeichnis: "
                    + System.getProperty("user.home"));
    opts.addOption("l", "debug", false,
            "Schaltet alle Ausgaben ein auf der Konsole ein, auch die, die eigentlich nur whrend der Softwareentwicklung angezeigt werden.");
    opts.addOption("t", "training", false,
            "Wird fr Einarbeitungsversionen bentigt. Frbt die Oberflche anders ein und zeigt eine Warnmeldung nach jeder Anmeldung.");
    Option optFTPserver = OptionBuilder.withLongOpt("ftpserver").withArgName("ip or hostname").hasArgs(1)
            .withDescription(lang.getString("cmdline.ftpserver")).create("f");
    opts.addOption(optFTPserver);
    //        opts.addOption("p", "pidfile", false, "Path to the pidfile which needs to be deleted when this application ends properly.");

    Option notification = OptionBuilder.withLongOpt("notification").hasOptionalArg()
            .withDescription("Schickt allen festgelegten Empfngern die jeweilige Benachrichtungs-Mail.")
            .create("n");
    notification.setArgName(
            "Liste der Empfnger (durch Komma getrennt, ohne Leerzeichen. UID verwenden). Damit kannst Du die Benachrichtigungen einschrnken. Fehlt diese Liste, erhalten ALLE Empfnger eine Mail.");
    opts.addOption(notification);

    opts.addOption(OptionBuilder.withLongOpt("jdbc").hasArg().withDescription(lang.getString("cmdline.jdbc"))
            .create("j"));

    Option dfnimport = OptionBuilder //.withArgName("datum")
            .withLongOpt("dfnimport").hasOptionalArg()
            .withDescription("Startet OPDE im DFNImport Modus fr den aktuellen Tag.").create("d");
    dfnimport.setArgName(
            "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden.");
    opts.addOption(dfnimport);

    Option bhpimport = OptionBuilder.withLongOpt("bhpimport").hasOptionalArg()
            .withDescription("Startet OPDE im BHPImport Modus fr den aktuellen Tag.").create("b");
    //        bhpimport.setOptionalArg(true);
    bhpimport.setArgName(
            "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden.");
    opts.addOption(bhpimport);

    BasicParser parser = new BasicParser();
    CommandLine cl = null;
    String footer = "http://www.Offene-Pflege.de";

    /***
     *      _          _
     *     | |__   ___| |_ __    ___  ___ _ __ ___  ___ _ __
     *     | '_ \ / _ \ | '_ \  / __|/ __| '__/ _ \/ _ \ '_ \
     *     | | | |  __/ | |_) | \__ \ (__| | |  __/  __/ | | |
     *     |_| |_|\___|_| .__/  |___/\___|_|  \___|\___|_| |_|
     *                  |_|
     */
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OffenePflege.jar [OPTION]",
                "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts,
                footer);
        System.exit(0);
    }

    // Alternative FTP-Server
    if (cl.hasOption("f")) {
        UPDATE_FTPSERVER = cl.getOptionValue("f");
    }

    if (cl.hasOption("h")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OffenePflege.jar [OPTION]",
                "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts,
                footer);
        System.exit(0);
    }

    String homedir = System.getProperty("user.home");
    // alternatice working dir
    if (cl.hasOption("w")) {
        File dir = new File(cl.getOptionValue("w"));
        if (dir.exists() && dir.isDirectory()) {
            homedir = dir.getAbsolutePath();
        }
    }
    opwd = homedir + sep + AppInfo.dirBase;

    /***
     *                                                                ___
     *       __ _ _ __   ___  _ __  _   _ _ __ ___   ___  _   _ ___  |__ \
     *      / _` | '_ \ / _ \| '_ \| | | | '_ ` _ \ / _ \| | | / __|   / /
     *     | (_| | | | | (_) | | | | |_| | | | | | | (_) | |_| \__ \  |_|
     *      \__,_|_| |_|\___/|_| |_|\__, |_| |_| |_|\___/ \__,_|___/  (_)
     *                              |___/
     */
    if (cl.hasOption("a")) { // anonym Modus
        //localProps.put("anonym", "true");
        anonym = true;
        anonymize = new HashMap[] { SYSConst.getNachnamenAnonym(), SYSConst.getVornamenFrauAnonym(),
                SYSConst.getVornamenMannAnonym() };
    } else {
        anonym = false;
    }

    /***
     *      _       _ _                _       _
     *     (_)_ __ (_) |_   _ __  _ __(_)_ __ | |_ ___ _ __ ___
     *     | | '_ \| | __| | '_ \| '__| | '_ \| __/ _ \ '__/ __|
     *     | | | | | | |_  | |_) | |  | | | | | ||  __/ |  \__ \
     *     |_|_| |_|_|\__| | .__/|_|  |_|_| |_|\__\___|_|  |___/
     *                     |_|
     */
    printers = new LogicalPrinters();

    /***
     *      _                 _   _                 _                                   _   _
     *     | | ___   __ _  __| | | | ___   ___ __ _| |  _ __  _ __ ___  _ __   ___ _ __| |_(_) ___  ___
     *     | |/ _ \ / _` |/ _` | | |/ _ \ / __/ _` | | | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __|
     *     | | (_) | (_| | (_| | | | (_) | (_| (_| | | | |_) | | | (_) | |_) |  __/ |  | |_| |  __/\__ \
     *     |_|\___/ \__,_|\__,_| |_|\___/ \___\__,_|_| | .__/|_|  \___/| .__/ \___|_|   \__|_|\___||___/
     *                                                 |_|             |_|
     */
    if (loadLocalProperties()) {

        //            try {
        //                FileAppender fileAppender = new FileAppender(layout, , true);
        //                logger.addAppender(fileAppender);
        //            } catch (IOException ex) {
        //                fatal(ex);
        //            }

        animation = localProps.containsKey("animation") && localProps.getProperty("animation").equals("true");

        logger.info("######### START ###########  " + OPDE.getAppInfo().getProgname() + ", v"
                + OPDE.getAppInfo().getVersion() + "/" + OPDE.getAppInfo().getBuildnum());
        logger.info(System.getProperty("os.name").toLowerCase());

        /***
         *      _     ____       _                   ___ ___
         *     (_)___|  _ \  ___| |__  _   _  __ _  |__ \__ \
         *     | / __| | | |/ _ \ '_ \| | | |/ _` |   / / / /
         *     | \__ \ |_| |  __/ |_) | |_| | (_| |  |_| |_|
         *     |_|___/____/ \___|_.__/ \__,_|\__, |  (_) (_)
         *                                   |___/
         */
        if (cl.hasOption("l") || SYSTools.catchNull(localProps.getProperty("debug")).equalsIgnoreCase("true")) {
            debug = true;
            logger.setLevel(Level.DEBUG);
        } else {
            debug = false;
            logger.setLevel(Level.INFO);
        }

        Logger.getLogger("org.hibernate").setLevel(Level.OFF);

        if (cl.hasOption("x")
                || SYSTools.catchNull(localProps.getProperty("experimental")).equalsIgnoreCase("true")) {
            experimental = true;

        } else {
            experimental = false;
        }

        if (cl.hasOption("t")
                || SYSTools.catchNull(localProps.getProperty("training")).equalsIgnoreCase("true")) {
            training = true;
        } else {
            training = false;
        }

        /***
         *          _ _                       _                                               _   _ _     _        ___ 
         *       __| | |____   _____ _ __ ___(_) ___  _ __     ___ ___  _ __ ___  _ __   __ _| |_(_) |__ | | ___  |__ \
         *      / _` | '_ \ \ / / _ \ '__/ __| |/ _ \| '_ \   / __/ _ \| '_ ` _ \| '_ \ / _` | __| | '_ \| |/ _ \   / /
         *     | (_| | |_) \ V /  __/ |  \__ \ | (_) | | | | | (_| (_) | | | | | | |_) | (_| | |_| | |_) | |  __/  |_| 
         *      \__,_|_.__/ \_/ \___|_|  |___/_|\___/|_| |_|  \___\___/|_| |_| |_| .__/ \__,_|\__|_|_.__/|_|\___|  (_) 
         *                                                                       |_|                                   
         */
        url = cl.hasOption("j") ? cl.getOptionValue("j") : localProps.getProperty("javax.persistence.jdbc.url");
        String hostkey = OPDE.getLocalProps().getProperty("hostkey");
        String cryptpassword = localProps.getProperty("javax.persistence.jdbc.password");
        DesEncrypter desEncrypter = new DesEncrypter(hostkey);
        Connection jdbcConnection = DriverManager.getConnection(url,
                localProps.getProperty("javax.persistence.jdbc.user"), desEncrypter.decrypt(cryptpassword));
        if (appInfo.getDbversion() != getDBVersion(jdbcConnection)) {
            SYSFilesTools.print(lang.getString("cant.start.with.version.mismatch"), false);
            System.exit(1);
        }
        jdbcConnection.close();

        /***
         *          _ ____   _      ____        _        _
         *         | |  _ \ / \    |  _ \  __ _| |_ __ _| |__   __ _ ___  ___
         *      _  | | |_) / _ \   | | | |/ _` | __/ _` | '_ \ / _` / __|/ _ \
         *     | |_| |  __/ ___ \  | |_| | (_| | || (_| | |_) | (_| \__ \  __/
         *      \___/|_| /_/   \_\ |____/ \__,_|\__\__,_|_.__/ \__,_|___/\___|
         *
         */
        Properties jpaProps = new Properties();
        jpaProps.put("javax.persistence.jdbc.user", localProps.getProperty("javax.persistence.jdbc.user"));

        try {
            jpaProps.put("javax.persistence.jdbc.password", desEncrypter.decrypt(cryptpassword));
        } catch (Exception e) {
            if (Desktop.isDesktopSupported()) {
                JOptionPane.showMessageDialog(null, SYSTools.xx("misc.msg.decryption.failure"),
                        appInfo.getProgname(), JOptionPane.ERROR_MESSAGE);
            } else {
                OPDE.fatal(e);
            }
            System.exit(1);
        }

        jpaProps.put("javax.persistence.jdbc.driver", localProps.getProperty("javax.persistence.jdbc.driver"));
        jpaProps.put("javax.persistence.jdbc.url", url);

        //            if (cl.hasOption("d") || cl.hasOption("d")) {  // not for BHP or DFN
        //                jpaProps.put("eclipselink.cache.shared.default", "false");
        //            } else {
        //                jpaProps.put("eclipselink.cache.shared.default", "true");
        //            }

        jpaProps.put("eclipselink.cache.shared.default", "false");
        jpaProps.put("eclipselink.session.customizer", "entity.JPAEclipseLinkSessionCustomizer");
        emf = Persistence.createEntityManagerFactory("OPDEPU", jpaProps);

        /***
         *     __     __            _
         *     \ \   / /__ _ __ ___(_) ___  _ __
         *      \ \ / / _ \ '__/ __| |/ _ \| '_ \
         *       \ V /  __/ |  \__ \ | (_) | | | |
         *        \_/ \___|_|  |___/_|\___/|_| |_|
         *
         */
        String header = SYSTools.getWindowTitle("");
        if (cl.hasOption("v")) {
            System.out.println(header);
            System.out.println(footer);
            System.exit(0);
        }

        /***
         *       ____                           _         ____  _____ _   _
         *      / ___| ___ _ __   ___ _ __ __ _| |_ ___  |  _ \|  ___| \ | |___
         *     | |  _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ | | | | |_  |  \| / __|
         *     | |_| |  __/ | | |  __/ | | (_| | ||  __/ | |_| |  _| | |\  \__ \
         *      \____|\___|_| |_|\___|_|  \__,_|\__\___| |____/|_|   |_| \_|___/
         *
         */
        if (cl.hasOption("d")) {
            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                // create the new DFNs
                DFNTools.generate(em);
                // move over the floating ones that have not yet been clicked to the current day
                DFNTools.moveFloating(em);

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        /***
         *       ____                           _         ____  _   _ ____
         *      / ___| ___ _ __   ___ _ __ __ _| |_ ___  | __ )| | | |  _ \ ___
         *     | |  _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ |  _ \| |_| | |_) / __|
         *     | |_| |  __/ | | |  __/ | | (_| | ||  __/ | |_) |  _  |  __/\__ \
         *      \____|\___|_| |_|\___|_|  \__,_|\__\___| |____/|_| |_|_|   |___/
         *
         */
        if (cl.hasOption("b")) {

            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                BHPTools.generate(em);

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        /***
         *      _   _       _   _  __ _           _   _
         *     | \ | | ___ | |_(_)/ _(_) ___ __ _| |_(_) ___  _ __
         *     |  \| |/ _ \| __| | |_| |/ __/ _` | __| |/ _ \| '_ \
         *     | |\  | (_) | |_| |  _| | (_| (_| | |_| | (_) | | | |
         *     |_| \_|\___/ \__|_|_| |_|\___\__,_|\__|_|\___/|_| |_|
         *
         */
        if (cl.hasOption("n")) {

            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                EMailSystem.notify(cl.getOptionValue("n"));

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        // to speed things later. The first connection loads the while JPA system.
        EntityManager em1 = createEM();
        em1.close();

        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        setStandardFont();

        try {
            css = SYSTools.readFileAsString(opwd + sep + AppInfo.dirTemplates + sep + AppInfo.fileStandardCSS);
        } catch (IOException ie) {
            css = "";
        }

        // JideSoft
        Lm.verifyLicense("Torsten Loehr", "Open-Pflege.de", "G9F4JW:Bm44t62pqLzp5woAD4OCSUAr2");
        WizardStyle.setStyle(WizardStyle.JAVA_STYLE);
        // JideSoft

        /***
         *      _____               __  __       _        ____
         *     |  ___| __ _ __ ___ |  \/  | __ _(_)_ __  / /\ \
         *     | |_ | '__| '_ ` _ \| |\/| |/ _` | | '_ \| |  | |
         *     |  _|| |  | | | | | | |  | | (_| | | | | | |  | |
         *     |_|  |_|  |_| |_| |_|_|  |_|\__,_|_|_| |_| |  | |
         *                                               \_\/_/
         */

        //        JFrame frm = new JFrame();
        //            frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //            frm.setLayout(new FlowLayout());
        //
        //                    frm.getContentPane().add(new PnlBodyScheme(new Properties()));
        //
        //                    frm.setVisible(true);

        SYSTools.checkForSoftwareupdates();

        mainframe = new FrmMain();

        mainframe.setVisible(true);

    }
}