Example usage for java.util Locale setDefault

List of usage examples for java.util Locale setDefault

Introduction

In this page you can find the example usage for java.util Locale setDefault.

Prototype

public static synchronized void setDefault(Locale newLocale) 

Source Link

Document

Sets the default locale for this instance of the Java Virtual Machine.

Usage

From source file:edu.ku.brc.specify.config.SpecifyAppContextMgr.java

/**
 * @param databaseName//  ww  w .  j  a va  2  s. c  o m
 * @param userName
 * @param startingOver
 * @param doPrompt
 * @param collectionName
 * @return
 */
public CONTEXT_STATUS setContext(final String databaseName, final String userName, final boolean startingOver,
        final boolean doPrompt, final boolean isFirstTime, final String collectionName,
        final boolean isMainSpecifyApp) {
    if (debug)
        log.debug("setting context - databaseName: [" + databaseName + "] userName: [" + userName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    this.databaseName = databaseName;
    this.userName = userName;
    this.hasContext = true;

    if (isFirstTime) {
        DBTableIdMgr.getInstance().clearPermissions();
    }

    // This is where we will read it in from the Database
    // but for now we don't need to do that.
    //
    // We need to search for User, Collection, Discipline and UserType
    // Then

    DataProviderSessionIFace session = null;
    try {
        session = openSession();

    } catch (org.hibernate.exception.SQLGrammarException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex);
        showLocalizedError(L10N + "SCHEMA_OUTOF_SYNC"); //$NON-NLS-1$
        System.exit(0);
    }

    if (session == null) {
        return CONTEXT_STATUS.Error;
    }

    try {
        List<?> list = session.getDataList(SpecifyUser.class, "name", userName); //$NON-NLS-1$
        if (list.size() == 1) {
            user = (SpecifyUser) list.get(0);
            user.getAgents().size(); // makes sure the Agent is not lazy loaded
            session.evict(user.getAgents());
            setClassObject(SpecifyUser.class, user);

            if (!startingOver && isMainSpecifyApp) {
                if (user.getIsLoggedIn()) {
                    Object[] options = { getResourceString(L10N + "OVERRIDE"), //$NON-NLS-1$
                            getResourceString(L10N + "EXIT") //$NON-NLS-1$
                    };
                    int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                            getResourceString(L10N + "LOGGED_IN"), getResourceString(L10N + "LOGGED_IN_TITLE"), //$NON-NLS-2$
                            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (userChoice == JOptionPane.NO_OPTION) {
                        //CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
                        System.exit(0);
                    }
                }

                user.setIsLoggedIn(true);
                user.setLoginOutTime(new Timestamp(System.currentTimeMillis()));

                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

                } catch (Exception ex) {
                    session.rollback();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class,
                            ex);
                    log.error(ex);
                }
            }

        } else {
            //JOptionPane.showMessageDialog(null, 
            //        getResourceString("USER_NOT_FOUND"), 
            //        getResourceString("USER_NOT_FOUND_TITLE"), JOptionPane.WARNING_MESSAGE);

            return CONTEXT_STATUS.Error;
            //throw new RuntimeException("The user ["+userName+"] could  not be located as a Specify user.");
        }

        // First we start by getting all the Collection that the User want to
        // work with for this "Context" then we need to go get all the Default View and
        // additional XML Resources.

        if (isFirstTime) {
            FixDBAfterLogin.fixUserPermissions(false);
        }

        if (!AppPreferences.getGlobalPrefs().getBoolean("ExsiccataUpdateFor1_7", false)) {
            FixDBAfterLogin.fixExsiccata();
        }

        Collection curColl = getClassObject(Collection.class);
        int prevCollectionId = curColl != null ? curColl.getCollectionId() : -1;

        Discipline curDis = getClassObject(Discipline.class);
        int prevDisciplineId = curDis != null ? curDis.getDisciplineId() : -1;

        classObjHash.clear();

        setClassObject(SpecifyUser.class, user);

        // Ask the User to choose which Collection they will be working with
        Collection collection = setupCurrentCollection(user, doPrompt, collectionName);
        if (collection == null) {
            // Return false but don't mess with anything that has been set up so far
            currentStatus = currentStatus == CONTEXT_STATUS.Initial ? CONTEXT_STATUS.Error
                    : CONTEXT_STATUS.Ignore;
            return currentStatus;
        }

        collection = session.merge(collection);
        String userType = user.getUserType();

        if (debug)
            log.debug("User[" + user.getName() + "] Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

        userType = StringUtils.replace(userType, " ", "").toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$

        if (debug)
            log.debug("Def Type[" + userType + "]"); //$NON-NLS-1$ //$NON-NLS-2$

        spAppResourceList.clear();
        viewSetHash.clear();

        Discipline discipline = session.getData(Discipline.class, "disciplineId", //$NON-NLS-1$
                collection.getDiscipline().getId(), DataProviderSessionIFace.CompareType.Equals);
        discipline.forceLoad();

        setClassObject(Discipline.class, discipline);

        String disciplineStr = discipline.getType().toLowerCase();

        Division division = discipline.getDivision();
        division.forceLoad();
        setClassObject(Division.class, division);

        DataType dataType = discipline.getDataType();
        dataType.forceLoad();
        setClassObject(DataType.class, dataType);

        Agent userAgent = null;
        for (Agent agt : user.getAgents()) {
            if (agt.getDivision().getId().equals(division.getId())) {
                userAgent = agt;
                userAgent.getAddresses().size();
                userAgent.getVariants().size();
                break;
            }
        }
        setClassObject(Agent.class, userAgent);

        IconEntry ceEntry = IconManager.getIconEntryByName("CollectingEvent");
        if (ceEntry != null) {
            boolean isEmbedded = collection.getIsEmbeddedCollectingEvent();
            IconEntry ciEntry = IconManager
                    .getIconEntryByName(isEmbedded ? "collectinginformation" : "ce_restore");
            if (ciEntry != null) {
                ceEntry.setIcon(ciEntry.getIcon());
                ceEntry.getIcons().clear();
            }
        }

        if (isFirstTime) {
            AppPreferences.startup();

            //--------------------------------------------------------------------------------
            // Check for locks set on uploader, tree update, ...
            //--------------------------------------------------------------------------------

            int uploadLockCheckResult = Uploader.checkUploadLock(null);
            boolean noLocks = uploadLockCheckResult != Uploader.LOCKED;
            boolean goodTrees = true;
            if (uploadLockCheckResult != Uploader.LOCK_IGNORED) {
                if (noLocks) {
                    if (!discipline.getTaxonTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getTaxonTreeDef().getName());
                    }
                }
                if (noLocks) {
                    if (!discipline.getGeographyTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getGeographyTreeDef().getName());
                    }
                }
                if (noLocks) {
                    if (!division.getInstitution().getStorageTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                division.getInstitution().getStorageTreeDef().getName());
                    }
                }
                if (noLocks && discipline.getGeologicTimePeriodTreeDef() != null) {
                    if (!discipline.getGeologicTimePeriodTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getGeologicTimePeriodTreeDef().getName());
                    }
                }
                if (noLocks && discipline.getLithoStratTreeDef() != null) {
                    if (!discipline.getLithoStratTreeDef().checkNodeRenumberingLock()) {
                        noLocks = false;
                        UIRegistry.showLocalizedError("Specify.TreeUpdateLock",
                                discipline.getLithoStratTreeDef().getName());
                    }
                }

                if (noLocks) {
                    // Now force node number updates for trees that are
                    // out-of-date
                    goodTrees = discipline.getTaxonTreeDef().checkNodeNumbersUpToDate(true);
                    if (goodTrees) {
                        goodTrees = discipline.getGeographyTreeDef().checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees) {
                        goodTrees = division.getInstitution().getStorageTreeDef()
                                .checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees && discipline.getGeologicTimePeriodTreeDef() != null) {
                        goodTrees = discipline.getGeologicTimePeriodTreeDef().checkNodeNumbersUpToDate(true);
                    }
                    if (goodTrees && discipline.getLithoStratTreeDef() != null) {
                        goodTrees = discipline.getLithoStratTreeDef().checkNodeNumbersUpToDate(true);
                    }
                }
            }

            if (!noLocks || !goodTrees) {
                user.setIsLoggedIn(false);
                user.setLoginOutTime(new Timestamp(System.currentTimeMillis()));
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class,
                            ex);
                    log.error(ex);
                }
                System.exit(0);
            } else {
                user.setLoginCollectionName(collection.getCollectionName());
                user.setLoginDisciplineName(discipline.getName());
                try {
                    session.beginTransaction();
                    session.saveOrUpdate(user);
                    session.commit();

                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class,
                            ex);
                    log.error(ex);
                }
            }
        }

        DisciplineType disciplineType = DisciplineType.getDiscipline(discipline.getType());
        String folderName = disciplineType.getFolder();

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection / UserType / isPersonal
        // For example: rods/fish/fish/manager / true (meaning the usr's personal space)
        //---------------------------------------------------------
        String title = getResourceString(L10N + "" + PERSONALDIR);
        SpAppResourceDir appResDir = getAppResDir(session, user, discipline, collection, userType, true, title,
                true);
        //System.out.println("PERSONALDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());  
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(PERSONALDIR, appResDir);
        viewSetMgrHash.put(PERSONALDIR, new Pair<String, File>(null, null));

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection / UserType
        // For example: rods/fish/fish/manager
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + USERTYPEDIR);
        appResDir = getAppResDir(session, user, discipline, collection, userType, false, title, true);
        //System.out.println("USERTYPEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        File dir = XMLHelper.getConfigDir(folderName + File.separator + userType);
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(USERTYPEDIR, appResDir, disciplineStr + " " + userType, dir); //$NON-NLS-1$
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(USERTYPEDIR, appResDir);

        //---------------------------------------------------------
        // This is the Full Path User / Discipline / Collection
        // For example: rods/fish/fish
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + COLLECTIONDIR);
        appResDir = getAppResDir(session, user, discipline, collection, null, false, title, true);
        //System.out.println("COLLECTIONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(COLLECTIONDIR, appResDir);
        viewSetMgrHash.put(COLLECTIONDIR, new Pair<String, File>(null, null));

        //---------------------------------------------------------
        // This is the Full Path User / Discipline
        // For example: rods/fish
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + DISCPLINEDIR);
        appResDir = getAppResDir(session, user, discipline, null, null, false, title, true);
        //System.out.println("DISCPLINEDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        dir = XMLHelper.getConfigDir(folderName);
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(DISCPLINEDIR, appResDir, disciplineStr, dir);
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(DISCPLINEDIR, appResDir);

        //---------------------------------------------------------
        // Common Views 
        //---------------------------------------------------------
        title = getResourceString(L10N + "" + COMMONDIR);
        appResDir = getAppResDir(session, user, null, null, COMMONDIR, false, title, true);
        //System.out.println("COMMONDIR Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
        dir = XMLHelper.getConfigDir("common"); //$NON-NLS-1$
        if (dir.exists()) {
            mergeAppResourceDirFromDiskDir(COMMONDIR, appResDir, COMMONDIR, dir);
            appResDir.setUserType(COMMONDIR);
        }
        spAppResourceList.add(appResDir);
        spAppResourceHash.put(COMMONDIR, appResDir);

        //---------------------------------------------------------
        // BackStop
        //---------------------------------------------------------
        String backStopStr = "backstop";
        dir = XMLHelper.getConfigDir(backStopStr); //$NON-NLS-1$
        if (dir.exists()) {
            appResDir = createAppResourceDefFromDir(BACKSTOPDIR, dir); //$NON-NLS-1$
            //System.out.println("appResDir Dir: "+appResDir.getId()+", UT: "+appResDir.getUserType()+",  IsPers: "+appResDir.getIsPersonal()+", Disp: "+appResDir.getDisciplineType());
            appResDir.setUserType(BACKSTOPDIR); //$NON-NLS-1$
            appResDir.setTitle(getResourceString(L10N + "" + BACKSTOPDIR)); //$NON-NLS-1$

            spAppResourceList.add(appResDir);
            spAppResourceHash.put(BACKSTOPDIR, appResDir);
        }

        if (isFirstTime) {
            SpecifyAppPrefs.initialPrefs();
        }

        closeSession();
        session = null;

        if (isFirstTime) {
            FixDBAfterLogin.fixDefaultDates();

            // Reset the form system because 
            // 'fixDefaultDates' loads all the forms.
            FormDevHelper.clearErrors();
            viewSetHash.clear();
            lastLoadTime = 0;

            // Now notify everyone
            if (prevDisciplineId != -1) {
                CommandDispatcher.dispatch(new CommandAction("Discipline", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (prevCollectionId != -1) {
                CommandDispatcher.dispatch(new CommandAction("Collection", "Changed")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        // We must check here before we load the schema
        checkForInitialFormats();

        session = openSession();

        // Now load the Schema, but make sure the Discipline has a localization.
        // for the current locale.
        //
        // Bug Fix 9167 - 04/01/2013 - Must always redo the Schema because any formatters at the collection level
        // otherwise will not get set
        //
        if (UIFieldFormatterMgr.isInitialized()) {
            UIFieldFormatterMgr.getInstance().shutdown();
            UIFieldFormatterMgr.getInstance().reset();
        }

        int disciplineId = getClassObject(Discipline.class).getDisciplineId();
        if (disciplineId != prevDisciplineId) {
            Locale engLocale = null;
            Locale fndLocale = null;
            Locale currLocale = SchemaI18NService.getCurrentLocale();
            List<Locale> locales = SchemaI18NService.getInstance()
                    .getLocalesFromData(SpLocaleContainer.CORE_SCHEMA, disciplineId);
            for (Locale locale : locales) {
                if (locale.equals(currLocale)) {
                    fndLocale = currLocale;
                }
                if (locale.getLanguage().equals("en")) {
                    engLocale = currLocale;
                }
            }
            if (fndLocale == null) {
                if (engLocale != null) {
                    fndLocale = engLocale;

                } else if (locales.size() > 0) {
                    fndLocale = locales.get(0);

                } else {
                    currentStatus = CONTEXT_STATUS.Error;
                    String msg = "Specify was unable to a Locale in the Schema Config for this discipline.\nPlease contact Specify support immediately.";
                    UIRegistry.showError(msg);
                    AppPreferences.shutdownAllPrefs();
                    DataProviderFactory.getInstance().shutdown();
                    DBConnection.shutdown();
                    System.exit(0);
                    return currentStatus;
                }

                fndLocale = engLocale != null ? engLocale : locales.get(0);
                SchemaI18NService.setCurrentLocale(fndLocale);
                Locale.setDefault(fndLocale);
                UIRegistry.displayErrorDlgLocalized(L10N + "NO_LOCALE", discipline.getName(),
                        currLocale.getDisplayName(), fndLocale.getDisplayName());
            }
            SchemaI18NService.getInstance().loadWithLocale(SpLocaleContainer.CORE_SCHEMA, disciplineId,
                    DBTableIdMgr.getInstance(), Locale.getDefault());
        }

        //setUpCatNumAccessionFormatters(getClassObject(Institution.class), collection);

        // We close the session here so all SpAppResourceDir get unattached to hibernate
        // because UIFieldFormatterMgr and loading views all need a session
        // and we don't want to reuse it and get a double session
        closeSession();
        session = null;

        if (isFirstTime) {
            for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
                ti.setPermissions(SecurityMgr.getInstance().getPermission("DO." + ti.getName().toLowerCase()));
            }

            // Here is where you turn on View/Viewdef re-use.
            /*if (true)
            {
            boolean cacheDoVerify = ViewLoader.isDoFieldVerification();
            ViewLoader.setDoFieldVerification(false);
                    
            UIFieldFormatterMgr.getInstance();
                    
            ViewLoader.setDoFieldVerification(cacheDoVerify);
            }*/

            RegisterSpecify.register(false, 0);
        }

        return currentStatus = CONTEXT_STATUS.OK;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex);
        ex.printStackTrace();

    } finally {
        if (session != null) {
            closeSession();
        }
    }

    showLocalizedError(L10N + "CRITICAL_LOGIN_ERR"); //$NON-NLS-1$
    System.exit(0);
    return null;
}

From source file:org.yccheok.jstock.gui.MainFrame.java

/**
 * @param args the command line arguments
 *//*from  ww  w  .j  a v a 2  s  .c  o  m*/
public static void main(String args[]) {
    if (false == AppLock.lock()) {
        final int choice = JOptionPane.showOptionDialog(null,
                MessagesBundle.getString("warning_message_running_2_jstock"),
                MessagesBundle.getString("warning_title_running_2_jstock"), JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null,
                new String[] { MessagesBundle.getString("yes_button_running_2_jstock"),
                        MessagesBundle.getString("no_button_running_2_jstock") },
                MessagesBundle.getString("no_button_running_2_jstock"));
        if (choice != JOptionPane.YES_OPTION) {
            System.exit(0);
            return;
        }
    }

    // As ProxyDetector is affected by system properties
    // http.proxyHost, we are forced to initialized ProxyDetector right here,
    // before we manually change the system properties according to
    // JStockOptions.
    ProxyDetector.getInstance();

    Utils.setDefaultLookAndFeel();

    final String[] _args = args;

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            final MainFrame mainFrame = MainFrame.getInstance();
            final JStockOptions jStockOptions = getJStockOptions(_args);
            // This global effect, should just come before anything else, 
            // after we get an instance of JStockOptions.
            Locale.setDefault(jStockOptions.getLocale());

            // We need to first assign jStockOptions to mainFrame, as during
            // Utils.migrateXMLToCSVPortfolios, we will be accessing mainFrame's
            // jStockOptions.
            mainFrame.initJStockOptions(jStockOptions);

            mainFrame.init();
            mainFrame.setVisible(true);
            mainFrame.updateDividerLocation();
            mainFrame.requestFocusOnJComboBox();
        }
    });
}

From source file:ru.apertum.qsystem.client.forms.FReception.java

/**
 * @param args the command line arguments
 *//* ww  w .j  a  v  a 2s. co  m*/
public static void main(String args[]) {
    QLog.initial(args, 2);
    Locale.setDefault(Locales.getInstance().getLangCurrent());
    Uses.showSplash();
    //     plugins
    if (QLog.l().isPlaginable()) {
        Uses.loadPlugins("./plugins/");
    }

    try {
        config = new PropertiesConfiguration("config/reception.properties");
    } catch (ConfigurationException ex) {
        throw new ClientException(ex);
    }

    final IClientNetProperty netProperty = new ClientNetProperty(args);
    // ?    ? .
    //    main   ?   ,
    //  ?     15-20 ?? java.net.SocketException: Malformed reply from SOCKS server  
    /*
     Socket skt = null;
     try {
     skt = new Socket(netProperty.getAddress(), 61111);
     skt.close();
     } catch (IOException ex) {
     }
     */

    final boolean res;
    try {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                    .getInstalledLookAndFeels()) {
                //System.out.println(info.getName());
                /*Metal Nimbus CDE/Motif Windows   Windows Classic  */
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException ex) {
        }
        fReception = new FReception(netProperty);
        Uses.setLocation(fReception);
        res = fReception.load();
    } catch (Exception ex) {
        Uses.closeSplash();
        throw new ClientException(ex);
    }

    // ? ,  ?  ? .
    //  ??? 
    for (final IStartReception event : ServiceLoader.load(IStartReception.class)) {
        QLog.l().logger()
                .info(" SPI ??. ?: " + event.getDescription());
        try {
            new Thread(() -> {
                event.start(fReception);
            }).start();
        } catch (Throwable tr) {
            QLog.l().logger().error(
                    " SPI ?? ?? . ?: "
                            + tr);
        }
    }

    Uses.closeSplash();
    if (res) {
        java.awt.EventQueue.invokeLater(() -> {
            try {
                fReception.setVisible(true);
            } catch (Exception ex) {
                Uses.closeSplash();
                throw new ClientException(ex);
            } finally {
                Uses.closeSplash();
            }
        });
    } else {
        System.exit(13);
    }
}

From source file:org.yccheok.jstock.gui.JStock.java

/**
 * @param args the command line arguments
 */// ww  w.ja  v  a  2s .co m
public static void main(String args[]) {
    /***********************************************************************
     * UI Manager initialization via JStockOptions.
     **********************************************************************/
    final JStockOptions jStockOptions = getJStockOptionsViaXML();

    // OSX menu bar at top.
    if (Utils.isMacOSX()) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("apple.awt.brushMetalLook", "true");
    }

    boolean uiManagerLookAndFeelSuccess = false;
    try {
        String lookNFeel = jStockOptions.getLooknFeel();
        if (null != lookNFeel) {
            UIManager.setLookAndFeel(lookNFeel);
            uiManagerLookAndFeelSuccess = true;
        }
    } catch (java.lang.ClassNotFoundException | java.lang.InstantiationException
            | java.lang.IllegalAccessException | javax.swing.UnsupportedLookAndFeelException exp) {
        log.error(null, exp);
    }

    if (!uiManagerLookAndFeelSuccess) {
        String className = Utils.setDefaultLookAndFeel();
        if (null != className) {
            final String lookNFeel = jStockOptions.getLooknFeel();
            // When jStockOptions.getLookNFeel returns null, it means we wish
            // to use system default value. Hence, don't overwrite the null value,
            // so that we can use the same jStockOptions, across different
            // platforms.
            if (lookNFeel != null) {
                jStockOptions.setLooknFeel(className);
            }
        }
    }

    /***********************************************************************
     * Ensure correct localization.
     **********************************************************************/
    // This global effect, should just come before anything else, 
    // after we get an instance of JStockOptions.
    Locale.setDefault(jStockOptions.getLocale());

    /***********************************************************************
     * Single application instance enforcement.
     **********************************************************************/
    if (false == AppLock.lock()) {
        final int choice = JOptionPane.showOptionDialog(null,
                MessagesBundle.getString("warning_message_running_2_jstock"),
                MessagesBundle.getString("warning_title_running_2_jstock"), JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null,
                new String[] { MessagesBundle.getString("yes_button_running_2_jstock"),
                        MessagesBundle.getString("no_button_running_2_jstock") },
                MessagesBundle.getString("no_button_running_2_jstock"));
        if (choice != JOptionPane.YES_OPTION) {
            System.exit(0);
            return;
        }
    }

    // Avoid "JavaFX IllegalStateException when disposing JFXPanel in Swing"
    // http://stackoverflow.com/questions/16867120/javafx-illegalstateexception-when-disposing-jfxpanel-in-swing
    Platform.setImplicitExit(false);

    // As ProxyDetector is affected by system properties
    // http.proxyHost, we are forced to initialized ProxyDetector right here,
    // before we manually change the system properties according to
    // JStockOptions.
    ProxyDetector.getInstance();

    /***********************************************************************
     * Apply large font if possible.
     **********************************************************************/
    if (jStockOptions.useLargeFont()) {
        java.util.Enumeration keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
                javax.swing.plaf.FontUIResource fr = (javax.swing.plaf.FontUIResource) value;
                UIManager.put(key, new javax.swing.plaf.FontUIResource(
                        fr.deriveFont((float) fr.getSize2D() * (float) Constants.FONT_ENLARGE_FACTOR)));
            }
        }
    }

    /***********************************************************************
     * GA tracking.
     **********************************************************************/
    GA.trackAsynchronously("main");

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            final JStock mainFrame = JStock.instance();

            // We need to first assign jStockOptions to mainFrame, as during
            // Utils.migrateXMLToCSVPortfolios, we will be accessing mainFrame's
            // jStockOptions.
            mainFrame.initJStockOptions(jStockOptions);

            mainFrame.init();
            mainFrame.setVisible(true);
            mainFrame.updateDividerLocation();
            mainFrame.requestFocusOnJComboBox();
        }
    });
}

From source file:com.androzic.Androzic.java

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (locale != null) {
        newConfig.locale = locale;/*from   w w  w .ja  v  a2 s  . com*/
        Locale.setDefault(locale);
        getBaseContext().getResources().updateConfiguration(newConfig,
                getBaseContext().getResources().getDisplayMetrics());
    }
}

From source file:com.androzic.Androzic.java

public void onCreateEx() {
    try {//from   w  w w  .  ja  va  2 s.c o m
        (new File(Environment.getExternalStorageDirectory(), WordManager.FOLDER)).mkdirs();
        (new File(Environment.getExternalStorageDirectory(), WordManager.FOLDER + "/ghiam")).mkdirs();
    } catch (Throwable e) {
    }

    if (initialized)
        return;

    AndroidGraphicFactory.createInstance(this);
    try {
        OzfDecoder.useNativeCalls();
    } catch (UnsatisfiedLinkError e) {
        Toast.makeText(Androzic.this, "Failed to initialize native library: " + e.getMessage(),
                Toast.LENGTH_LONG).show();
    }

    Resources resources = getResources();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    Configuration config = resources.getConfiguration();

    renderingThread = new HandlerThread("RenderingThread");
    renderingThread.start();

    longOperationsThread = new HandlerThread("LongOperationsThread");
    longOperationsThread.setPriority(Thread.MIN_PRIORITY);
    longOperationsThread.start();

    uiHandler = new Handler();
    mapsHandler = new Handler(longOperationsThread.getLooper());

    // We silently initialize data uri to let location service restart after crash
    File datadir = new File(
            settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory()
                    + File.separator + resources.getString(R.string.def_folder_data)));
    setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());

    setInstance(this);

    String intentToCheck = "com.androzic.donate";
    String myPackageName = getPackageName();
    PackageManager pm = getPackageManager();
    PackageInfo pi;
    try {
        pi = pm.getPackageInfo(intentToCheck, 0);
        isPaid = (pm.checkSignatures(myPackageName, pi.packageName) == PackageManager.SIGNATURE_MATCH);
    } catch (NameNotFoundException e) {
        //         e.printStackTrace();
    }

    File sdcard = Environment.getExternalStorageDirectory();
    Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this, sdcard.getAbsolutePath()));

    DisplayMetrics displayMetrics = new DisplayMetrics();

    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    if (wm != null) {
        wm.getDefaultDisplay().getMetrics(displayMetrics);
    } else {
        displayMetrics.setTo(resources.getDisplayMetrics());
    }
    BaseMap.viewportWidth = displayMetrics.widthPixels;
    BaseMap.viewportHeight = displayMetrics.heightPixels;

    charset = settings.getString(getString(R.string.pref_charset), "UTF-8");
    String lang = settings.getString(getString(R.string.pref_locale), "");
    if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
        locale = new Locale(lang);
        Locale.setDefault(locale);
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }

    magInterval = resources.getInteger(R.integer.def_maginterval) * 1000;

    overlayManager = new OverlayManager(longOperationsThread.getLooper());
    TooltipManager.initialize(this);

    onSharedPreferenceChanged(settings, getString(R.string.pref_unitcoordinate));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitdistance));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitspeed));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitelevation));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitangle));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitanglemagnetic));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitprecision));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitsunrise));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapadjacent));
    onSharedPreferenceChanged(settings, getString(R.string.pref_vectormap_textscale));
    onSharedPreferenceChanged(settings, getString(R.string.pref_onlinemapprescalefactor));
    onSharedPreferenceChanged(settings, getString(R.string.pref_onlinemapexpiration));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapcropborder));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapdrawborder));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showwaypoints));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showcurrenttrack));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showaccuracy));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showdistance_int));

    settings.registerOnSharedPreferenceChangeListener(this);

    initialized = true;
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * Reads Local Preferences for the Locale setting.
 *///from  w w  w  . j av a 2  s  . com
public static void adjustLocaleFromPrefs() {
    String language = AppPreferences.getLocalPrefs().get("locale.lang", null); //$NON-NLS-1$
    if (language != null) {
        String country = AppPreferences.getLocalPrefs().get("locale.country", ""); //$NON-NLS-1$
        String variant = AppPreferences.getLocalPrefs().get("locale.var", ""); //$NON-NLS-1$

        Locale prefLocale = new Locale(language, country, variant);

        Locale.setDefault(prefLocale);
        UIRegistry.setResourceLocale(prefLocale);
    }

    try {
        ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$

    } catch (MissingResourceException ex) {
        Locale.setDefault(Locale.ENGLISH);
        UIRegistry.setResourceLocale(Locale.ENGLISH);
    }
}

From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java

public static void init() {
      if (!init) {
          init = true;//from   w  ww.  ja  v a 2  s  .c  o  m
          instance = LuckyApp.getInstance();
          if (firstrun == null) {
              firstrun = Boolean.valueOf(true);
          }
          luckyPackage = LuckyApp.getInstance().getApplicationInfo().packageName;
          startUnderRoot = Boolean.valueOf(false);
          api = Build.VERSION.SDK_INT;
      }
      try {
          versionCodeLocal = getPkgMng().getPackageInfo(LuckyApp.getInstance().getPackageName(), 0).versionCode;
          version = getPkgMng().getPackageInfo(LuckyApp.getInstance().getPackageName(), 0).versionName;
          System.out.println("LuckyPatcher " + version + ": Application Start!");
          if (getConfig().getBoolean("fast_start", false)) {
              fast_start = true;
          }
          localObject2 = getConfig().getString("force_language", "default");
      } catch (Exception localException2) {
          try {
              if (((String) localObject2).equals("default")) {
                  localObject1 = Resources.getSystem().getConfiguration().locale;
                  Locale.setDefault(Locale.getDefault());
                  localObject2 = new Configuration();
                  ((Configuration) localObject2).locale = ((Locale) localObject1);
                  LuckyApp.getInstance().getResources().updateConfiguration((Configuration) localObject2,
                          LuckyApp.getInstance().getResources().getDisplayMetrics());
                  boot_pat = new ArrayList();
              }
          } catch (Exception localException2) {
              try {
                  for (;;) {
                      Object localObject2;
                      toolfilesdir = LuckyApp.getInstance().getFilesDir().getAbsolutePath();
                      supath = LuckyApp.getInstance().getPackageCodePath();
                      int i = getConfig().getInt("root_force", 0);
                      if ((i == 0) && ((new File("/system/bin/su").exists())
                              || (new File("/system/xbin/su").exists()) || (new File("/su/bin/su").exists()))) {
                          su = true;
                      }
                      if (i == 1) {
                          su = true;
                      }
                      if (i == 2) {
                          su = false;
                      }
                      Object localObject1 = "";
                      extStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();
                      basepath = extStorageDirectory + "/LuckyPatcher";
                      try {
                          if (api > 18) {
                              basepath = LuckyApp.getInstance().getExternalFilesDir("LuckyPatcher")
                                      .getAbsolutePath();
                          }
                          basepath = extStorageDirectory + "/LuckyPatcher";
                          if (getConfig().getBoolean("manual_path", false)) {
                              basepath = getConfig().getString("basepath", basepath);
                          }
                          if (new File("/system/bin/dalvikvm").exists()) {
                              localObject1 = "/system/bin/dalvikvm";
                          }
                          if (new File("/system/bin/dalvikvm32").exists()) {
                              localObject1 = "/system/bin/dalvikvm32";
                          }
                          localObject2 = localObject1;
                          if (((String) localObject1).equals("")) {
                              localObject2 = localObject1;
                              if (su) {
                                  localFile = new File(LuckyApp.getInstance().getFilesDir() + "/dalvikvm");
                                  if (localFile.exists()) {
                                      break label1151;
                                  }
                                  localObject2 = localObject1;
                                  if (Utils.getRawToFile(2131099654, localFile)) {
                                      Utils.run_all("chmod 777 " + localFile.getAbsolutePath());
                                      Utils.run_all("chown 0.0 " + localFile.getAbsolutePath());
                                      Utils.run_all("chown 0:0 " + localFile.getAbsolutePath());
                                      localObject2 = localFile.getAbsolutePath();
                                  }
                              }
                          }
                          dalvikruncommand = (String) localObject2 + " -Xbootclasspath:"
                                  + System.getenv("BOOTCLASSPATH") + " -Xverify:none -Xdexopt:none -cp "
                                  + LuckyApp.getInstance().getPackageCodePath() + " com.chelpus.root.utils";
                          dalvikruncommandWithFramework = (String) localObject2 + " -Xbootclasspath:"
                                  + System.getenv("BOOTCLASSPATH") + " -Xverify:none -Xdexopt:none -cp "
                                  + LuckyApp.getInstance().getPackageCodePath()
                                  + " com.android.internal.util.WithFramework" + " com.chelpus.root.utils";
                          if ((runtime.equals("")) || (runtime == null)) {
                              localObject1 = "UNKNOWN";
                          }
                          try {
                              localObject2 = Utils.checkRuntimeFromCache(
                                      getPkgMng().getPackageInfo(getInstance().getPackageName(),
                                              0).applicationInfo.sourceDir);
                              localObject1 = localObject2;
                          } catch (PackageManager.NameNotFoundException localNameNotFoundException) {
                              for (;;) {
                                  Locale localLocale;
                                  String str1;
                                  localNameNotFoundException.printStackTrace();
                                  continue;
                                  new Thread(new Runnable() {
                                      public void run() {
                                          Utils.run_all("mkdir /data/lp");
                                          Utils.run_all("chmod 777 /data/lp");
                                          if (new Utils("").cmdRoot(new String[] { "getenforce" }).toLowerCase()
                                                  .contains("enforcing")) {
                                              listAppsFragment.selinux = "enforce";
                                          }
                                          Utils.save_text_to_file(this.val$link_to_utils,
                                                  listAppsFragment.toolfilesdir + "%chelpus%"
                                                          + listAppsFragment.api + "%chelpus%"
                                                          + listAppsFragment.runtime + "%chelpus%"
                                                          + listAppsFragment.selinux);
                                          Utils.run_all("chmod 777 /data/lp/lp_utils");
                                          Utils.initXposedParam();
                                      }
                                  }).start();
                              }
                          }
                          System.out.println("Runtime:" + (String) localObject1);
                          runtime = (String) localObject1;
                          if ((su) && (!new File("/data/lp/lp_utils").exists())) {
                              System.out.println("Tools not found in /data. Try create.");
                              localObject1 = new File("/data/lp/lp_utils");
                              if (!((File) localObject1).exists()) {
                              }
                          } else {
                              days = getConfig().getInt("days_on_up", 1);
                              getLaunchIntent();
                              return;
                              localException1 = localException1;
                              localException1.printStackTrace();
                              continue;
                              localLocale = null;
                              localObject2 = ((String) localObject2).split("_");
                              if (localObject2.length == 1) {
                                  localLocale = new Locale(localObject2[0]);
                              }
                              if (localObject2.length == 2) {
                                  localLocale = new Locale(localObject2[0], localObject2[1], "");
                                  if (localObject2[1].equals("rBR")) {
                                      localLocale = new Locale(localObject2[0], "BR");
                                  }
                              }
                              if (localObject2.length == 3) {
                                  localLocale = new Locale(localObject2[0], localObject2[1], localObject2[2]);
                              }
                              Locale.setDefault(localLocale);
                              localObject2 = new Configuration();
                              ((Configuration) localObject2).locale = localLocale;
                              LuckyApp.getInstance().getResources().updateConfiguration(
                                      (Configuration) localObject2,
                                      LuckyApp.getInstance().getResources().getDisplayMetrics());
                              continue;
                              localException2 = localException2;
                              localException2.printStackTrace();
                          }
                      } catch (Exception localException4) {
                          for (;;) {
                              File localFile;
                              localException4.printStackTrace();
                              new File(extStorageDirectory + "/Android/data/" + luckyPackage
                                      + "/files/LuckyPatcher").mkdirs();
                              basepath = extStorageDirectory + "/Android/data/" + luckyPackage
                                      + "/files/LuckyPatcher";
                              continue;
                              label1151: str1 = localFile.getAbsolutePath();
                              Utils.run_all("chmod 777 " + localFile.getAbsolutePath());
                              Utils.run_all("chown 0.0 " + localFile.getAbsolutePath());
                              Utils.run_all("chown 0:0 " + localFile.getAbsolutePath());
                          }
                      }
                  }
              } catch (Exception localException3) {
                  for (;;) {
                  }
              }
          }
      }
  }

From source file:be.ibridge.kettle.spoon.Spoon.java

/**
 * This is the main procedure for Spoon.
 * /*w  w w.  java 2 s. co m*/
 * @param a Arguments are available in the "Get System Info" step.
 */
public static void main(String[] a) throws KettleException {
    EnvUtil.environmentInit();
    ArrayList args = new ArrayList();
    for (int i = 0; i < a.length; i++)
        args.add(a[i]);

    Display display = new Display();

    Splash splash = new Splash(display);

    StringBuffer optionRepname, optionUsername, optionPassword, optionJobname, optionTransname, optionFilename,
            optionDirname, optionLogfile, optionLoglevel;

    CommandLineOption options[] = new CommandLineOption[] {
            new CommandLineOption("rep", "Repository name", optionRepname = new StringBuffer()),
            new CommandLineOption("user", "Repository username", optionUsername = new StringBuffer()),
            new CommandLineOption("pass", "Repository password", optionPassword = new StringBuffer()),
            new CommandLineOption("job", "The name of the job to launch", optionJobname = new StringBuffer()),
            new CommandLineOption("trans", "The name of the transformation to launch",
                    optionTransname = new StringBuffer()),
            new CommandLineOption("dir", "The directory (don't forget the leading /)",
                    optionDirname = new StringBuffer()),
            new CommandLineOption("file", "The filename (Transformation in XML) to launch",
                    optionFilename = new StringBuffer()),
            new CommandLineOption("level",
                    "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)",
                    optionLoglevel = new StringBuffer()),
            new CommandLineOption("logfile", "The logging file to write to",
                    optionLogfile = new StringBuffer()),
            new CommandLineOption("log", "The logging file to write to (deprecated)",
                    optionLogfile = new StringBuffer(), false, true), };

    // Parse the options...
    CommandLineOption.parseArguments(args, options);

    String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null);
    String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null);
    String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null);

    if (!Const.isEmpty(kettleRepname))
        optionRepname = new StringBuffer(kettleRepname);
    if (!Const.isEmpty(kettleUsername))
        optionUsername = new StringBuffer(kettleUsername);
    if (!Const.isEmpty(kettlePassword))
        optionPassword = new StringBuffer(kettlePassword);

    // Before anything else, check the runtime version!!!
    String version = Const.JAVA_VERSION;
    if ("1.4".compareToIgnoreCase(version) > 0) {
        System.out.println("The System is running on Java version " + version);
        System.out.println("Unfortunately, it needs version 1.4 or higher to run.");
        return;
    }

    // Set default Locale:
    Locale.setDefault(Const.DEFAULT_LOCALE);

    LogWriter log;
    LogWriter.setConsoleAppenderDebug();
    if (Const.isEmpty(optionLogfile)) {
        log = LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC);
    } else {
        log = LogWriter.getInstance(optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC);
    }

    if (log.getRealFilename() != null)
        log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingToFile") + log.getRealFilename());//"Logging goes to "

    if (!Const.isEmpty(optionLoglevel)) {
        log.setLogLevel(optionLoglevel.toString());
        log.logBasic(APP_NAME, Messages.getString("Spoon.Log.LoggingAtLevel") + log.getLogLevelDesc());//"Logging is at level : "
    }

    /* Load the plugins etc.*/
    StepLoader stloader = StepLoader.getInstance();
    if (!stloader.read()) {
        log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorLoadingAndHaltSystem"));//Error loading steps & plugins... halting Spoon!
        return;
    }

    /* Load the plugins etc. we need to load jobentry*/
    JobEntryLoader jeloader = JobEntryLoader.getInstance();
    if (!jeloader.read()) {
        log.logError("Spoon", "Error loading job entries & plugins... halting Kitchen!");
        return;
    }

    final Spoon spoon = new Spoon(log, display, null);
    staticSpoon = spoon;
    spoon.setDestroy(true);
    spoon.setArguments((String[]) args.toArray(new String[args.size()]));

    log.logBasic(APP_NAME, Messages.getString("Spoon.Log.MainWindowCreated"));//Main window is created.

    RepositoryMeta repositoryMeta = null;
    UserInfo userinfo = null;

    if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename)
            && spoon.props.showRepositoriesDialogAtStartup()) {
        log.logBasic(APP_NAME, Messages.getString("Spoon.Log.AskingForRepository"));//"Asking for repository"

        int perms[] = new int[] { PermissionMeta.TYPE_PERMISSION_TRANSFORMATION,
                PermissionMeta.TYPE_PERMISSION_JOB };
        splash.hide();
        RepositoriesDialog rd = new RepositoriesDialog(spoon.disp, perms,
                Messages.getString("Spoon.Application.Name"));//"Spoon"
        if (rd.open()) {
            repositoryMeta = rd.getRepository();
            userinfo = rd.getUser();
            if (!userinfo.useTransformations()) {
                MessageBox mb = new MessageBox(spoon.shell, SWT.OK | SWT.ICON_ERROR);
                mb.setMessage(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Message"));//"Sorry, this repository user can't work with transformations from the repository."
                mb.setText(Messages.getString("Spoon.Dialog.RepositoryUserCannotWork.Title"));//"Error!"
                mb.open();

                userinfo = null;
                repositoryMeta = null;
            }
        } else {
            // Exit point: user pressed CANCEL!
            if (rd.isCancelled()) {
                splash.dispose();
                spoon.quitFile();
                return;
            }
        }
    }

    try {
        // Read kettle transformation specified on command-line?
        if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) {
            if (!Const.isEmpty(optionRepname)) {
                RepositoriesMeta repsinfo = new RepositoriesMeta(log);
                if (repsinfo.readData()) {
                    repositoryMeta = repsinfo.findRepository(optionRepname.toString());
                    if (repositoryMeta != null) {
                        // Define and connect to the repository...
                        spoon.rep = new Repository(log, repositoryMeta, userinfo);
                        if (spoon.rep.connect(Messages.getString("Spoon.Application.Name")))//"Spoon"
                        {
                            if (Const.isEmpty(optionDirname))
                                optionDirname = new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR);

                            // Check username, password
                            spoon.rep.userinfo = new UserInfo(spoon.rep, optionUsername.toString(),
                                    optionPassword.toString());

                            if (spoon.rep.userinfo.getID() > 0) {
                                // Options /file, /job and /trans are mutually exclusive
                                int t = (Const.isEmpty(optionFilename) ? 0 : 1)
                                        + (Const.isEmpty(optionJobname) ? 0 : 1)
                                        + (Const.isEmpty(optionTransname) ? 0 : 1);
                                if (t > 1) {
                                    log.logError(APP_NAME, Messages.getString("Spoon.Log.MutuallyExcusive")); // "More then one mutually exclusive options /file, /job and /trans are specified."                                    
                                } else if (t == 1) {
                                    if (!Const.isEmpty(optionFilename)) {
                                        spoon.openFile(optionFilename.toString(), false);
                                    } else {
                                        // OK, if we have a specified job or transformation, try to load it...
                                        // If not, keep the repository logged in.
                                        RepositoryDirectory repdir = spoon.rep.getDirectoryTree()
                                                .findDirectory(optionDirname.toString());
                                        if (repdir == null) {
                                            log.logError(APP_NAME, Messages.getString(
                                                    "Spoon.Log.UnableFindDirectory", optionDirname.toString())); //"Can't find directory ["+dirname+"] in the repository."
                                        } else {
                                            if (!Const.isEmpty(optionTransname)) {
                                                TransMeta transMeta = new TransMeta(spoon.rep,
                                                        optionTransname.toString(), repdir);
                                                transMeta.setFilename(optionRepname.toString());
                                                transMeta.clearChanged();
                                                spoon.addSpoonGraph(transMeta);
                                            } else {
                                                // Try to load a specified job if any
                                                JobMeta jobMeta = new JobMeta(log, spoon.rep,
                                                        optionJobname.toString(), repdir);
                                                jobMeta.setFilename(optionRepname.toString());
                                                jobMeta.clearChanged();
                                                spoon.addChefGraph(jobMeta);
                                            }
                                        }
                                    }
                                }
                            } else {
                                log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableVerifyUser"));//"Can't verify username and password."
                                spoon.rep.disconnect();
                                spoon.rep = null;
                            }
                        } else {
                            log.logError(APP_NAME, Messages.getString("Spoon.Log.UnableConnectToRepository"));//"Can't connect to the repository."
                        }
                    } else {
                        log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoryRrovided"));//"No repository provided, can't load transformation."
                    }
                } else {
                    log.logError(APP_NAME, Messages.getString("Spoon.Log.NoRepositoriesDefined"));//"No repositories defined on this system."
                }
            } else if (!Const.isEmpty(optionFilename)) {
                spoon.openFile(optionFilename.toString(), false);
            }
        } else // Normal operations, nothing on the commandline...
        {
            // Can we connect to the repository?
            if (repositoryMeta != null && userinfo != null) {
                spoon.rep = new Repository(log, repositoryMeta, userinfo);
                if (!spoon.rep.connect(Messages.getString("Spoon.Application.Name"))) //"Spoon"
                {
                    spoon.rep = null;
                }
            }

            if (spoon.props.openLastFile()) {
                log.logDetailed(APP_NAME, Messages.getString("Spoon.Log.TryingOpenLastUsedFile"));//"Trying to open the last file used."

                List lastUsedFiles = spoon.props.getLastUsedFiles();

                if (lastUsedFiles.size() > 0) {
                    LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(0);

                    spoon.loadLastUsedFile(lastUsedFile, repositoryMeta);
                }
            }
        }
    } catch (KettleException ke) {
        log.logError(APP_NAME, Messages.getString("Spoon.Log.ErrorOccurred") + Const.CR + ke.getMessage());//"An error occurred: "
        spoon.rep = null;
        // ke.printStackTrace();
    }

    spoon.open();

    splash.dispose();

    try {
        while (!spoon.isDisposed()) {
            if (!spoon.readAndDispatch())
                spoon.sleep();
        }
    } catch (Throwable e) {
        log.logError(APP_NAME,
                Messages.getString("Spoon.Log.UnexpectedErrorOccurred") + Const.CR + e.getMessage());//"An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! "
        e.printStackTrace();
    }
    spoon.dispose();

    log.logBasic(APP_NAME, APP_NAME + " " + Messages.getString("Spoon.Log.AppHasEnded"));//" has ended."

    // Close the logfile
    log.close();

    // Kill all remaining things in this VM!
    System.exit(0);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc//from w w  w . ja  v a2  s . co m
 */
public L10NManager getLocalizationManager() {
    if (l10n == null) {
        Locale l = Locale.getDefault();
        l10n = new L10NManager(l.getLanguage(), l.getCountry()) {
            public double parseDouble(String localeFormattedDecimal) {
                try {
                    return NumberFormat.getNumberInstance().parse(localeFormattedDecimal).doubleValue();
                } catch (ParseException err) {
                    return Double.parseDouble(localeFormattedDecimal);
                }
            }

            public String format(int number) {
                return NumberFormat.getNumberInstance().format(number);
            }

            public String format(double number) {
                return NumberFormat.getNumberInstance().format(number);
            }

            public String formatCurrency(double currency) {
                return NumberFormat.getCurrencyInstance().format(currency);
            }

            public String formatDateLongStyle(Date d) {
                return DateFormat.getDateInstance(DateFormat.LONG).format(d);
            }

            public String formatDateShortStyle(Date d) {
                return DateFormat.getDateInstance(DateFormat.SHORT).format(d);
            }

            public String formatDateTime(Date d) {
                return DateFormat.getDateTimeInstance().format(d);
            }

            public String formatDateTimeMedium(Date d) {
                DateFormat dd = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
                return dd.format(d);
            }

            public String formatDateTimeShort(Date d) {
                DateFormat dd = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
                return dd.format(d);
            }

            public String getCurrencySymbol() {
                return NumberFormat.getInstance().getCurrency().getSymbol();
            }

            public void setLocale(String locale, String language) {
                super.setLocale(locale, language);
                Locale l = new Locale(language, locale);
                Locale.setDefault(l);
            }
        };
    }
    return l10n;
}